#!/usr/bin/env bash

# example line:
# ftp://ftp.sra.ebi.ac.uk/vol1/run/ERR398/ERR3988770/HG00447.final.cram
download_location=$1

num_cores=4

sample_filename=$(echo $download_location | cut -f 1 | cut -d '/' -f 8)
sample_id=$(echo $sample_filename | cut -d '.' -f 1)
cram_reference=/staging/lalli/pangenie/GRCh38_full_analysis_set_plus_decoy_hla.fa
reference_pangenome_vcf=/staging/lalli/pangenie/hprc-jun1-mc-chm13.pangenie_panel.vcf 
reference_pangenome_vcf_fasta=/staging/lalli/pangenie/hprc-jun1-mc-chm13.fasta

if [ -s /staging/lalli/pangenie/results/${sample_id}.pangenie_genotyping.*cf* ]
then
    # then this sample has already been completed
    exit 0
else
    mkdir ${sample_id}_working_dir
    cd ${sample_id}_working_dir

    # 1: download sample fastqs
    if [ ! -s /staging/lalli/pangenie/${sample_id}.jf ]
    then
        if [ ! -s /staging/lalli/pangenie/${sample_id}.cram ]
        then
            wget -q $download_location && mv *.cram ${sample_id}.cram
        fi
        echo "samtools fasta --reference $cram_reference ${sample_id}.cram" > generators
        jellyfish count -m 31 -s 3G -p 126 -c 7 -C -L 1 -t ${num_cores} \
                    -o /staging/lalli/pangenie/${sample_id}.jf \
                    --if ${reference_pangenome_vcf_fasta} \
                    -g generators -G 1

        # mv ${sample_id}.jf /staging/lalli/pangenie/${sample_id}.jf
        rm -f ${sample_id}.cram
    fi

    pangenie -i /staging/lalli/pangenie/${sample_id}.jf \
            -v $reference_pangenome_vcf \
            -r ${reference_pangenome_vcf_fasta} \
            -o ${sample_id}.pangenie \
            -s ${sample_id} \
            -t $num_cores \
            -g -d -u

    rm ${sample_id}.pangenie_path_segments.fasta
    
    bcftools reheader --fai ${reference_pangenome_vcf_fasta}.fai ${sample_id}.pangenie_genotyping.vcf | \
    bcftools view -Ob - > ${sample_id}.pangenie.bcf.gz && \
    mv ${sample_id}.pangenie.bcf.gz /staging/lalli/pangenie/results/${sample_id}.pangenie.bcf.gz && \
    cd .. && \
    rm -rf ${sample_id}_working_dir && \
    rm -rf  /staging/lalli/pangenie/${sample_id}.jf
fi
