#!/usr/bin/env bash
# sharekit-bootstrap.sh — single-command bootstrap for sharekit stack on a clean host.
#
# Idempotent. Safe to re-run. Designed for Hermes Agent scenarios where a new
# server instance gets a fresh sharekit deploy in <2 minutes.
#
# Assumes:
#   - this repo at /home/hermes/sharekit/  (file_server.py, mcp_server.py, .env)
#   - python venv at  /home/hermes/venv/
#   - nginx already configured (files.spannerjun.top + mcp.spannerjun.top)
#   - acme.sh already issuing certs for those two hostnames
#
# What it does:
#   1. chown sharekit + files to hermes:hermes
#   2. install two systemd services (sharekit-fileserver, sharekit-mcpserver)
#   3. enable + start them
#   4. wait for /health to respond
#   5. roll the hermes skills bundle into /home/hermes/files/skills/

set -euo pipefail

HERMES_USER="hermes"
SHAREKIT_HOME="/home/hermes/sharekit"
FILES_ROOT="/home/hermes/files"
VENV="/home/hermes/venv"

log() { echo "[sharekit-bootstrap] $*" >&2; }
die() { echo "[sharekit-bootstrap] FATAL: $*" >&2; exit 1; }

# --- preflight -----------------------------------------------------------
[ "$(id -u)" -eq 0 ] || die "must run as root (have sudo)"
id "$HERMES_USER" >/dev/null 2>&1 || die "user $HERMES_USER missing; run useradd first"
[ -d "$SHAREKIT_HOME" ] || die "missing $SHAREKIT_HOME"
[ -x "$VENV/bin/python" ] || die "missing venv at $VENV"
[ -f "$SHAREKIT_HOME/file_server.py" ] || die "missing $SHAREKIT_HOME/file_server.py"
[ -f "$SHAREKIT_HOME/mcp_server.py" ] || die "missing $SHAREKIT_HOME/mcp_server.py"

log "step 1: reown sharekit + files to $HERMES_USER"
chown -R "$HERMES_USER:$HERMES_USER" "$SHAREKIT_HOME" "$FILES_ROOT" "$VENV"

log "step 2: install systemd units"
cat > /etc/systemd/system/sharekit-fileserver.service <<EOF
[Unit]
Description=sharekit public file server (FastAPI, port 8789)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$HERMES_USER
Group=$HERMES_USER
WorkingDirectory=$SHAREKIT_HOME
Environment=SHARE_ROOT=$FILES_ROOT
Environment=SHARE_BIND_HOST=127.0.0.1
Environment=SHARE_BIND_PORT=8789
Environment=SHARE_MAX_UPLOAD_MB=512
Environment=SHARE_ROOT_TOKEN=
ExecStart=$VENV/bin/python $SHAREKIT_HOME/file_server.py
Restart=on-failure
RestartSec=3
LimitNOFILE=1048576
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=$FILES_ROOT

[Install]
WantedBy=multi-user.target
EOF

# Pull MCP allowed_hosts + litellm_master_key from /home/hermes/sharekit/.env
ALLOWED_HOSTS="mcp.spannerjun.top,127.0.0.1,localhost"
LITELLM_KEY=""
if [ -f "$SHAREKIT_HOME/.env" ]; then
  ALLOWED_HOSTS=$(grep -E "^SHARE_MCP_ALLOWED_HOSTS" "$SHAREKIT_HOME/.env" 2>/dev/null | cut -d= -f2- || echo "$ALLOWED_HOSTS")
  LITELLM_KEY=$(grep -E "^LITELLM_MASTER_KEY" "$SHAREKIT_HOME/.env" 2>/dev/null | cut -d= -f2- | tr -d '\n' || echo "")
fi

cat > /etc/systemd/system/sharekit-mcpserver.service <<EOF
[Unit]
Description=sharekit MCP server (FastMCP streamable-http, port 8790)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$HERMES_USER
Group=$HERMES_USER
WorkingDirectory=$SHAREKIT_HOME
Environment=SHARE_ROOT=$FILES_ROOT
Environment=SHARE_MCP_HOST=127.0.0.1
Environment=SHARE_MCP_PORT=8790
Environment=SHARE_MCP_TRANSPORT=streamable-http
Environment=SHARE_MCP_PATH=/mcp
Environment=SHARE_MCP_ALLOWED_HOSTS=$ALLOWED_HOSTS
Environment=MINIQUOTA_URL=http://127.0.0.1:8788
Environment=LITELLM_URL=http://127.0.0.1:4000
Environment=SHAREKIT_PUBLIC_BASE=https://files.spannerjun.top
Environment=LITELLM_MASTER_KEY=$LITELLM_KEY
$EXTRA_ENV_BLOCK
ExecStart=$VENV/bin/python $SHAREKIT_HOME/mcp_server.py --root $FILES_ROOT --host 127.0.0.1 --port 8790 --transport streamable-http
Restart=on-failure
RestartSec=3
LimitNOFILE=1048576
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict

[Install]
WantedBy=multi-user.target
EOF

log "step 3: enable + start"
systemctl daemon-reload
systemctl enable --now sharekit-fileserver.service
systemctl enable --now sharekit-mcpserver.service

log "step 4: wait for healthy"
for i in $(seq 1 30); do
  if curl -ksS --max-time 2 https://files.spannerjun.top/health 2>/dev/null | grep -q '"status":"ok"'; then
    log "fileserver healthy"
    break
  fi
  [ $i -eq 30 ] && die "fileserver did not become healthy in 30s"
  sleep 1
done

log "step 5: bundle hermes skills into /home/hermes/files/skills/"
mkdir -p "$FILES_ROOT/skills"
TS=$(date +%Y%m%d-%H%M)
BUNDLE="$FILES_ROOT/skills/hermes-skills-$TS.tar.gz"
if [ -d /root/.hermes/skills ]; then
  tar --exclude='__pycache__' -czf "$BUNDLE" -C /root/.hermes skills/
  chown "$HERMES_USER:$HERMES_USER" "$BUNDLE"
  log "bundled skills -> $BUNDLE ($(du -h "$BUNDLE" | cut -f1))"
else
  log "WARN: /root/.hermes/skills not present, skipping skill bundle"
fi

log "=== done ==="
systemctl status sharekit-fileserver --no-pager -n 2 | head
systemctl status sharekit-mcpserver --no-pager -n 2 | head
echo
echo "files server: https://files.spannerjun.top"
echo "mcp server:   https://mcp.spannerjun.top/mcp"
