#!/bin/bash

#SBATCH --partition queue_name
#SBATCH --ntasks 12 --mem 256000
#SBATCH --time 24:00:00
#SBATCH --job-name nothenioid_synolog_run

module load gcc
thr=12

# Synolog Database Directory
syn=/path/to/synolog_analysis
# BLASTs output directory
blast=$syn/species_database/rbhs
# Output directory
out=$syn/notothenioids_synolog

# Species in this run
spp=(
    cace.dtc.dtc  # C. aceratus
    cgun.ftc.fv8  # C. gunnari
    ceso.ftc.fv8  # C. esox
    emac.rtc.rv5  # E. maclovinus
    gyac.def.def  # G. acuticeps
    pgeo.def.def  # P. georgianus
    tber.def.def  # T. bernacchii
)

#
# Generate list of organism/annotation files.
#
gtfann=$(cat $syn/species.gtf.annotations | grep -v '^#' | tr '\t' '@' |
        while read row; do
            org=$(echo $row | cut -f1 -d '@')
            if [[ " ${spp[*]} " =~ " ${org} " ]]; then
                echo $row | tr '@' '\t' | awk -F'\t' '{if (NF==2) {print("--org "$1" --annotation "$2); } else { print("--org "$1" --annotation "$2" --agp "$3); }}'
            fi
        done | tr '\n' ' ' )
gffann=$(cat $syn/species.gff.annotations | grep -v '^#' | tr '\t' '@' |
        while read row; do
            org=$(echo $row | cut -f1 -d '@')
            if [[ " ${spp[*]} " =~ " ${org} " ]]; then
                echo $row | tr '@' '\t' | awk -F'\t' '{if (NF==2) {print("--org "$1" --annotation "$2); } else { print("--org "$1" --annotation "$2" --agp "$3); }}'
            fi
        done | tr '\n' ' ' )

# Generate the HITMAP file
# blast_abc_xyz.tsv.gz    abc    xyz    gzblast
# blast_xyz_abc.tsv.gz    xyz    abc    gzblast
hitmap=$out/hitmap.tsv
# Loop over all species
for sp_que in "${spp[@]}"; do
    # For each species, loop over all species
    for sp_sub in "${spp[@]}"; do
        # Only process when query and subject are different
        if [ "$sp_que" != "$sp_sub" ]; then
            blast_f="blast_${sp_que}_${sp_sub}.tsv.gz"
            echo -e "${blast_f}\t${sp_que}\t${sp_sub}\tgzblast"
        fi
    done
done > $hitmap

# Synolog command
cmd=(
    /usr/bin/time -v
    synolog
    -o $out
    --ann_type gzgtf
    $gtfann
    --ann_type gzgff
    $gffann
    # Blast hits
    --hits_prefix $blast
    # hitmap file
    --hits $hitmap
    --threads $thr
    --sql
)

# print to log
echo "${cmd[@]}" > $out/synolog.log 2>&1
# run command
"${cmd[@]}" >> $out/synolog.log 2>&1
