#!/bin/sh
#$ -S /bin/sh

# --------------------------------
# $1 ゲノム (例 "hg19 mm9 ce10 dm3 sacCer3")
# $2 projectDir (例 chipome_ver3)
# $3 qVal (例 "05 10 20")
# $4 メタデータ (例 NCBI_SRA_Metadata_Full_20150101.metadata.tab)

# qsub -l d_rt=1440:00:00 -l s_rt=1440:00:00 chipatlas/sh/一時スクリプト/controller_hg38etc.sh "hg38 mm10 ce11 dm6" chipatlas "05 10 20" chipatlas/lib/metadata/NCBI_SRA_Metadata_Full_20200328.metadata.tab
# --------------------------------
GENOME="$1"
projectDir=$2
QVAL="$3"
metaData=$4
nslot=`cat $projectDir/sh/preferences.txt |awk -F '\t' '{if ($1 == "nSlotForSrT") printf "%s", $2}'`
Sz=0
prevT=`date +%s`
intT=21600
HDsize=$(lfs quota -u `pwd -P| cut -d/ -f5` /`pwd -P| cut -d/ -f2`| tail -n1| awk '{printf "%d", $4/1000000000}')
let HDsize=$HDsize-2


qsub -ar 306 -l d_rt=576:00:00 -l s_rt=576:00:00 $projectDir/sh/TimeCourse.sh $projectDir "$GENOME"
# qsub -l d_rt=1440:00:00 -l s_rt=1440:00:00 -o libPrepForAnal.log.txt -e libPrepForAnal.log.txt -l s_vmem=30G -l mem_req=30G $projectDir/sh/libPrepForAnal.sh $projectDir # Colo や Target のためのライブラリ

for Genome in `echo $GENOME`; do
  # Organism Name の取得
  Org=`cat $projectDir/sh/preferences.txt |awk -F '\t' -v G=$Genome '{
    if ($1 == "Genome") {
      split($2, all, " ")
      for (key in all) {
        split (all[key], arr, "=")
        if (arr[1] ~ G) {
          gsub ("_", " ", arr[2])
          printf "%s", arr[2]
        }
      }
    }
  }'`

  # ラン用のメタデータを作製
  cat $metaData | awk -v ORG="$Org" -F '\t' '{
    if ($4  == "ChIP-Seq" || $4  == "DNase-Hypersensitivity")\
    if ($5  == "GENOMIC")\
    if ($6  == "ChIP" || $6  == "DNase")\
    if ($11 ~  "Illumina" || $11 ~  "NextSeq" || $11 ~  "HiSeq")\
    if ($17 ~  ORG)\
      print
  }' > $projectDir/results/$Genome/metadataForRun.txt
done
    # cellTissueList/$i.tab の例 ($1 数、$2 SRX、$3 細胞組織名、$4 略称)
    #    113 SRX319846       Primary_thioglycollate-elicited_peritoneal_macrophages  Primary_thioglycollate...
    #     96 SRX020259       Liver_tissue    Liver_tissue


line=0
# ここから本番
for Genome in `echo $GENOME`; do
  for SRX in `cat $projectDir/results/$Genome/metadataForRun.txt| cut -f1`; do
    Logfile="$projectDir/results/$Genome/log/$SRX.log.txt"
    awk -v Srx=$SRX '{if ($1 == Srx) print}' $projectDir/results/$Genome/metadataForRun.txt > $projectDir/results/$Genome/metadata/$SRX.meta.txt
    
    
    if [ $line -eq 0 ]; then
      Sz=$(lfs quota -u `pwd -P| cut -d/ -f5` /`pwd -P| cut -d/ -f2`| tail -n1| awk '{printf "%d", $2/1000000000}')
      while :; do
        LINE=`bin/arid| awk '
        BEGIN {
          srand("'$RANDOM'")
        } {
          num = ($3 * 2 - $2) / 4
          for (i=1; i<=num; i++) print rand() "\t" $0 "\t" num
        }'| sort -n| cut -f2-| tee arid.txt| wc -l`
        if [ $LINE -gt 0 ]; then
          break
        fi
      done
    fi
    
    let line=$line+1
    ar_id=`cat arid.txt| awk 'NR == '$line' {printf $1}'`
    
    while :; do
      if [ $Sz -lt $HDsize ]; then # HDD 空き容量が 2 TB 以上の時に submit する
        qsub -ar $ar_id -N "srT$Genome" -o $Logfile -e $Logfile -pe def_slot $nslot $projectDir/sh/sraTailor.sh $SRX $Genome $projectDir "$QVAL" g1
        if [ $LINE -eq $line ]; then
          line=0
        fi
        break
      fi
    done
    
    
  done
done
exit

=========================
qdeli
for Genome in ce11 dm6 hg38 mm10; do
  rm -rf chipatlas/results/$Genome
done
rm timecourse.chipatlas.tsv controller_hg38etc.sh.* TimeCourse.sh.*
for Genome in ce11 dm6 hg38 mm10; do
  mkdir chipatlas/results/$Genome
  mkdir chipatlas/results/$Genome/BigWig
  mkdir chipatlas/results/$Genome/log
  mkdir chipatlas/results/$Genome/summary
  mkdir chipatlas/results/$Genome/metadata
  mkdir chipatlas/results/$Genome/public
  for qval in `cat chipatlas/sh/preferences.txt |awk -F '\t' '{if ($1 == "qVal") print $2}'`; do
    mkdir chipatlas/results/$Genome/Bed$qval
    mkdir chipatlas/results/$Genome/Bed$qval/Bed
    mkdir chipatlas/results/$Genome/Bed$qval/BigBed
  done
done
qsub -ar 306 -l d_rt=576:00:00 -l s_rt=576:00:00 chipatlas/sh/一時スクリプト/controller_hg38etc.sh "hg38 ce11 mm10 dm6" chipatlas "05 10 20" chipatlas/lib/metadata/NCBI_SRA_Metadata_Full_20200328.metadata.tab

# 計算がエラーになる場合
#                     qstat     SRXディレクトリ     Bed/BigWig     log        summary      例
# (1) コアダンンプ      残らず     残る               できない        できる      できない      SRX328589 (hg19)
# (2) aspera エラー    残る       残る               できない        できる      できない      混雑状況によるため再現できない -> 再投入が必要
# (3) MACS2 エラー     残らず     残らず              できない        できる      できる       SRX211437 (sacCer3)
# (4) 時間切れ         残らず     残る                できない        できる      できない      SRX716883 (mm9)
# (5) MACS メモリ不足  残らず     残る                できる         できる       できない      DRX048524 (hg19)

# Aspera エラーの場合の再投入

projectDir=chipatlas
Genome=mm9
nslot="8-64"

for SRX in SRX814801 SRX810565 SRX258122 SRX1098159 SRX1098158 SRX1098157 SRX1098156; do
  QVAL="05 10 20"
  Logfile="$projectDir/results/$Genome/log/$SRX.log.txt"
  
  rm -f $Logfile
  rm -rf $projectDir/results/$Genome/$SRX
  
  qsub -N "srT$Genome" -o $Logfile -e $Logfile -pe def_slot $nslot $projectDir/sh/sraTailor.sh $SRX $Genome $projectDir "$QVAL"
done


# コアダンプで終了したもの => コア数を倍増して再解析
for SRX in `ll chipatlas/results/hg38/*/cor*| cut -d '/' -f4| awku`; do
  projectDir=chipatlas
  Genome=hg38
  nslot="16"
  Logfile="$projectDir/results/$Genome/log/$SRX.log.txt"
  QVAL="05 10 20"
  let i++
  ar_id=`bin/arid| sort -k3nr| cut -f1| awk 'NR == '$i''`
  qsub -ar $ar_id -N "srT$Genome" -o $Logfile -e $Logfile -pe def_slot $nslot $projectDir/sh/sraTailor.sh $SRX $Genome $projectDir "$QVAL"
done

SRX488721 # p8 で無事完了
SRX610814 # p8 で無事完了

SRX318767
SRX318772
SRX318768
SRX655400
SRX655406

