#!/bin/bash
#
# Copyright (C) 2023 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 [-N] <input/video/path>

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_file="$(dirname -- "${BASH_SOURCE[0]}")/bbsi_version"
    local vers
    vers="$(cat "$version_file" 2>/dev/null)" || vers="is unknown"
    echo "Bash-based set of instruments (bbsi), version $vers."
}


# parse command line arguments
if [[ $# -ne 1 ]]; then
    Wrong_Usage
    exit 1
elif [[ "$1" == "-h" || "$1" == "--help" ]]; then
    Print_Help
    exit 0
elif [[ "$1" == "-v" || "$1" == "--version" ]]; then
    Print_Version
    exit 0
fi
MEDIAFILE="$1"
BASENAME="${MEDIAFILE##*/}"
MP4_FILE="${BASENAME%.*}.mp4"


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
ffmpeg -i "$MEDIAFILE" -map 0 -c copy "$MP4_FILE"
set +x

echo "Saved to $MP4_FILE."
