#!/bin/sh
# autopkgtest for cuteSV, following the Debian Med convention: run the
# installed program on a small example data set and check the calls it
# produces.  The example is derived from the BED files in the upstream
# simulation directory, so it also demonstrates their use.
set -e

pkg=cutesv

if [ "$AUTOPKGTEST_TMP" = "" ]; then
	AUTOPKGTEST_TMP="$(mktemp -d /tmp/$pkg-test.XXXXXX)"
	trap "rm -rf $AUTOPKGTEST_TMP" 0 INT QUIT ABRT PIPE TERM
fi

# The test runs from the top level of the unpacked source tree.
cp -a simulation "$AUTOPKGTEST_TMP"/
cd "$AUTOPKGTEST_TMP"

set -x
cuteSV --version
cuteSV --help

# Build a tiny long-read data set from the simulation BED files: the first
# deletion of sim_del.bed.gz and the first insertion of sim_ins.bed.gz are
# turned into reads on a random reference sequence, mimicking the VISOR
# workflow described in simulation/README.md.
python3 - <<'PY'
import gzip
import random

import pysam

CHR = "1"
FLANK = 1000

with gzip.open("simulation/sim_del.bed.gz", "rt") as fh:
    del_lines = fh.readlines()
del_chrom, del_start, del_end = del_lines[0].split("\t")[:3]
del_start, del_end = int(del_start), int(del_end)

with gzip.open("simulation/sim_ins.bed.gz", "rt") as fh:
    ins_chrom, ins_start, ins_end, _type, ins_seq = \
        fh.readline().split("\t")[:5]
ins_start, ins_end = int(ins_start), int(ins_end)

assert del_chrom == ins_chrom == CHR, "simulation BED files use mixed chromosomes"

# Random but reproducible reference sequence.
rng = random.Random(1)
ref_len = max(del_end, ins_end) + FLANK + 1000
ref = "".join(rng.choice("ACGT") for _ in range(ref_len))
with open("reference.fa", "w") as fh:
    fh.write(">%s\n" % CHR)
    for i in range(0, len(ref), 60):
        fh.write(ref[i:i + 60] + "\n")
pysam.faidx("reference.fa")

header = {"HD": {"VN": "1.6"}, "SQ": [{"SN": CHR, "LN": ref_len}]}
reads = []


def add_read(name, pos, seq, cigar):
    read = pysam.AlignedSegment()
    read.query_name = name
    read.query_sequence = seq
    read.flag = 0
    read.reference_id = 0
    read.reference_start = pos
    read.mapping_quality = 60
    read.cigartuples = cigar
    read.query_qualities = pysam.qualitystring_to_array("I" * len(seq))
    reads.append(read)


for i in range(3):
    add_read(
        "deletion_%d" % i,
        del_start - FLANK,
        ref[del_start - FLANK:del_start] + ref[del_end:del_end + FLANK],
        [(0, FLANK), (2, del_end - del_start), (0, FLANK)],
    )
for i in range(3):
    add_read(
        "insertion_%d" % i,
        ins_start - FLANK,
        ref[ins_start - FLANK:ins_start] + ins_seq + ref[ins_end:ins_end + FLANK],
        [(0, FLANK), (1, len(ins_seq)), (0, FLANK)],
    )

reads.sort(key=lambda read: (read.reference_start, read.query_name))
with pysam.AlignmentFile("simulated.bam", "wb", header=header) as out:
    for read in reads:
        out.write(read)
pysam.index("simulated.bam")

# Expected calls, used by the shell checks below.
with open("expected.tsv", "w") as fh:
    fh.write("DEL\t%d\t%d\n" % (del_start, -(del_end - del_start)))
    fh.write("INS\t%d\t%d\n" % (ins_start, len(ins_seq)))

# Restrict calling to the simulated deletions, as described in the README.
with open("deletions.bed", "w") as fh:
    fh.writelines(del_lines)
PY

# Basic usage as documented in README.md:
#     cuteSV <sorted.bam> <reference.fa> <output.vcf> <work_dir>
cuteSV -t 2 -s 3 simulated.bam reference.fa calls.vcf .

# Genotyping exercises the numpy based genotype module.
cuteSV -t 2 -s 3 --genotype simulated.bam reference.fa genotypes.vcf .

# Only detect SVs in the regions given by the simulated deletion BED file.
cuteSV -t 2 -s 3 -include_bed deletions.bed simulated.bam reference.fa deletions.vcf .
set +x

check_sv() {
	vcf="$1"
	svtype="$2"
	pos="$3"
	svlen="$4"
	awk -F '\t' -v t="$svtype" -v p="$pos" -v l="$svlen" '
		$0 !~ /^#/ && $2 == p && \
		$8 ~ ("(^|;)SVTYPE=" t "(;|$)") && \
		$8 ~ ("(^|;)SVLEN=" l "(;|$)") { found = 1 }
		END { exit(found ? 0 : 1) }' "$vcf"
}

grep -q '^##fileformat=VCF' calls.vcf
grep -q '^##source=cuteSV' calls.vcf

while read -r svtype pos svlen; do
	check_sv calls.vcf "$svtype" "$pos" "$svlen"
	check_sv genotypes.vcf "$svtype" "$pos" "$svlen"
	case "$svtype" in
		DEL) check_sv deletions.vcf "$svtype" "$pos" "$svlen" ;;
	esac
done < expected.tsv

# The BED file covers the deletion only, so the insertion must be filtered.
test "$(grep -vc '^#' deletions.vcf)" -eq 1
! grep -q 'SVTYPE=INS' deletions.vcf

# The genotype run adds allele frequencies.
grep -q ';AF=' genotypes.vcf

echo PASS
