#!/bin/bash
set -euo pipefail
#set -x
if [ $# -ne 1 -o x$1 == x-h -o x$1 == x--help ]; then
	echo -e \
"Usage:

    samtools sort -O bam -T prefix ... | bambai BAMPATH

Read a sorted BAM file from standard input, write it to BAMPATH and
index it at the same time (creating BAMPATH.bai)."
exit 2
fi
if [ -t 0 ]; then
	echo "Reading input from terminal - this is probably not what you want. Use Ctrl+C to cancel."
fi
BAM="$1"
WORKDIR=$(mktemp -d) || exit 1
trap "rm -rf ${WORKDIR}" exit
FIFO=${WORKDIR}/fifo.bam
mkfifo ${FIFO}
samtools index ${FIFO} && mv ${FIFO}.bai "${BAM}.bai" &
tee ${FIFO} > "${BAM}"
