#!/bin/bash
#
# Copyright (C) 2026 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 adds new audio track to the specified video file.

Usage:
    ${0##*/} <video_path> <track_path> <language> <track_name> [-o <path>]

For language, use ISO 639-2 ("eng", "epo", "fra",
"por", "spa", "srp", "rus", "tur", etc.).
By default, the result is saved to a new file with ".a" before file extension.

Example:
    ${0##*/} video.mkv esperanto.ac3 epo 'Esperanto'
Result will be saved to "video.a.mkv".

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.
Incorrect_Usage() {
    echo "Incorrect 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
                Incorrect_Usage
                exit 1
            fi
            Print_Help
            exit 0
            ;;
        '-v'|'--version')
            # getopt adds "--" as argument
            if [[ $# -ne 2 ]]; then
                Incorrect_Usage
                exit 1
            fi
            Print_Version
            exit 0
            ;;
        '--')
            shift
            break
            ;;
        *)
            echo "Internal error" >&2
            exit 1
    esac
done


if [[ $# -ne 4 ]]; then
    Incorrect_Usage
    exit 1
fi
readonly MEDIAFILE="$1"
readonly AUDIOTRACK="$2"
readonly TRACK_LANG="$3"
readonly TRACK_TITLE="$4"

WITHOUT_EXT="${MEDIAFILE%.*}"
EXT="${MEDIAFILE##*.}"
readonly DEF_OUT="${WITHOUT_EXT}.a.${EXT}"
[[ -n "$CUSTOM_PATH" ]] && mkdir -p "$(dirname "$CUSTOM_PATH")"
OUT=${CUSTOM_PATH:-$DEF_OUT}


if [[ -f "$OUT" ]]; then
    ANSWER=n
    echo "This file exists: $OUT"
    echo -n "Delete it? Y/n >: "
    read ANSWER
    ANSWER=${ANSWER,,}  # to lower case
    if [[ "$ANSWER" == "y" || "$ANSWER" == "yes" || "$ANSWER" == "" ]]; then
        rm -f "$OUT"
    fi
fi


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


Get_New_Audio_Stream_Index() {
    local AUDIO_TRACKS
    if ! AUDIO_TRACKS=$(ffprobe -v error -select_streams a \
        -show_entries stream=index -of csv=p=0 "$1"); then
        echo "Failed to analyze file." >&2
        return 1
    fi
    local INDEX=$(echo "$AUDIO_TRACKS" | wc -l)
    if [[ -z $INDEX ]]; then
        INDEX=0
    fi
    echo $INDEX
}


N="$(Get_New_Audio_Stream_Index "$MEDIAFILE")"
OPTIONS=(
    -map '0:v?' -c:v copy
    -map '0:a?' -map '1:a:0' -c:a copy
    -map '0:s?' -c:s copy
    -map '0:t?' -c:t copy
    -map '0:d?' -c:d copy
    -max_interleave_delta 0
    -metadata:s:a:$N "language=$TRACK_LANG"
    -metadata:s:a:$N "title=$TRACK_TITLE"
)

set -x
ffmpeg -hide_banner -i "$MEDIAFILE" -i "$AUDIOTRACK" "${OPTIONS[@]}" "$OUT"
set +x

echo "Saved as \"$OUT\"."
