#$ -S /bin/bash
#$ -cwd

cd ~/bzou
while :; do
  echo -e "SRX\tgenome\tstart\tjob_state\tfastq\tbmap\tmapsum\tmptc\tcalcoverage\tmethexport\tbmap_sum\thypohyper\tbw\tnum_reads\tmapping_rate_1\tmapping_rate_2\tmethyl_rate_cpg_total\tmethyl_rate_cpg_lambda\tlow_methyl_region\tpartial_methyl_region\thigh_methyl_region\tcoverage\tend\tduration (h)" > ~/bzou/log_repo.tsv
  for log in `ls | grep "RX" | grep "log.txt"`; do
    echo -e "$(echo $log | cut -d"." -f2)\t$(echo $log | cut -d"." -f1)\t$(cat $log | grep "Started at" | cut -f2)\t$(qstat | grep $(cat $log | grep "Job ID" | awk -F" = " '{print $2}') | awk '{print $5}')\t`cat $log | grep -c "fastq に変換しました"`\t`cat $log | grep "=-=-=" | cut -f2 | awk -F"\t" '{printf "%s\t", $1}'`"
  done | awk -F"\t" -v OFS="\t" '{gsub("1", "OK",$5);gsub("0","",$5);if ($4 == "") $4="end"; print $0}' >> ~/bzou/log_repo.tsv
  cat ~/bzou/log_repo.tsv | cut -f1-24 | awk -F"\t" -v OFS="\t" '$4 == "end" {print $1,$2}' > ~/bzou/finished.tsv
  
  for i in `cat finished.tsv | cut -f1 | awk '!a[$0]++'`; do
    j=`cat finished.tsv | grep -c $i`
    if [ $j = 2 ]; then
      echo $i
    fi
  done > finished_srx.tsv
  
  cat ~/bzou/srx_list_temp | awk -F"\t" -v OFS="\t" '
    BEGIN {
      while ("cat /home/okishinya/bzou/finished_srx.tsv" | getline) end[$1]++
      while ("cat /home/okishinya/bzou/log_repo.tsv" | getline) run[$1]++
    }{
      if (length(end[$1]) > 0) {
        print $0, "finished"
      }
      else if (length(run[$1]) > 0) {
        print $0, "running"
      }
      else {
        print $0
      }
    }' > ~/bzou/srx_list.tsv
  sleep `cat ~/bzou/preference.txt | grep log_sleep | cut -f2`
done
