#!/usr/bin/env nix-shell
#!nix-shell -i bash -p ffmpeg v4l-utils alsa-utils gnome.zenity lxterminal
set -euo pipefail

#if [[ -z ${_IS_IN_GUI:-} ]]; then
#    exec lxterminal --command "_IS_IN_GUI=1 $(printf "%q" "$(realpath "$0")")" &
#fi

video_devices=()
audio_devices=()

tab=$(printf '\t')
current_name=
while IFS= read line; do
    if ! [[ $line == "$tab"* ]]; then
        current_name="$line"
    else
        video_devices+=("$(echo "$line - $current_name" | xargs)")
    fi
done < <( v4l2-ctl --list-devices )

printf "%s\n" "${video_devices[@]}"

current_name=
current_device=
current_subdevice=
while IFS= read line; do
    if ! [[ $line == "  "* ]]; then
        current_name=$(echo $line | cut -d: -f2- | cut -c2-)
        current_device=$(echo $line | grep -E 'card [0-9]+:' -o | tr -dc '[:digit:]' || true)
    elif [[ $line == "  Subdevice #"* ]]; then
        current_subdevice=$(echo $line | grep -E 'Subdevice #[0-9]+:' -o | tr -dc '[:digit:]' || true)
        #audio_devices+=("$(echo "$line - $current_name" | xargs)")
        audio_devices+=("hw:$current_device,$current_subdevice - $current_name")
    else
        :
    fi
done < <( arecord -l )


printf "%s\n" "${audio_devices[@]}"


zenity_cells=()
maybe_true=TRUE
for video_device in "${video_devices[@]}"; do
    if grep <<<"$video_device" -q Elgato; then
        zenity_cells+=("$maybe_true")
        maybe_true=FALSE
    else
        zenity_cells+=(FALSE)
    fi
    zenity_cells+=("$video_device")
done
selected_video_device=$(
    zenity --list --text="Which video device" --radiolist --column=Select --column=Device "${zenity_cells[@]}" \
        | cut -d' ' -f1
)

zenity_cells=()
maybe_true=TRUE
for audio_device in "${audio_devices[@]}"; do
    if grep <<<"$audio_device" -q Elgato; then
        zenity_cells+=("$maybe_true")
        maybe_true=FALSE
    else
        zenity_cells+=(FALSE)
    fi
    zenity_cells+=("$audio_device")
done
selected_audio_device=$(
    zenity --list --text="Which audio device" --radiolist --column=Select --column=Device "${zenity_cells[@]}" \
        | cut -d' ' -f1
)

# TODO:
#     ffmpeg -f video4linux2 -list_formats all -i /dev/video3
#     [video4linux2,v4l2 @ 0x23ed7140] Raw       :     yuyv422 :           YUYV 4:2:2 : 1920x1080 1600x1200 1280x720 720x576 720x480 640x480
#     [video4linux2,v4l2 @ 0x23ed7140] Raw       :        nv12 :           Y/UV 4:2:0 : 3840x2160 2560x1440 1920x1080 1600x1200 1280x720 720x576 720x480 640x480

ffmpeg_common=(
    -fflags nobuffer
    -flags nobuffer
    -flags low_delay
    -strict experimental
)
ffmpeg_args=(
    -f v4l2
        -input_format nv12
        -video_size 1920x1080
        -framerate 60
        #-i /dev/video3
        -i "$selected_video_device"
    -f alsa
        #-i hw:5,0
        -i "$selected_audio_device"
)

set -x
ffmpeg "${ffmpeg_common[@]}" "${ffmpeg_args[@]}" -c copy -f nut pipe: | ffplay -framedrop "${ffmpeg_common[@]}" -f nut -i pipe:
