#!/bin/bash
#
# Copyright (C) 2023-2025 Eugene 'Vindex' Stulin
# Distributed under the Boost Software License 1.0.

set -eu -o pipefail


# The function prints help information.
Print_Help() {
cat <<EndOfHelp
This script converts the specified video file to the MP4 format.
Warning: such conversion is not always possible.

Usage:
    ${0##*/} <input/video/path> [-o <file>]

Example:
    ${0##*/} /home/user/video.avi
Result will be saved to video.mp4 in the current directory.

Help and version:
    ${0##*/} --help|-h
    ${0##*/} --version|-v
EndOfHelp
}


# The function prints the script version.
Print_Version() {
    local VERSION_SCRIPT="$(dirname -- "${BASH_SOURCE[0]}")/bbsi-version"
    if [[ ! -x "$VERSION_SCRIPT" ]]; then
        echo "Unknown version."
    else
        "$VERSION_SCRIPT"
    fi
}


# The function prints information about wrong usage to stderr.
Wrong_Usage() {
    echo "Wrong usage. See: ${0##*/} --help" >&2
}


# parse command line arguments
CUSTOM_PATH=""
OPT_TEMP=$(getopt -o 'o:hv' --long 'help,version' -n "$0" -- "$@")
eval set -- "$OPT_TEMP"
while true; do
    case "$1" in
        '-o')
            CUSTOM_PATH="$2"
            shift 2
            continue
            ;;
        '-h'|'--help')
            # getopt adds "--" as argument
            if [[ $# -ne 2 ]]; then
                Wrong_Usage
                exit 1
            fi
            Print_Help
            exit 0
            ;;
        '-v'|'--version')
            # getopt adds "--" as argument
            if [[ $# -ne 2 ]]; then
                Wrong_Usage
                exit 1
            fi
            Print_Version
            exit 0
            ;;
        '--')
            shift
            break
            ;;
        *)
            echo "Internal error" >&2
            exit 1
    esac
done

if [[ $# -ne 1 ]]; then
    Wrong_Usage
    exit 1
fi

MEDIAFILE="$1"
BASENAME="${MEDIAFILE##*/}"
if [[ -n "$CUSTOM_PATH" ]]; then
    CUSTOM_EXT="${CUSTOM_PATH##*.}"
    CUSTOM_EXT=$(echo "$CUSTOM_EXT" | tr '[:upper:]' '[:lower:]')
    if [[ "$CUSTOM_EXT" != "mp4" ]]; then
        echo "Extension must be 'mp4'." >&2
        Wrong_Usage
        exit 1
    fi
    mkdir -p "$(dirname "$CUSTOM_PATH")"
    MP4_FILE="$CUSTOM_PATH"
else
    MP4_FILE="${BASENAME%.*}.mp4"
fi


Interrupt_Execution() {
    set +x
    echo "The script has been interrupted." 2>&1
    rm -f "$MP4_FILE"
    exit 1
}
trap Interrupt_Execution ABRT INT QUIT TERM


# convert
set -x
if ! ffmpeg -i "$MEDIAFILE" -map 0 -c copy -c:s mov_text "$MP4_FILE"; then
    set +x
    Interrupt_Execution
fi
set +x

echo "Saved as $MP4_FILE."
