#!/bin/bash

set -e

usage() {
	echo "$0 [options] FILENAME"
	echo "  crea un file pescatoio/FILENAME (se non esiste)"
	echo "  mettendo intro/outro al FILENAME"
	echo
	echo "options:"
	echo "   -t   TIPO     prende intro-TIPO.ogg e outro-TIPO.ogg [default=generico]"
	echo "                 Valori possibili:"
	find "$(dirname $0)/materiale/intro-outro/" -name 'intro-*.ogg' |
	while read fpath
	do
		echo "                 - $(basename "$fpath" .ogg|cut -d- -f 2-)"
	done
	echo "   -h            Mostra questo help"
}

tipo=generico

while getopts 'ht:' opt; do
	case $opt in
		t)
			tipo="$OPTARG"
			;;
		h)
			usage
			exit 0
			;;
	esac
done
shift $((OPTIND-1))

if [[ $# -ne 1 ]]; then
	echo "Invalid syntax" >&2
	usage >&2
	exit 2
fi
file=$1
shift

if ! [ -f "$file" ]; then
	echo "Filename non valido" >&2
	exit 2
fi
intro=$(realpath "$(dirname $0)/materiale/intro-outro/intro-$tipo.ogg")
outro=$(realpath "$(dirname $0)/materiale/intro-outro/outro-$tipo.ogg")
if ! [ -f "$intro" ]; then
	echo "Intro $intro non valido" >&2
	exit 2
fi
if ! [ -f "$outro" ]; then
	echo "Outro $outro non valido" >&2
	exit 2
fi

out=$(realpath "$(dirname $0)/pescatoio/$(basename $file)")
if [[ -f "$out" ]]; then
	echo "File di output $out gia esistente" >&2
	exit 2
fi

ffmpeg -loglevel error -n -i "concat:$intro|$file|$outro" "$out"
