#!/usr/bin/env bash
set -euo pipefail

HUB_URL="${SHELLFLEET_HUB:-https://agent.vnstech.cloud}"
GROUP="${SHELLFLEET_GROUP:-/}"
PREFIX="${SHELLFLEET_PREFIX:-/opt/shellfleet-agent}"
BUNDLE_URL="${SHELLFLEET_BUNDLE_URL:-https://filesv.vnstech.cloud/shell-fleet-20260603.tgz}"
WORKDIR="$(mktemp -d)"
KEEP_WORKDIR="${SHELLFLEET_KEEP_WORKDIR:-0}"
PROXY="${SHELLFLEET_PROXY:-}"
AGENT_USER="${SHELLFLEET_AGENT_USER:-shellfleet-agent}"

cleanup() {
  if [ "${KEEP_WORKDIR}" != "1" ]; then rm -rf "$WORKDIR"; fi
}
trap cleanup EXIT

say() { printf '%s\n' "$*"; }
die() { printf 'Error: %s\n' "$*" >&2; exit 1; }

need_root() {
  [ "$(id -u)" -eq 0 ] || die 'Run with sudo/root. Example: curl -fsSL https://filesv.vnstech.cloud/install-shellfleet-agent-ubuntu.sh | sudo -E bash'
}

apt_install_if_missing() {
  missing=""
  for pkg in "$@"; do
    case "$pkg" in
      python3-venv) python3 -m venv --help >/dev/null 2>&1 || missing="$missing $pkg" ;;
      curl) command -v curl >/dev/null 2>&1 || missing="$missing $pkg" ;;
      tar) command -v tar >/dev/null 2>&1 || missing="$missing $pkg" ;;
      *) dpkg -s "$pkg" >/dev/null 2>&1 || missing="$missing $pkg" ;;
    esac
  done
  if [ -n "$missing" ]; then
    say "==> installing missing packages:$missing"
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y $missing
  fi
}

detect_proxy() {
  if [ -n "$PROXY" ]; then return 0; fi
  for name in HTTPS_PROXY https_proxy HTTP_PROXY http_proxy; do
    value="${!name:-}"
    if [ -n "$value" ]; then PROXY="$value"; return 0; fi
  done
  if command -v systemctl >/dev/null 2>&1; then
    for file in /etc/environment /etc/apt/apt.conf /etc/apt/apt.conf.d/*proxy* /etc/apt/apt.conf.d/*Proxy*; do
      [ -r "$file" ] || continue
      value="$(sed -n 's/.*\(https\?:\/\/[^"; ]*\).*/\1/p' "$file" | head -n 1 || true)"
      if [ -n "$value" ]; then PROXY="$value"; return 0; fi
    done
  fi
}

write_service() {
  cat > /etc/systemd/system/shellfleet-agent.service <<EOF_SERVICE
[Unit]
Description=Shell Fleet Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$AGENT_USER
Group=$AGENT_USER
Environment=SHELLFLEET_CONFIG=$PREFIX/agent.json
WorkingDirectory=$PREFIX
ExecStart=$PREFIX/start.sh
Restart=always
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=$PREFIX

[Install]
WantedBy=multi-user.target
EOF_SERVICE
  systemctl daemon-reload
  systemctl enable --now shellfleet-agent
}

need_root
if ! grep -qiE 'ubuntu|debian' /etc/os-release 2>/dev/null; then
  say 'Warning: this installer is intended for Ubuntu/Debian-like systems.'
fi
apt_install_if_missing curl tar python3-venv

detect_proxy
CURL_ARGS=(-fsSL --retry 3 --connect-timeout 15)
if [ -n "$PROXY" ]; then
  say "==> using proxy: $PROXY"
  CURL_ARGS+=(--proxy "$PROXY")
else
  say '==> no proxy detected; using direct connection'
fi

say "==> downloading Shell Fleet bundle"
curl "${CURL_ARGS[@]}" -o "$WORKDIR/shell-fleet.tgz" "$BUNDLE_URL"
tar -xzf "$WORKDIR/shell-fleet.tgz" -C "$WORKDIR"
[ -x "$WORKDIR/shell-fleet/install.sh" ] || die 'bundle is invalid: install.sh not found'

if ! id "$AGENT_USER" >/dev/null 2>&1; then
  useradd --system --home "$PREFIX" --shell /usr/sbin/nologin "$AGENT_USER"
fi
install -d -m 0750 -o "$AGENT_USER" -g "$AGENT_USER" "$PREFIX"

say "==> installing Python agent into $PREFIX"
python3 -m venv "$PREFIX/venv"
"$PREFIX/venv/bin/python" -m pip install --quiet --upgrade pip setuptools wheel
"$PREFIX/venv/bin/python" -m pip install --quiet "$WORKDIR/shell-fleet/protocol" "$WORKDIR/shell-fleet/agent"
"$PREFIX/venv/bin/python" -m pip install --quiet psutil 2>/dev/null || true

cat > "$PREFIX/start.sh" <<EOF_START
#!/usr/bin/env bash
export SHELLFLEET_CONFIG="$PREFIX/agent.json"
exec "$PREFIX/venv/bin/shellfleet-agent" run
EOF_START
chmod 750 "$PREFIX/start.sh"
chown -R "$AGENT_USER:$AGENT_USER" "$PREFIX"

say "==> enrolling agent to $HUB_URL"
say '    Use an admin or agent-role account from Shell Fleet.'
export SHELLFLEET_CONFIG="$PREFIX/agent.json"
ENROLL_ARGS=(enroll --hub "$HUB_URL" --group "$GROUP")
if [ -n "$PROXY" ]; then ENROLL_ARGS+=(--proxy "$PROXY"); fi
"$PREFIX/venv/bin/shellfleet-agent" "${ENROLL_ARGS[@]}"
chown "$AGENT_USER:$AGENT_USER" "$PREFIX/agent.json"
chmod 600 "$PREFIX/agent.json"

write_service
sleep 2
if ! systemctl is-active --quiet shellfleet-agent; then
  journalctl -u shellfleet-agent --no-pager -n 40 >&2 || true
  die 'shellfleet-agent service did not start'
fi

say ''
say 'Shell Fleet agent installed and running.'
say "Hub: $HUB_URL"
say "Config: $PREFIX/agent.json"
say 'Status: systemctl status shellfleet-agent'
say 'Logs:   journalctl -u shellfleet-agent -f'
