#!/bin/bash
# FFmpeg PipeWire Screen Capture
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3

# --- DEPENDENCY CHECK ---
if ! command -v pactl &> /dev/null; then
    yad --error --title="Missing Dependency" --text="This tool requires 'pulseaudio-utils' (pactl) to map PipeWire streams." --center
    exit 1
fi

# --- 1. DETECT ENVIRONMENT ARCHITECTURE (HARDENED) ---
# Check standard environment variables first
DE_CHECK=$(echo "$XDG_CURRENT_DESKTOP $DESKTOP_SESSION" | tr '[:upper:]' '[:lower:]')

IS_ENLIGHTENMENT=false
IS_MOKSHA=false

if [[ "$DE_CHECK" == *"moksha"* ]]; then
    IS_MOKSHA=true
elif [[ "$DE_CHECK" == *"enlightenment"* ]] || pgrep -x "enlightenment" &>/dev/null; then
    # If the string contains 'enlightenment' OR the binary is actively running, force true
    IS_ENLIGHTENMENT=true
fi

# --- 2. DETECT PIPEWIRE AUDIO SOURCES ---
AUDIO_SOURCES=()
while IFS= read -r line; do
    AUDIO_SOURCES+=("$line")
done < <(pactl list sources short | awk '{print $2}')

AUDIO_CB=$(IFS="!" ; echo "${AUDIO_SOURCES[*]}")

# --- 3. DETECT TARGET DESKTOP RESOLUTION ---
DETECTED_RES=$(xdotool getdisplaygeometry 2>/dev/null || echo "1920 1080")
CURRENT_W=$(echo "$DETECTED_RES" | awk '{print $1}')
CURRENT_H=$(echo "$DETECTED_RES" | awk '{print $2}')
DEFAULT_GEOM="${CURRENT_W}x${CURRENT_H}"

# --- 4. CONFIGURATION SELECTION DIALOG ---
CONFIG_OUT=$(yad --form \
    --title="FFmpeg Screen Capture" \
    --image="/usr/local/share/icons/custom/ffmpeg-app.png" \
    --window-icon="/usr/local/share/icons/custom/ffmpeg.png" \
    --width=600 --center \
    --text="<b>Screen Capture Settings</b>\n*Captures Screen as H.264+WAV in an MKV Container" \
    --field="Capture Resolution:" "$DEFAULT_GEOM" \
    --field="PipeWire Audio Source:CB" "$AUDIO_CB" \
    --field="Frame Rate (FPS):CB" "30!60" \
    --field="Record System Audio:CHK" "TRUE" \
    --button="Start Recording":10 \
    --button="Cancel":1)

[[ $? -ne 10 ]] && exit 0

TARGET_RES=$(echo "$CONFIG_OUT" | cut -d'|' -f1)
TARGET_SOURCE=$(echo "$CONFIG_OUT" | cut -d'|' -f2)
TARGET_FPS=$(echo "$CONFIG_OUT" | cut -d'|' -f3)
USE_AUDIO=$(echo "$CONFIG_OUT" | cut -d'|' -f4)

TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
OUTPUT_DIR="$HOME/Videos"
mkdir -p "$OUTPUT_DIR"
OUTPUT_FILE="${OUTPUT_DIR}/ScreenCapture_${TIMESTAMP}.mkv"

# --- 5. ASSEMBLE X11 FFMPEG GRABBER ---
FFMPEG_ARGS=(-y -f x11grab -video_size "$TARGET_RES" -framerate "$TARGET_FPS" -i :0.0)

if [[ "$USE_AUDIO" == "TRUE" && -n "$TARGET_SOURCE" ]]; then
    FFMPEG_ARGS+=(-f pulse -i "$TARGET_SOURCE")
    FFMPEG_ARGS+=(-c:v libx264 -preset ultrafast -crf 15 -pix_fmt yuv420p -c:a pcm_s16le)
else
    FFMPEG_ARGS+=(-c:v libx264 -preset ultrafast -crf 15 -pix_fmt yuv420p -an)
fi

# Run backend engine completely inside the unprivileged local user context
ffmpeg "${FFMPEG_ARGS[@]}" "$OUTPUT_FILE" &>/tmp/ffmpeg_screencast.log &
FFMPEG_PID=$!

sleep 1
if ! kill -0 "$FFMPEG_PID" 2>/dev/null; then
    yad --error --title="Capture Engine Error" \
        --text="FFmpeg failed to start recording.\nCheck <i>/tmp/ffmpeg_screencast.log</i> for details." --width=600 --center
    exit 1
fi

# --- 6. DYNAMIC CONTROLLER DISPATCH ---
# Explicit boolean flags prevent fallback leakage into the broken notification tray layer
if [ "$IS_ENLIGHTENMENT" = true ]; then
    # Enlightenment Pure Branch: Safe borderless micro-pill screen overlay bypass.
    yad --form --title="Recording Stream" \
        --width=180 --height=44 --undecorated --skip-taskbar --sticky --geometry=-10+10 \
        --text="🔴 <b>RECORDING...</b>" \
        --button="STOP CAPTURE:0" --text-align=center
else
    # Universal Tray Branch (Moksha, XFCE, Mate, Cinnamon, etc.):
    yad --notification \
        --image="media-record" \
        --text="FFmpeg Screen Recording Active...\nClick this tray icon to stop capture safely." \
        --command="kill -SIGINT $FFMPEG_PID"
fi

# Stop the engine cleanly as the native user space owner
kill -SIGINT $FFMPEG_PID 2>/dev/null
wait $FFMPEG_PID

# --- 7. COMPLETION NOTIFICATION ---
notify-send "Screen Capture Written to ~/Videos Folder!" --icon="/usr/local/share/icons/custom/ffmpeg.png"

exit 0