#!/bin/bash

# === Detect available terminal emulator ===
find_terminal() {
    for term in gnome-terminal konsole xfce4-terminal lxterminal x-terminal-emulator; do
        if command -v "$term" &> /dev/null; then
            echo "$term"
            return
        fi
    done
    echo ""
}

TERMINAL_EMULATOR=$(find_terminal)

if [ -z "$TERMINAL_EMULATOR" ]; then
    zenity --error \
        --title="❌ Terminal Not Found" \
        --text="Could not detect a supported terminal emulator.\nPlease install gnome-terminal, konsole, xfce4-terminal, or lxterminal."
    exit 1
fi

# === Clippy-style confirmation ===
zenity --question \
  --title="🧹🍺 Clippy's Check-In" \
  --width=400 \
  --text="Hi, I'm Clippy!\n\nIt looks like you want to uninstall Homebrew from your system.\n\nAre you *sure* you want to remove everything from:\n\n<b>/home/linuxbrew/</b>?\n\nThis action cannot be undone!" \
  --no-wrap

if [ $? -ne 0 ]; then
    zenity --info \
      --title="👍 Clippy Says No Worries!" \
      --text="Okay, I won’t uninstall anything.\nIf you change your mind, just run this again."
    exit 0
fi

# === Uninstall command ===
UNINSTALL_CMD='
echo "🧹 Clippy is uninstalling Homebrew from /home/linuxbrew/..."
sleep 1
sudo rm -rf /home/linuxbrew
EC=$?
if [ $EC -eq 0 ]; then
    echo
    echo "✅ Homebrew was successfully removed!"
else
    echo
    echo "❌ Failed to uninstall Homebrew (exit code $EC)."
fi
echo
echo "Press Enter to close this window..."
read
'

# === Launch the correct terminal ===
case "$TERMINAL_EMULATOR" in
    gnome-terminal)
        gnome-terminal -- bash -c "$UNINSTALL_CMD"
        ;;
    konsole)
        konsole -e bash -c "$UNINSTALL_CMD"
        ;;
    xfce4-terminal)
        xfce4-terminal -e "bash -c '$UNINSTALL_CMD'"
        ;;
    lxterminal)
        lxterminal -e bash -c "$UNINSTALL_CMD"
        ;;
    x-terminal-emulator)
        x-terminal-emulator -e bash -c "$UNINSTALL_CMD"
        ;;
    *)
        zenity --error \
            --title="❌ Terminal Error" \
            --text="Terminal detected but unsupported launch syntax: $TERMINAL_EMULATOR"
        exit 1
        ;;
esac

# === Final confirmation dialog ===
zenity --info \
  --title="🧹 All Done!" \
  --width=400 \
  --text="Clippy here!\n\nHomebrew has been uninstalled from your system.\nYou're all cleaned up. 💨"
