#!/usr/bin/env bash

set -euo pipefail

# Check args
if [ "$#" -lt 5 ]; then
    echo "Usage: $0 <src_dir> <dst_dir> <input_extension> <output_extension> <ffmpeg_cmd_template>"
    echo "Example:"
    echo '  ./batch_ffmpeg.sh ./in ./out mkv mp4 "ffmpeg -i {input} -c:v libx264 {output}"'
    exit 1
fi

SRC_DIR="$1"
DST_DIR="$2"
INPUT_EXT="$3"
OUTPUT_EXT="$4"
FFMPEG_TEMPLATE="$5"

# Ensure output dir exists
mkdir -p "$DST_DIR"
JOBFILE=$(mktemp)
THREADS=$(nproc)

if [ "$#" -eq 6 ]; then
	THREADS="$6"
fi

# Iterate through matching files
shopt -s nullglob
for infile in "$SRC_DIR"/*."$INPUT_EXT"; do
    filename=$(basename "$infile")
    base="${filename%.*}"
    outfile="$DST_DIR/$base"."$OUTPUT_EXT"

    # Replace placeholders in the template
    FFMPEG_CMD="${FFMPEG_TEMPLATE//\{input\}/"'$infile'"}"
    FFMPEG_CMD="${FFMPEG_CMD//\{output\}/"'$outfile'"}"

   # eval $FFMPEG_CMD

    echo "$FFMPEG_CMD" >> "$JOBFILE"
done

echo "Starting parallel processing with $THREADS threads..."

# Use GNU parallel if available
echo "$JOBFILE"
echo "using $THREADS threads"
cat "$JOBFILE"
parallel -j "$THREADS" < $JOBFILE

#rm "$JOBFILE"
