#!/usr/bin/env bash
set -euo pipefail
HUB_URL="${SHELLFLEET_HUB:-https://agent.vnstech.cloud}"
BUNDLE_URL="${SHELLFLEET_BUNDLE_URL:-https://agent.vnstech.cloud/dist/bundle.tgz}"
GROUP="${SHELLFLEET_GROUP:-/}"
PROXY="${SHELLFLEET_PROXY:-${HTTPS_PROXY:-${https_proxy:-}}}"
PREFIX="${SHELLFLEET_PREFIX:-$HOME/.shellfleet-agent}"
FILES_DIR="${SHELLFLEET_FILES:-$HOME/.shellfleet-files}"

say(){ printf '%s\n' "==> $*"; }
die(){ echo "error: $*" >&2; exit 1; }
PY="$(command -v python3.11 || command -v python3 || true)"; [ -n "$PY" ] || die "python3 required"
CURL=(curl -fsSL --retry 3); [ -z "$PROXY" ] || CURL+=(--proxy "$PROXY")
PIPX=(); [ -z "$PROXY" ] || PIPX=(--proxy "$PROXY")
OS="$(uname -s)"

say "Shell Fleet agent install  (hub: $HUB_URL)"
mkdir -p "$PREFIX" "$FILES_DIR"
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
say "downloading bundle from hub"
"${CURL[@]}" -o "$WORK/bundle.tgz" "$BUNDLE_URL"
tar -xzf "$WORK/bundle.tgz" -C "$WORK"
BDIR="$(find "$WORK" -maxdepth 3 -type d -name protocol -print -quit | sed 's#/protocol$##')"
[ -n "$BDIR" ] || die "bundle invalid (no protocol/)"

say "creating venv + installing agent"
"$PY" -m venv "$PREFIX/venv"
"$PREFIX/venv/bin/python" -m pip install -q ${PIPX[@]+"${PIPX[@]}"} --upgrade pip
"$PREFIX/venv/bin/python" -m pip install -q ${PIPX[@]+"${PIPX[@]}"} "$BDIR/protocol" "$BDIR/agent"
"$PREFIX/venv/bin/python" -m pip install -q ${PIPX[@]+"${PIPX[@]}"} psutil psycopg2-binary redis || true

cat > "$PREFIX/start.sh" <<EOF
#!/usr/bin/env bash
export SHELLFLEET_CONFIG="$PREFIX/agent.json"
export SHELLFLEET_FILES="$FILES_DIR"
exec "$PREFIX/venv/bin/shellfleet-agent" run
EOF
chmod +x "$PREFIX/start.sh"

export SHELLFLEET_CONFIG="$PREFIX/agent.json"
ENROLL=( "$PREFIX/venv/bin/shellfleet-agent" enroll --hub "$HUB_URL" --group "$GROUP" )
[ -z "$PROXY" ] || ENROLL+=(--proxy "$PROXY")
if grep -q '"token"' "$PREFIX/agent.json" 2>/dev/null; then
  say "already enrolled — reusing saved token"
elif [ -n "${SHELLFLEET_ENROLL_USER:-}" ] && [ -n "${SHELLFLEET_ENROLL_PASS:-}" ]; then
  say "enrolling (credentials from env)"; "${ENROLL[@]}"
elif [ -r /dev/tty ]; then
  say "enrolling (interactive)"; "${ENROLL[@]}" </dev/tty
else
  die "no token, no SHELLFLEET_ENROLL_USER/PASS, no terminal"
fi
chmod 600 "$PREFIX/agent.json" 2>/dev/null || true

# install a service that auto-restarts (so web upgrades just work)
if [ "$OS" = "Linux" ] && command -v systemctl >/dev/null 2>&1 && [ "$(id -u)" = 0 ]; then
  say "installing systemd service (system)"
  cat > /etc/systemd/system/shellfleet-agent.service <<EOF
[Unit]
Description=Shell Fleet Agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
Environment=SHELLFLEET_CONFIG=$PREFIX/agent.json
Environment=SHELLFLEET_FILES=$FILES_DIR
ExecStart=$PREFIX/start.sh
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload && systemctl enable --now shellfleet-agent
  say "status: systemctl status shellfleet-agent"
elif [ "$OS" = "Linux" ] && command -v systemctl >/dev/null 2>&1; then
  say "installing systemd service (user)"
  mkdir -p "$HOME/.config/systemd/user"
  cat > "$HOME/.config/systemd/user/shellfleet-agent.service" <<EOF
[Unit]
Description=Shell Fleet Agent
[Service]
ExecStart=$PREFIX/start.sh
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
EOF
  systemctl --user daemon-reload && systemctl --user enable --now shellfleet-agent
elif [ "$OS" = "Darwin" ]; then
  say "installing launchd LaunchAgent"
  PL="$HOME/Library/LaunchAgents/com.shellfleet.agent.plist"
  mkdir -p "$HOME/Library/LaunchAgents"
  cat > "$PL" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.shellfleet.agent</string>
  <key>ProgramArguments</key><array><string>$PREFIX/start.sh</string></array>
  <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>/tmp/shellfleet-agent.log</string>
  <key>StandardErrorPath</key><string>/tmp/shellfleet-agent.log</string>
</dict></plist>
EOF
  launchctl unload "$PL" 2>/dev/null || true
  launchctl load -w "$PL"
else
  say "no service manager — starting in background"
  nohup "$PREFIX/start.sh" >/tmp/shellfleet-agent.log 2>&1 &
fi
say "Done. Agent installed at $PREFIX"
