#!/bin/sh

# Remux a video into a mp4 container and delete the original.
#
# This is an example of an yle-dl postprocessing script. To use this
# as postprocessing step, call yle-dl with:
#
# yle-dl --postprocess muxmp4 https://areena.yle.fi/1-65174150
#
# To run this directly on the command line, run:
#
# muxmp4 videofile.mkv subtitlefile.srt

absolute_path() {
    case "$1" in
	/*) echo "$1";;
	*)  echo "$PWD/$1";;
    esac
}

# The two input parameters for a yle-dl postprocessing script are the
# video file name and the subtitle file name (may be missing).
INPUTVIDEOFILE="$1"
SUBTITLEFILE="$2"

OUTPUTFILE=$(echo "$INPUTVIDEOFILE" | sed 's/.mkv$//').mp4
ABS_INPUT=$(absolute_path "$INPUTVIDEOFILE")
ABS_OUTPUT=$(absolute_path "$OUTPUTFILE")

if [ -n "$SUBTITLEFILE" ]; then
    ABS_SUBTITLE=$(absolute_path "$SUBTITLEFILE")

    ffmpeg -i "file://$ABS_INPUT" -f srt -i "file://$ABS_SUBTITLE" -codec copy -c:s mov_text "file://$ABS_OUTPUT"
else
    ffmpeg -i "file://$ABS_INPUT" -codec copy "file://$ABS_OUTPUT"
fi

if [ $? -eq 0 ]; then
    rm "$@"
fi
