#!/bin/bash
# AVL-MXe Universal DVD Stream Extractor
# Logic: Bit-perfect MPEG-2 extraction using mpv --stream-dump
# Concept by Glen MacArthur, coded by Google Gemini 3

# --- ASSETS ---
APP_ICON="/usr/local/share/icons/custom/dvdcopy-app.png"
WIN_ICON="/usr/local/share/icons/custom/dvdcopy.png"

# --- 1. AGNOSTIC PATH HANDLING ---
RAW_PATH="$1"
CLEAN_PATH=$(echo "$RAW_PATH" | sed 's|^file://||')
MOUNT_POINT=$(readlink -f "$CLEAN_PATH")

if [[ -d "$MOUNT_POINT" ]]; then
    DVD_DEV=$(findmnt -n -o SOURCE "$MOUNT_POINT")
fi

if [[ -z "$DVD_DEV" ]]; then
    DVD_DEV=$(lsblk -do NAME,TYPE | awk '/rom/ {print "/dev/"$1; exit}')
fi

[[ -z "$DVD_DEV" ]] && DVD_DEV="/dev/sr0"

# --- 2. DISC PROBING ---
if ! command -v lsdvd &> /dev/null; then
    yad --error --title="Dependency Missing" --text="Please install 'lsdvd'."
    exit 1
fi

PROBE_DATA=$(lsdvd -x "$DVD_DEV" 2>/dev/null)

# Check if lsdvd actually got data
if [[ -z "$PROBE_DATA" ]]; then
    yad --error --title="Read Error" --image="$APP_ICON" --window-icon="$WIN_ICON" \
        --text="Could not read <b>$DVD_DEV</b>.\n\nNote: Ensure the disc is inserted. If it is mounted, try unmounting it first."
    exit 1
fi

# ROBUST PARSER: Grabs Title Number and Duration, Strips commas.
# We only want lines starting with "Title:" and non-zero lengths.
TITLE_LIST=$(echo "$PROBE_DATA" | grep "^Title:" | awk '{print $2 "|" $4}' | tr -d ',' | awk -F'|' '$2 != "00:00:00.000" {print $0}')

if [[ -z "$TITLE_LIST" ]]; then
    yad --error --title="Parse Error" --text="No valid video titles found on this disc."
    exit 1
fi

# --- 3. SELECTION UI ---

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

# Fix: Strip leading zero so '01' becomes '1'
RAW_TITLE=$(echo "$CHOICE" | cut -d'|' -f1)
SELECTED_TITLE=$((10#$RAW_TITLE))

# --- 4. SAVE LOCATION ---
SAVE_PATH=$(yad --file --save --confirm-overwrite \
    --title="Save MPEG-2 Stream" \
    --window-icon="$WIN_ICON" --image="$APP_ICON" \
    --filename="$HOME/Videos/Archive_Title_${SELECTED_TITLE}.mpg")

[[ -z "$SAVE_PATH" ]] && exit 0

# --- 5. EXECUTION ---
terminology -T="Copying DVD MPEG-2 Stream... $SELECTED_TITLE" -e bash -c "
    echo 'Source: $DVD_DEV (Title $SELECTED_TITLE)';
    echo 'Destination: $SAVE_PATH';
    echo '------------------------------------------------';
    
    # We use --dvd-device explicitly and ensure the title is a clean integer
    mpv dvd://$SELECTED_TITLE --dvd-device='$DVD_DEV' --stream-dump='$SAVE_PATH';
    
    if [ \$? -eq 0 ]; then
        echo '------------------------------------------------';
        echo 'SUCCESS: Title extracted successfully.';
        sleep 2;
    else
        echo '------------------------------------------------';
        echo 'ERROR: Extraction failed.';
        read -p 'Press Enter to close...';
    fi"

notify-send "DVD Stream Extraction Complete!" --icon="$WIN_ICON"

exit 0