#!/bin/bash
# left 2 stereo mix
VERSION=1.1
unset DEPENDENCIES
DEPENDENCIES=(ffmpeg ffprobe)

SCRIPTDIR=$(dirname "${0}")
. "${SCRIPTDIR}/mmfunctions" || { echo "Missing '${SCRIPTDIR}/mmfunctions'. Exiting." ; exit 1 ;};

_usage(){
    echo
    echo "$(basename "${0}") ${VERSION}"
    echo "This application takes an input video file(s) and produces outputs that are map the left channel of the input to a stereo mix in the output."
    echo "Dependencies: ${DEPENDENCIES[@]}"
    echo "Usage: $(basename "${0}") file1 [ file2 ...]"
    echo
    exit
}
[ "${#}" = 0 ] && _usage
_check_dependencies "${DEPENDENCIES[@]}"

_cleanup(){
    _log -a "Process aborted"
    exit 1
}

# local variables
SUFFIX="_left2stereo"

trap _cleanup SIGHUP SIGINT SIGTERM
_log -b

while [ "${*}" != "" ] ; do

    SOURCEFILE="${1}"
    NAME=$(basename "${1}")

    _get_codectagstring
    unset FFMPEG_OPTS
    FFMPEG_OPTS+=(-c:v copy -c:a pcm_s24be -ar 48000 -ac 2)
    _get_audio_index "${SOURCEFILE}"
    FFMPEG_OPTS+=(-map_channel 0.${AUDIO_INDEX_1}.0)
    if [ "${CODEC_TAG_STRING}" = "mpeg" ] ; then
        EXTENSION="mxf"
    else
        EXTENSION="mov"
    fi

    OUTPUT_MOVIE="${SOURCEFILE%.*}${SUFFIX}.${EXTENSION}"
    if [ -f "${OUTPUT_MOVIE}" ] ; then
        _report -wt "The intended output of $(basename "${0}") already exists. Skipping for now. Please delete ${OUTPUT_MOVIE} and rerun or figure out why you are trying to do this."
    else
        _report -dt "Generating ${OUTPUT_MOVIE} ... with these options ${FFMPEG_OPTS[*]}"
        ffmpeg -i "${SOURCEFILE}" "${FFMPEG_OPTS[@]}" "${OUTPUT_MOVIE}"
        _report -dt "$(basename "${0}") is done with ${NAME}."
    fi
    shift
done
_log -e