#!/bin/bash


if [ -z "$TERM" ] || [ "$TERM" = "dumb" ]; then
    for term in gnome-terminal konsole xfce4-terminal xterm; do
        if command -v "$term" >/dev/null 2>&1; then
            exec "$term" -e "bash $0"
            exit 0
        fi
    done
    echo "Error: No terminal emulator found (gnome-terminal, konsole, xfce4-terminal, xterm)"
    exit 1
fi

# Make the script executable if not already
if [ ! -x "$0" ]; then
    chmod +x "$0" 2>/dev/null || {
        echo "Error: Cannot make script executable"
        exit 1
    }
fi

# Prompt for URL
read -p "Enter FRAMR URL: " url

# Validate URL format (http:// or https:// and basic structure)
if [[ ! "$url" =~ ^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$ ]]; then
    echo "Error: Invalid URL format"
    exit 1
fi
if ! host "$(echo "$url" | sed -E 's#^https?://([^/]+).*#\1#')" >/dev/null 2>&1; then
    echo "Error: Domain not resolvable"
    exit 1
fi

# Check for Chrome/Chromium
if command -v google-chrome >/dev/null 2>&1; then
    CHROME_PATH=$(command -v google-chrome)
elif command -v chromium-browser >/dev/null 2>&1; then
    CHROME_PATH=$(command -v chromium-browser)
else
    echo "Error: Chrome/Chromium not found"
    exit 1
fi

# Create autostart directory
AUTOSTART_DIR="$HOME/.config/autostart"
if ! mkdir -p "$AUTOSTART_DIR" 2>/dev/null; then
    echo "Error: Cannot create $AUTOSTART_DIR"
    exit 1
fi

# Check rw
if ! [ -w "$AUTOSTART_DIR" ]; then
    echo "Error: No write permission in $AUTOSTART_DIR"
    exit 1
fi

# Backup existing desktop file
DESKTOP_FILE="$AUTOSTART_DIR/chrome-kiosk.desktop"
if [ -f "$DESKTOP_FILE" ]; then
    cp "$DESKTOP_FILE" "$DESKTOP_FILE.bak-$(date +%F-%H%M%S)" 2>/dev/null || {
        echo "Error: Cannot backup existing config"
        exit 1
    }
fi

# Create desktop entry
cat > "$DESKTOP_FILE" << EOL
[Desktop Entry]
Type=Application
Name=Chrome Kiosk Mode
Exec=bash -c "sleep 10; xset s off; xset s noblank; [ -n \\\"\$GNOME_DESKTOP_SESSION_ID\\\" ] && gsettings set org.gnome.desktop.screensaver idle-activation-enabled false && gsettings set org.gnome.desktop.session idle-delay 0; [ -n \\\"\$KDE_FULL_SESSION\\\" ] && qdbus org.freedesktop.ScreenSaver /ScreenSaver SetActive false && qdbus org.freedesktop.ScreenSaver /ScreenSaver SetTimeout 0; [ -n \\\"\$XFCE_DESKTOP_SESSION\\\" ] && xfconf-query -c xfce4-power-manager -p /xfce4-power-manager/blank-on-ac -s 0; $CHROME_PATH --kiosk --autoplay-policy=no-user-gesture-required \\\"$url\\\""
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
X-KDE-autostart-after=panel
X-KDE-StartupNotify=false
Terminal=false
Comment=Launch Chrome in kiosk mode with specified URL and disable sleep/screensaver
EOL

# Set executable permissions for desktop file
chmod +x "$DESKTOP_FILE" 2>/dev/null || {
    echo "Error: Cannot set permissions on $DESKTOP_FILE"
    exit 1
}

echo "Setup complete. FRAMR will start on next login."