#!/usr/bin/env bash
# ZeroGravity — Linux setup
# Checks prerequisites, creates the zerogravity-ls system user for
# UID-scoped iptables isolation, and builds the release binary.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# ── 0. Dependency check ──
MISSING=()
for cmd in cargo curl jq gcc sudo iptables; do
    command -v "$cmd" &>/dev/null || MISSING+=("$cmd")
done
if [ ${#MISSING[@]} -gt 0 ]; then
    echo "✗ Missing dependencies: ${MISSING[*]}"
    echo "  Install them first, then re-run this script."
    exit 1
fi

# ── 1. Prerequisite check: Antigravity must be installed ──
LS_BINARY="${ZEROGRAVITY_LS_PATH:-/usr/share/antigravity/resources/app/extensions/antigravity/bin/language_server_linux_x64}"
echo "→ Checking for Antigravity installation…"
if [ ! -f "$LS_BINARY" ]; then
    echo ""
    echo "✗ Antigravity is not installed (or the LS binary is missing)."
    echo "  ZeroGravity requires a working Antigravity installation."
    echo "  The Language Server binary is bundled with the Antigravity app"
    echo "  and cannot be downloaded separately."
    echo ""
    echo "  Expected path:"
    echo "    $LS_BINARY"
    echo ""
    echo "  Install Antigravity first, then re-run this script."
    echo "  Alternatively, set ZEROGRAVITY_LS_PATH to a custom LS binary location."
    exit 1
fi
echo "  Found: $LS_BINARY"

# ── 2. System user for UID isolation ──
echo "→ Creating zerogravity-ls system user…"
if id -u zerogravity-ls &>/dev/null; then
    echo "  Already exists."
else
    sudo useradd --system --no-create-home --shell /usr/sbin/nologin zerogravity-ls
    echo "  Created."
fi

# ── 3. Sudoers rule (run commands as zerogravity-ls without password) ──
SUDOERS="/etc/sudoers.d/zerogravity"
echo "→ Installing sudoers rule…"
if [ -f "$SUDOERS" ]; then
    echo "  Already exists."
else
    echo "$USER ALL=(zerogravity-ls) NOPASSWD: ALL" | sudo tee "$SUDOERS" > /dev/null
    sudo chmod 0440 "$SUDOERS"
    echo "  Installed: $SUDOERS"
fi

# ── 4. Data directory permissions ──
echo "→ Setting up /tmp/zerogravity-standalone…"
sudo mkdir -p /tmp/zerogravity-standalone
sudo chmod 1777 /tmp/zerogravity-standalone

# ── 5. Config directory ──
echo "→ Setting up ~/.config/zerogravity…"
mkdir -p "$HOME/.config/zerogravity"

# ── 6. Build ──
echo "→ Building release binary…"
cd "$PROJECT_DIR"
cargo build --release 2>&1 | tail -1
echo ""
echo "✓ Setup complete. Start with: zg start"
