#!/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 adds new subtitle track to the specified videofile.
The result is saved to a new file with ".s" before file extension.

Usage:
    $0 <video_file_path> <subtitle_file_path> <track_name> [-o output_path]
The track name is the name of the subtitle language (usually).

Example:
    $0 video.mkv esperanto.srt
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_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."
}


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


# parse command line arguments
if [[ $# -eq 1 ]]; then
    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        Print_Help
        exit 0
    elif [[ "$1" == "-v" || "$1" == "--version" ]]; then
        Print_Version
        exit 0
    else
        Wrong_Usage
        exit 1
    fi
elif [[ $# -lt 3 || $# -eq 4 || $# -gt 5 ]]; then
    Wrong_Usage
    exit 1
fi

readonly VIDEO="$1"
readonly SUBS="$2"
readonly SUBLANG="$3"
if [[ $# -eq 5 ]]; then
    if [[ "$4" != "-o" ]]; then
        Wrong_Usage
        exit 1
    fi
    OUT="$5"
fi

WITHOUT_EXT="${VIDEO%.*}"
EXT="${VIDEO##*.}"
readonly DEF_OUT="${WITHOUT_EXT}.s.${EXT}"
OUT=${OUT:-$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}"

set -x
ffmpeg -hide_banner -i "$VIDEO" -i "$SUBS" $PARAMS language="$SUBLANG" "$OUT"
set +x

echo "Saved to \"$OUT\"."
