#!/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 adds new subtitle track to the specified video file.

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

For language, use ISO 639-2. By default, the result
is saved to a new file with ".s" before file extension.

Example:
    ${0##*/} video.mkv esperanto.srt epo 'Esperanto subs'
Result will be saved to "video.s.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.
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 4 ]]; then
    Wrong_Usage
    exit 1
fi
readonly VIDEO="$1"
readonly SUBS="$2"
readonly SUBLANG="$3"
readonly TITLE="$4"

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


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


N=$(ffprobe "$VIDEO" 2>&1 | grep -c ": Subtitle:")
PARAMS=(
    -map 0
    -map 1
    -c copy
    -metadata:s:s:${N} language="$SUBLANG"
    -metadata:s:s:${N} title="$TITLE"
)

set -x
ffmpeg -hide_banner -i "$VIDEO" -i "$SUBS" "${PARAMS[@]}" "$OUT"
set +x

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