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

set -eu -o pipefail

# The function prints help information.
Print_Help() {
cat <<EndOfHelp
The script merges source mediafiles to a new mediafile.

Usage:
    $0 <input/path1> <input/path2> ...

Example:
    $0 001.mp3 002.mp3
Result is saved to output.mp3 (extension depends on the first source file).

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 0 ]]; then
    Wrong_Usage
    exit 1
elif [[ $# -eq 1 ]]; then
    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        Print_Help
        exit 0
    elif [[ "$1" == "-v" || "$1" == "--version" ]]; then
        Print_Version
        exit 0
    fi
fi

readonly FIRST_MEDIAFILE="$1"

EXT="${FIRST_MEDIAFILE##*.}"
OUTFILE="output.$EXT"
FILE_LIST="tmp-list.txt"


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


Exit() {
    set +x
    rm -f "$FILE_LIST"
}
trap Exit EXIT


> "$FILE_LIST"
for MEDIAFILE in "$@"; do
    printf '%s\n' "file '${MEDIAFILE}'" >> "$FILE_LIST"
done
ffmpeg -hide_banner -f concat -safe 0 -i "$FILE_LIST" -c copy "$OUTFILE"
set +x

echo "Saved to $OUTFILE."
