#!/bin/bash
set -eo pipefail

medaka_version=$(medaka --version)
modeldata=()
while read -r line; do
    modeldata+=("$line")
done < <(medaka tools list_models) # Available models on first line, default on next line
MODEL=${modeldata[1]##* }

OUTPUT="medaka_variant"
THREADS=1
THRESHOLD=0.04
BATCH_SIZE=150
REGIONS=""

iflag=false
fflag=false
DELETE=false

HAP1OPTS="--tag_name HP --tag_value 1 --tag_keep_missing"
HAP2OPTS="--tag_name HP --tag_value 2 --tag_keep_missing"
HAPLOIDTHRESHOLD=1
VARIANT_DECODER="SNPDecoder"

WHATSHAPOPTS="--ignore-read-groups"

usage="
${medaka_version}
------------

Variant calling via neural networks. The input bam should be aligned to the reference against which to call variants.

$(basename "$0") [-h] -i <fastx>

    -h  show this help text.
    -i  input bam of reads aligned to ref. Read groups are currently ignored, so the bam should only contain reads from a single sample.
    -f  input fasta input reference (required).
    -r  region string(s). If providing multiple regions, wrap them in quotes. If not provided, will process all contigs in bam. 
    -o  output folder (default: ${OUTPUT}).
    -m  medaka model, (default: ${MODEL}).
        ${modeldata[0]}.
        Alternatively a .hdf file from 'medaka train'. 
    -v  medaka variant decoder used to call final variants. One of: 'SNPDecoder', 'HaploidVariantDecoder' (default: ${VARIANT_DECODER}).
    -T  label probability threshold for calling heterozygous SNPs from unphased reads. (default: ${THRESHOLD}).
        This will only affect the initial SNP calls used to phase reads, not the final SNP calls, which are
        computed from medaka consensuses of each haplotype run individually. 
    -t  number of threads with which to create features (default: 1).
    -b  batchsize, controls memory use (default: ${BATCH_SIZE}).
    -d  delete intermediate files. (default: keep)."


while getopts ':hi::f:r:o:m:v:T:t:b:d' option; do
  case "$option" in
    h  ) echo "$usage" >&2; exit;;
    i  ) iflag=true; CALLS2REF=$(readlink -f $OPTARG);;
    f  ) fflag=true; REF=$(readlink -f $OPTARG);;
    r  ) REGIONS="$OPTARG";;
    o  ) OUTPUT=$OPTARG;;
    m  ) MODEL=$OPTARG;;
    v  ) VARIANT_DECODER=$OPTARG;;
    T  ) THRESHOLD=$OPTARG;;
    t  ) THREADS=$OPTARG;;
    b  ) BATCH_SIZE=$OPTARG;;
    d  ) DELETE=true;;
    \? ) echo "Invalid option: -${OPTARG}." >&2; exit 1;;
    :  ) echo "Option -$OPTARG requires an argument." >&2; exit 1;;
  esac
done
shift $(($OPTIND - 1))

if ! $iflag; then
  echo "$usage" >&2;
  echo "" >&2;
  echo "-i must be specified." >&2;
  exit 1;
fi

if ! $fflag; then
  echo "$usage" >&2;
  echo "" >&2;
  echo "-f must be specified." >&2;
  exit 1;
fi

run_extract_region_from_bam () {

    local BAMIN=$1
    local BAMOUT=$2
    local REGIONS=$3

    exit_if_file_does_not_exist ${BAMIN} ${BAMIN}.bai
    if [[ ! -e ${BAMOUT} ]]; then
        echo ""
        echo "======================================"
        echo "Extracting regions $REGIONS from bam ${BAMIN} "
        echo "======================================"
        echo ""
        samtools view -b -h ${BAMIN} -@ ${THREADS} -o ${BAMOUT} ${REGIONS} \
            || (echo "Failed to extract regions from bam." && exit 1)
    else 
        echo "Not extracting regions from bam, ${BAMOUT} exists."
    fi
    run_samtools_index ${BAMOUT}
}


run_medaka_consensus () {
    local BAM=$1
    local PROBS=$2
    local EXTRAOPTS=$3
    if [ -n "${REGIONS}" ]; then
        local REG_OPT="--regions ${REGIONS}"
    else
        local REG_OPT=""
    fi
    exit_if_file_does_not_exist ${BAM} ${BAM}.bai
    if [[ ! -e ${PROBS} ]]; then
        echo ""
        echo "======================================"
        echo "Running medaka consensus ${BAM} ${EXTRAOPTS}"
        echo "======================================"
        echo ""
        medaka consensus ${BAM} ${PROBS} --model ${MODEL} --batch_size ${BATCH_SIZE} ${REG_OPT} --threads ${THREADS} ${EXTRAOPTS} \
            || (echo "Failed to run medaka consensus." && exit 1)
    else 
        echo "Not running medaka consensus, ${PROBS} exists."
    fi
}

run_medaka_variant () {
    local PROBS=$1
    local VCF=$2
    local T=$3
    local EXTRAOPTS=$4
    exit_if_file_does_not_exist ${PROBS} ${REF}
    if [[ ! -e ${VCF} ]]; then
        echo ""
        echo "======================================"
        echo "Running medaka variant with threshold ${T}"
        echo "======================================"
        echo ""
        medaka variant ${REF} ${PROBS} ${VCF} --threshold ${T} ${EXTRAOPTS} \
            || (echo "Failed to call variants from consensus chunks." && exit 1)
        echo "VCF written to ${OUTPUT}/${VCF}."
    else
        echo "Using existing output:  ${OUTPUT}/${VCF}."
    fi
}

run_medaka_haploid2diploid () {
    local VCF1=$1
    local VCF2=$2
    local REF=$3
    local MERGED=$4

    exit_if_file_does_not_exist ${VCF1} ${VCF2} ${REF}
    if [[ ! -e ${MERGED} ]]; then
        echo ""
        echo "======================================"
        echo "Running medaka haploid2diploid "
        echo "======================================"
        echo ""
        medaka tools haploid2diploid ${VCF1} ${VCF2} ${REF} ${MERGED} \
            || (echo "Failed to run medaka haploid2diploid." && exit 1)
        echo "VCF written to ${OUTPUT}/${MERGED}."
    else
        echo "Using existing output:  ${OUTPUT}/${MERGED}."
    fi
}

run_phase_vcf () {
    local VCFIN=$1 
    local VCFOUT=$2
    exit_if_file_does_not_exist ${VCFIN}
    run_samtools_faidx ${REF}
    if [[ ! -e ${VCFOUT} ]]; then
        echo ""
        echo "============================================="
        echo "Running whatshap phase to phase vcf ${VCFIN}."
        echo "============================================="
        echo ""
        whatshap phase --reference ${REF} -o ${VCFOUT} ${VCFIN} ${CALLS2REF} ${WHATSHAPOPTS} \
            || (echo "Failed to phase variants in ${VCFIN}." && exit 1)
        echo "Phased VCF written to ${OUTPUT}/${VCFOUT}."
    else
        echo "Using existing output:  ${OUTPUT}/${VCFOUT}."
    fi
}

run_whatshap_tag () {
    local VCFIN=$1
    local BAMOUT=$2
    if [[ ! -e ${BAMOUT} ]]; then
        echo ""
        echo "============================================="
        echo "Running whatshap tag using ${VCFIN}."
        echo "============================================="
        echo ""
        whatshap haplotag -o ${BAMOUT} --reference ${REF} ${VCFIN} ${CALLS2REF} ${WHATSHAPOPTS} \
            || (echo "Failed to partition reads in round 0." && exit 1)
        echo "Tagged reads written to ${OUTPUT}/${BAMOUT}."
    else
        echo "Using existing output:  ${OUTPUT}/${BAMOUT}."
    fi
    run_samtools_index ${BAMOUT}
}

run_bgzip () {
    local FILEIN=$1
    local FILEOUT=$2
    exit_if_file_does_not_exist ${FILEIN}
    if [[ ! -e ${FILEOUT} ]]; then
        echo "Compressing ${FILEIN}."
        bgzip -c ${FILEIN} > ${FILEOUT} \
            || (echo "Failed to compress ${FILEIN}." && exit 1)
        echo "Compressed file written to ${OUTPUT}/${FILEOUT}."
    else
        echo "Using existing output:  ${OUTPUT}/${FILEOUT}."
    fi
    run_tabix ${FILEOUT} 
}

run_tabix () {
    local FILEIN=$1
    local FILEOUT=${1}.tbi
    exit_if_file_does_not_exist ${FILEIN}
    if [[ ! -e ${FILEOUT} ]]; then
        echo "Indexing ${FILEIN}."
        tabix -p vcf ${FILEIN} \
            || (echo "Failed to compress ${FILEIN}." && exit 1)
        echo "Compressed file written to ${OUTPUT}/${FILEOUT}."
    else
        echo "Using existing output:  ${OUTPUT}/${FILEOUT}."
    fi
}

run_samtools_faidx () {
    local FILEIN=$1
    local FILEOUT=${1}.fai
    exit_if_file_does_not_exist ${FILEIN}
    if [[ ! -e ${FILEOUT} ]]; then
        echo "Indexing ${FILEIN}."
        samtools faidx ${FILEIN} \
            || (echo "Failed to index ${FILEIN}." && exit 1)
        echo "Created index ${OUTPUT}/${FILEOUT}."
    else
        echo "Using existing output:  ${OUTPUT}/${FILEOUT}."
    fi
}


run_samtools_index () {
    local BAM=$1
    local INDEX=${BAM}.bai
    exit_if_file_does_not_exist ${BAM}

    if [[ ! -e ${INDEX} ]]; then
        echo "Running samtools index on ${BAM}."
        samtools index ${BAM} -@ ${THREADS} \
            || (echo "Failed to index bam ${BAM}." && exit 1)
        echo "Bam index in ${OUTPUT}/${INDEX}."
    else
        echo "Using existing output:  ${OUTPUT}/${INDEX}."
    fi
}

exit_if_file_does_not_exist () {
    for FILE in "$@"; do
        if [[ ! -e ${FILE} ]]; then
            echo "Could not find file ${FILE}, exiting." && exit 1
        fi
    done
}

echo "Checking program versions"
medaka_version_report || exit 1

if [[ ! -e ${OUTPUT} ]]; then
  mkdir -p ${OUTPUT}
else
  echo "Warning: Output ${OUTPUT} already exists, may use old results."
fi

cd ${OUTPUT}

# check input bam, bam index and ref exist
exit_if_file_does_not_exist ${CALLS2REF} ${CALLS2REF}.bai ${REF}

# if regions have been provided, extract that region from the input bam
# (whatshap currently does not have a region string option). 

if [ -n "${REGIONS}" ]; then
    CALLS2REF_EXTRACTED=$(basename ${CALLS2REF})
    run_extract_region_from_bam ${CALLS2REF} ${CALLS2REF_EXTRACTED} ${REGIONS}
    CALLS2REF=${CALLS2REF_EXTRACTED}
fi

CONSENSUSPROBS=round_0_hap_mixed_probs.hdf
run_medaka_consensus ${CALLS2REF} ${CONSENSUSPROBS}

UNPHASEDVCF=round_0_hap_mixed_thresh_${THRESHOLD}_unphased.vcf
run_medaka_variant ${CONSENSUSPROBS} ${UNPHASEDVCF} ${THRESHOLD}

PHASEDVCF=round_0_hap_mixed_thresh_${THRESHOLD}_phased.vcf
run_phase_vcf ${UNPHASEDVCF} ${PHASEDVCF} 

PHASEDVCFGZ=${PHASEDVCF}.gz
run_bgzip ${PHASEDVCF} ${PHASEDVCFGZ}

PHASEDBAM=round_0_hap_mixed_thresh_${THRESHOLD}_phased.bam
run_whatshap_tag ${PHASEDVCFGZ} ${PHASEDBAM}

PROBSHAP1=round_1_hap_1_probs.hdf
run_medaka_consensus ${PHASEDBAM} ${PROBSHAP1} "${HAP1OPTS}"

PROBSHAP2=round_1_hap_2_probs.hdf
run_medaka_consensus ${PHASEDBAM} ${PROBSHAP2} "${HAP2OPTS}" 

VCFHAP1=round_1_hap_1.vcf
run_medaka_variant ${PROBSHAP1} ${VCFHAP1} ${HAPLOIDTHRESHOLD}
VCFHAP2=round_1_hap_2.vcf
run_medaka_variant ${PROBSHAP2} ${VCFHAP2} ${HAPLOIDTHRESHOLD}
VCFMERGED=round_1_final.vcf
echo "run_medaka_haploid2diploid ${VCFHAP1} ${VCFHAP2} ${REF} ${VCFMERGED}"
run_medaka_haploid2diploid ${VCFHAP1} ${VCFHAP2} ${REF} ${VCFMERGED}

# since medaka output unphased VCF, rephase variants with whatshap
VCFREPHASED="${VCFMERGED%.*}_rephased.vcf"
run_phase_vcf ${VCFMERGED} ${VCFREPHASED} 
VCFREPHASEDGZ=${VCFREPHASED}.gz 
run_bgzip ${VCFREPHASED} ${VCFREPHASEDGZ}

PHASEDBAM=round_1_phased.bam
run_whatshap_tag ${VCFREPHASEDGZ} ${PHASEDBAM}

PROBSHAP1=round_2_hap_1_probs.hdf
run_medaka_consensus ${PHASEDBAM} ${PROBSHAP1} "${HAP1OPTS}"
PROBSHAP2=round_2_hap_2_probs.hdf
run_medaka_consensus ${PHASEDBAM} ${PROBSHAP2} "${HAP2OPTS}"

FINAL_DECODING_OPTS="--decoder ${VARIANT_DECODER}"
VCFHAP1=round_2_hap_1.vcf
run_medaka_variant ${PROBSHAP1} ${VCFHAP1} ${HAPLOIDTHRESHOLD} "${FINAL_DECODING_OPTS}"
VCFHAP2=round_2_hap_2.vcf
run_medaka_variant ${PROBSHAP2} ${VCFHAP2} ${HAPLOIDTHRESHOLD} "${FINAL_DECODING_OPTS}"

VCFMERGEDUNPHASED=round_2_final_unphased.vcf
run_medaka_haploid2diploid ${VCFHAP1} ${VCFHAP2} ${REF} ${VCFMERGEDUNPHASED}

# since medaka output unphased VCF, rephase variants with whatshap
VCFMERGEDPHASED="${VCFMERGEDUNPHASED%_*}_phased.vcf"
run_phase_vcf ${VCFMERGEDUNPHASED} ${VCFMERGEDPHASED} 

if $DELETE; then
  files=$(ls *.hdf *.bam *.bai *.gz *.tbi)
  echo ""
  echo "Deleting intermediate files:"
  echo "${files}"
  rm ${files}
fi

echo ""
echo "All done." 
echo "Final unphased VCF written to ${OUTPUT}/${VCFMERGEDUNPHASED}"
echo "Final phased VCF written to ${OUTPUT}/${VCFMERGEDPHASED}"
