#!/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

INSTALL_COMMAND='echo "🍺 Installing Homebrew, please wait..."; /usr/bin/homebrew-installer; EC=$?; echo; [ $EC -eq 0 ] && echo "✅ Homebrew installation complete!" || echo "❌ Installer exited with code $EC"; echo; echo "Press Enter to close..."; read'

# === Clippy-style greeting ===
zenity --info \
  --title="🐧📦 Hi, I'm Clippy!" \
  --width=400 \
  --text="It looks like you're trying to install Homebrew on Linux!\n\nDon't worry, I got this. 🍺 I'll open a terminal and take care of it."

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

# === Final confirmation ===
zenity --info \
  --title="🎉 It's Done!" \
  --width=400 \
  --text="All done!\n\nHomebrew is now installed on your Linux system.\n