#!/bin/bash
# ESP32 Watch Dogs — one-line installer
# curl -sL https://locosp.github.io/WDGoNG/install | sudo bash

set -e

GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

err() {
    echo -e "${RED}[error]${NC} $1" >&2
    exit 1
}

warn() {
    echo -e "${YELLOW}[warn]${NC} $1" >&2
}

# Pre-flight checks
[ "$(uname)" = "Linux" ] || err "Only Linux is supported (uConsole / Raspberry Pi OS / Debian / Ubuntu)."
command -v git >/dev/null 2>&1 || err "git is required. Install with: apt-get install git"
command -v bash >/dev/null 2>&1 || err "bash is required."

# Resolve install user (works under sudo and non-sudo)
TARGET_USER="${SUDO_USER:-$(whoami)}"
TARGET_HOME=$(getent passwd "$TARGET_USER" | cut -d: -f6)
[ -n "$TARGET_HOME" ] || err "Cannot resolve home directory for user '$TARGET_USER'."

INSTALL_DIR="${INSTALL_DIR:-$TARGET_HOME/python/WDGoNG}"
EXPECT_REMOTE_HTTPS="https://github.com/LOCOSP/WDGoNG.git"
EXPECT_REMOTE_SSH="git@github.com:LOCOSP/WDGoNG.git"

echo -e "${CYAN}"
echo "  ██╗    ██╗ █████╗ ████████╗ ██████╗██╗  ██╗"
echo "  ██║    ██║██╔══██╗╚══██╔══╝██╔════╝██║  ██║"
echo "  ██║ █╗ ██║███████║   ██║   ██║     ███████║"
echo "  ██║███╗██║██╔══██║   ██║   ██║     ██╔══██║"
echo "  ╚███╔███╔╝██║  ██║   ██║   ╚██████╗██║  ██║"
echo "   ╚══╝╚══╝ ╚═╝  ╚═╝   ╚═╝    ╚═════╝╚═╝  ╚═╝"
echo -e "  ${GREEN}DOGS GO${CYAN} — Open-World Hacking RPG${NC}"
echo ""
echo "  Install dir: $INSTALL_DIR"
echo "  Target user: $TARGET_USER"
echo ""

echo -e "${GREEN}[1/3]${NC} Cloning repository..."
if [ -d "$INSTALL_DIR/.git" ]; then
    cd "$INSTALL_DIR" || err "Cannot enter $INSTALL_DIR"
    # Only trust an existing checkout if it is OUR repo. Otherwise its setup.sh
    # (which we run as root below) could be anything an attacker left there.
    origin=$(sudo -u "$TARGET_USER" git remote get-url origin 2>/dev/null || echo "")
    if [ "$origin" != "$EXPECT_REMOTE_HTTPS" ] && [ "$origin" != "$EXPECT_REMOTE_SSH" ]; then
        err "$INSTALL_DIR is a git repo but its origin is '$origin', not the WDGoNG repo. Remove it or set INSTALL_DIR=... to a fresh path."
    fi
    echo "  Directory exists — pulling latest..."
    # A failed update must abort: never fall through to run a stale/untrusted setup.
    sudo -u "$TARGET_USER" git pull --ff-only origin main \
        || err "git pull failed — aborting so we do not run an outdated copy. Fix the repo and re-run."
elif [ -d "$INSTALL_DIR" ]; then
    err "$INSTALL_DIR exists but is not a git repo. Remove it first or set INSTALL_DIR=..."
else
    mkdir -p "$(dirname "$INSTALL_DIR")"
    chown "$TARGET_USER:$TARGET_USER" "$(dirname "$INSTALL_DIR")" 2>/dev/null || true
    if ! sudo -u "$TARGET_USER" git clone https://github.com/LOCOSP/WDGoNG.git "$INSTALL_DIR"; then
        err "git clone failed — check internet connection and try again"
    fi
    cd "$INSTALL_DIR" || err "Cannot enter $INSTALL_DIR after clone"
fi

echo ""
echo -e "${GREEN}[2/3]${NC} Running setup (this may take a few minutes)..."
cd "$INSTALL_DIR" || err "Cannot enter $INSTALL_DIR"
# Integrity gate: the working tree must match exactly what git fetched. Any local
# change (a planted setup.sh, a swapped file) means tampering — refuse to run it.
if [ -n "$(sudo -u "$TARGET_USER" git status --porcelain 2>/dev/null)" ]; then
    err "$INSTALL_DIR has local modifications — refusing to run setup. Run 'git reset --hard origin/main' there and retry."
fi
# Run setup AS THE TARGET USER, never as root: setup.sh uses sudo only for the
# few system steps that need it, so a tampered copy can at most run with the
# user's own rights, not root's. It also keeps .venv owned by the user.
if ! sudo -u "$TARGET_USER" bash setup.sh; then
    err "setup.sh failed — see errors above. Re-run: cd $INSTALL_DIR && bash setup.sh"
fi

echo ""
echo -e "${GREEN}[3/3]${NC} Creating desktop launcher..."
DESKTOP_DIR="$TARGET_HOME/Desktop"
if [ -d "$DESKTOP_DIR" ]; then
    DESKTOP_FILE="$DESKTOP_DIR/watchdogs.desktop"
    cat > "$DESKTOP_FILE" << DESKTOP
[Desktop Entry]
Name=Watch Dogs Go
Comment=Open-World Hacking RPG
Exec=lxterminal --title="ESP32 Watch Dogs" -e bash -c "cd $INSTALL_DIR && sudo -E ./run.sh; read -p 'Press Enter to close...'"
Terminal=false
Type=Application
Categories=Game;Security;
Icon=$INSTALL_DIR/assets/icon.png
DESKTOP
    chmod +x "$DESKTOP_FILE" 2>/dev/null || true
    chown "$TARGET_USER:$TARGET_USER" "$DESKTOP_FILE" 2>/dev/null || true
    echo "  Created: $DESKTOP_FILE"
else
    warn "No Desktop folder at $DESKTOP_DIR — skipping launcher"
fi

echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║         Installation complete!              ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${CYAN}To start:${NC}  cd $INSTALL_DIR && sudo ./run.sh"
if [ -d "$DESKTOP_DIR" ]; then
    echo -e "  ${CYAN}Desktop:${NC}  Double-click Watch Dogs Go on desktop"
fi
echo ""
echo -e "  ${YELLOW}Optional:${NC} edit secrets.conf for API keys (Wigle, WPA-sec)"
echo -e "           cp secrets.conf.example secrets.conf && nano secrets.conf"
echo ""
echo -e "  ${GREEN}// real hacking is cooler than simulated${NC}"
echo ""
