#!/usr/bin/env bash

# Source the script 'common-functions.sh'.
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
ROOT_DIR=$(grep --only-matching "^.*scripts[^/]*" <<<"$SCRIPT_DIR")
source "$ROOT_DIR/common-functions.sh"

_main() {
    local input_files=""
    local output_dir=""

    # Execute initial checks.
    _check_dependencies "
        command=ffmpeg; pkg_manager=apt; package=ffmpeg |
        command=ffmpeg; pkg_manager=dnf; package=ffmpeg-free |
        command=ffmpeg; pkg_manager=pacman; package=ffmpeg |
        command=ffmpeg; pkg_manager=zypper; package=ffmpeg"
    _display_wait_box "2"
    input_files=$(_get_files "par_type=file; par_select_mime='audio/|video/'; par_min_items=2; par_sort_list=true")
    output_dir=$(_get_output_dir "par_use_same_dir=true")

    _main_task "$input_files" "$output_dir"
    _display_result_box "$output_dir"
}

_main_task() {
    local input_files=$1
    local output_dir=$2
    local output_file=""
    local std_output=""

    # Create the input list for the 'ffmpeg'.
    local temp_file=""
    temp_file=$(_get_temp_file)
    input_files="file '$input_files'"
    # shellcheck disable=SC2001
    input_files=$(sed "s|$FIELD_SEPARATOR|'${FIELD_SEPARATOR}file '|g" <<<"$input_files")
    _convert_filenames_to_text "$input_files" >"$temp_file"

    # Run the main process.
    output_file=$(_get_output_filename "Concatenated audio.wav" "$output_dir" "par_extension_opt=preserve")
    std_output=$(ffmpeg -hide_banner -y -f "concat" -safe 0 -i "$temp_file" -- "$output_file" 2>&1)
    _check_output "$?" "$std_output" "" "$output_file" || return 1
}

_main "$@"
