#!/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_max_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=""
    local file_1=""
    local file_2=""

    file_1=$(cut -d "$FIELD_SEPARATOR" -f 1 <<<"$input_files")
    file_2=$(cut -d "$FIELD_SEPARATOR" -f 2 <<<"$input_files")

    # Run the main process.
    output_file=$(_get_output_filename "Mixed audio.wav" "$output_dir" "par_extension_opt=preserve")
    std_output=$(ffmpeg -hide_banner -y -i "$file_1" -i "$file_2" -filter_complex "amix=inputs=2:duration=longest" -- "$output_file" 2>&1)
    _check_output "$?" "$std_output" "" "$output_file" || return 1
}

_main "$@"
