#!/usr/bin/env bash
# InterLoop Vanilla Thin Shell Installer & Launcher
set -e

SERVER="${INTERLOOP_SERVER:-https://api.grepcode.net}"
TOKEN=""

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --server) SERVER="$2"; shift ;;
        --token) TOKEN="$2"; shift ;;
        *) shift ;;
    esac
    shift || true
done

INSTALL_DIR="$HOME/.interloop"
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

echo "📥 Downloading InterLoop Vanilla Thin Shell..."
curl -fsSL "${SERVER}/shell/interloop-shell.py" -o "$INSTALL_DIR/interloop-shell.py"
chmod +x "$INSTALL_DIR/interloop-shell.py"

# Only overwrite config if explicit --token was passed; otherwise keep existing or start in standby
if [[ -n "$TOKEN" ]]; then
cat << EOF > "$INSTALL_DIR/interloop-shell.json"
{
  "server_url": "${SERVER}",
  "token": "${TOKEN}",
  "tracking_enabled": true
}
EOF
fi

# Stop any prior instance so local port 127.0.0.1:19845 is cleanly bound
pkill -f "interloop-shell.py" 2>/dev/null || true
sleep 0.5

echo "🚀 Starting Vanilla Thin Shell daemon (listening on http://127.0.0.1:19845)..."
nohup python3 "$INSTALL_DIR/interloop-shell.py" --config "$INSTALL_DIR/interloop-shell.json" > "$INSTALL_DIR/shell.log" 2>&1 &
echo "🎉 Thin Shell is running in the background! (PID: $!)"
echo "   The Web GUI will automatically detect and configure this Thin Shell when you log in."
echo "   Logs: tail -f $INSTALL_DIR/shell.log"
