#!/bin/bash

set -eu
set -o pipefail

all_mkv=True

function usage
{
    exit_code="$1"
    case "$exit_code" in
        0)
            ;;
        *)
            exec 1>&2
            ;;
    esac
    echo "Usage: $0 foo1.mkv foo2.mkv"
    echo "Downsamples bluray matroska (mkv) files to DVD resolution mkv or ogm files."
    exit "$exit_code"
}

if [ "$#" = 0 ]
then
    usage 0
fi

failed_files=""

for input_file in "$@"
do
    case "$input_file" in
        *.mkv)
            output_file=$(basename "$input_file" .mkv).ds.mkv
            if ! HandBrakeCLI \
                -i "$input_file" \
                -o "$output_file" \
                --width 720 \
                --loose-anamorphic \
                --all-audio \
                --all-subtitles
            then
                failed_files="$failed_files
$input_file"
            fi
            ;;
        *)
            echo "$0: Warning: $input_file is not a .mkv. Skipping."
            all_mkv=False
            ;;
    esac
done

if [ "$failed_files" != "" ]
then
    echo "$0: Some files failed to convert:$failed_files" 1>&2
    exit 1
fi

case "$all_mkv" in
    True)
        # Cool. Nothing to worry about.
        ;;
    False)
        echo "$0: One or more files skipped" 1>&2
        exit 1
        ;;
    *)
        echo "$0: internal error: \$all_mkv has a strange value: $all_mkv" 1>&2
        exit 1
        ;;
esac