#!/bin/bash
# AVL-MXe DVD Authoring ONLY
# Logic: Uses an XML-style config to force NTSC compliance
# Updated: Automated .chapters.txt companion lookups

# 1. Input Check
IFS=$'\n' FILES=($(sort <<<"$*"))
unset IFS
[[ ${#FILES[@]} -lt 1 ]] && exit 1

# 2. MAIN SETTINGS DIALOG
MAIN_OPTIONS=$(yad --form \
    --title="FFmpeg DVD Author & ISO Builder" \
    --image="/usr/local/share/icons/custom/isoimage-app.png" \
    --window-icon="/usr/local/share/icons/custom/isoimage.png" \
    --width=500 --center \
    --text="<b>Author MPEG-2 DVD-compliant Files to ISO</b>" \
    --field="Volume Label (Max 32 chars):" "" \
    --field="Dual Layer (DVD-9) Mode:CHK" "FALSE" \
    --button="Start Authoring":10 \
    --button="Cancel":1)

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

VOL_LABEL=$(echo "$MAIN_OPTIONS" | cut -d'|' -f1)
IS_DVD9=$(echo "$MAIN_OPTIONS" | cut -d'|' -f2)

# --- PROCESSING LOOP ---
for INPUT_FILE in "${FILES[@]}"; do
    BASENAME="${INPUT_FILE%.*}"
    DVD_DIR="${BASENAME}_DVD_TEMP"
    
    # NEW: Create a sanitized VOB for dvdauthor
    TEMP_VOB="/tmp/sanitized_$(date +%s).vob"
    
    # Remux to DVD Program Stream (this adds the missing VOBU headers)
    ffmpeg -i "$INPUT_FILE" -target ntsc-dvd -codec copy -f dvd "$TEMP_VOB" -y
    
    # --- FIX: DYNAMIC LABELING & FILENAME ---
    if [[ -n "$VOL_LABEL" ]]; then
        # Use custom label for both filename and internal metadata
        ISO_OUT="${VOL_LABEL}.iso"
        CURRENT_LABEL="${VOL_LABEL:0:32}"
    else
        # Fallback to basename if YAD field was left empty
        ISO_OUT="${BASENAME}_DVD.iso"
        CURRENT_LABEL="${BASENAME:0:32}"
    fi
    
    # --- CHAPTER DETERMINATION GATEWAY ---
    # Look for a .chapters.txt sidecar companion file
    CHAPTERS_FILE="${BASENAME}.chapters.txt"

    if [[ -f "$CHAPTERS_FILE" ]]; then
        # Found custom chapter points! Pull string directly out of the file
        CHAPTERS=$(cat "$CHAPTERS_FILE")
    else
        # Fallback to original automatic 5-minute chapters if no sidecar file exists
        CHAPTERS="0,5:00,10:00,15:00,20:00,25:00,30:00,35:00,40:00,45:00,50:00,55:00,1:00:00,1:05:00,1:10:00,1:15:00,1:20:00,1:25:00,1:30:00,1:35:00,1:40:00,1:45:00,1:50:00,1:55:00,2:00:00,2:05:00,2:10:00,2:15:00,2:20:00,2:25:00,2:30:00,2:35:00,2:40:00,2:45:00,2:50:00,2:55:00,3:00:00"
    fi

    # --- XML CONFIG GENERATION ---
    CFG="/tmp/dvdauthor_$(date +%s).xml"
    cat <<EOF > "$CFG"
<dvdauthor dest="$DVD_DIR">
  <vmgm>
    <menus>
      <video format="ntsc" />
    </menus>
  </vmgm>
  <titleset>
    <titles>
      <video format="ntsc" />
      <pgc>
        <vob file="$TEMP_VOB" chapters="$CHAPTERS" />
      </pgc>
    </titles>
  </titleset>
</dvdauthor>
EOF

   # --- EXECUTION ---
   terminology -T="Authoring DVD to ISO" -e bash -c "
        rm -rf '$DVD_DIR'
        mkdir -p '$DVD_DIR'
        
        echo 'Step 1: Authoring DVD structure...'
        dvdauthor -x '$CFG'
        
        if [ \$? -ne 0 ]; then 
            echo 'ERROR: Authoring failed'
            rm -f '$TEMP_VOB'
            read
            exit 1
        fi
        
        # --- PLACE REMOVAL HERE ---
        # dvdauthor is done reading the VOB; we can free up the space now
        rm -f '$TEMP_VOB'
        
        echo 'Step 2: Mastering ISO as: $ISO_OUT'
        if [ '$IS_DVD9' = 'TRUE' ]; then
            genisoimage -dvd-video -udf -allow-limited-size -V '$CURRENT_LABEL' -o '$ISO_OUT' '$DVD_DIR'
        else
            genisoimage -dvd-video -V '$CURRENT_LABEL' -o '$ISO_OUT' '$DVD_DIR'
        fi
        
        if [ \$? -eq 0 ]; then
            echo 'SUCCESS!'
            rm -rf '$DVD_DIR'
            rm -f '$CFG'
            sleep 2
        else
            echo 'ISO Master Failed'
            rm -f '$CFG'
            read
        fi"
done

notify-send "Authoring MPEG-2 to DVD Complete!" --icon="/usr/local/share/icons/custom/isoimage.png"