#!/usr/bin/env bash

where="${1:-.}"

selection=$(find "$where" -type f | fzf --multi --preview 'ffprobe -v error -show_format -show_streams {}' --preview-window=up:wrap)

output_dir=$(find $HOME -type d ! -name '.*' ! -path '*/.*/*' | fzf --preview 'tree -C {}' --preview-window=up:wrap --prompt "Select output directory: ")

if gum confirm "Flatten the directory structure?";
then
    flatten=true
else
    flatten=false
fi

function transcode_job {
    local ifile="$1"
    local output_dir="$2"
    local flatten="$3"
    local where="$4"
    local fname=$(basename "$ifile")
    local segment=$(realpath --relative-to="$where" "$ifile")


    if [ "$flatten" = true ]; then
        output_file="$output_dir/$fname.mov"
    else
        output_file="$output_dir/$segment.mov"
    fi

    tmp_file=$(mktemp)

    mkdir -p "$(dirname "$output_file")"

    if ffmpeg -y -i "$ifile" -c:v dnxhd -profile:v dnxhr_hq -pix_fmt yuv422p -c:a pcm_s16le "$output_file" 2>> "$tmp_file";
    then
        rm -f "$tmp_file"
    else
        # gum log "Failed to transcode $ifile. Check ./error.log for details."
        cat "$tmp_file" >> error.log
        rm -f "$tmp_file"

    fi
}
export -f transcode_job

mapfile -t files <<< "$selection"
len=${#files[@]}
i=1
for file in "${files[@]}"; do
    if [[ -f "$file" ]]; then
        gum spin --spinner dot --title "[$i/$len] Transcoding $file" -- bash -c "source <(declare -f transcode_job); transcode_job \"$file\" \"$output_dir\" \"$flatten\" \"$where\""
    else
        echo "Skipping invalid file: $file" >&2
    fi
    ((i++))
done
