#!/bin/bash
#
# Copyright (C) 2024-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
The script merges source mediafiles to a new mediafile (name without
extension is "output" by default). Files must be compatible.

Usage:
    ${0##*/} <input/path1> <input/path2> ... [-o <output_file>]

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_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
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

CUSTOM_PATH=""
OPT_TEMP=$(getopt -o 'o:' -n "$0" -- "$@")
if [[ $? -ne 0 ]]; then
    Wrong_Usage
    exit 1
fi
eval set -- "$OPT_TEMP"
while true; do
    case "$1" in
        '-o')
            CUSTOM_PATH="$2"
            shift 2
            continue
            ;;
        '--')
            shift
            break
            ;;
        *)
            echo "Internal error" >&2
            exit 1
    esac
done

if [[ $# -eq 0 ]]; then
    Wrong_Usage
    exit 1
fi

readonly FIRST_MEDIAFILE="$1"

[[ ! -z "$CUSTOM_PATH" ]] && mkdir -p "$(dirname "$CUSTOM_PATH")"
EXT="${FIRST_MEDIAFILE##*.}"
[[ -z "$CUSTOM_PATH" ]] && OUTFILE="output.$EXT" || OUTFILE="$CUSTOM_PATH"
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"
CODE=$?
if [[ $CODE -ne 0 ]]; then
    rm -f "$OUTFILE"
    exit $CODE
fi
set +x

echo "Saved as $OUTFILE."
