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

# Guanghu lighthouse-node baseline: Ubuntu 22.04 / x86_64 / Node 20.
NODE_ID=${NODE_ID:-JD-FD-PRIMARY}
NODE_NAME=${NODE_NAME:-京东云北京 · 第五域国内主节点}
NODE_ROLES=${NODE_ROLES:-fd-primary,ops-center,lighthouse-node}
PROVIDER=${PROVIDER:-jdcloud}
REGION=${REGION:-beijing}
REPO_URL=${REPO_URL:-https://guanghulab.com/fifth-domain/bingshuo/fifth-domain.git}
REPO_BRANCH=${REPO_BRANCH:-main}
REPO_DIR=${REPO_DIR:-/opt/guanghu/fifth-domain}
BACKUP_DIR=/var/backups/guanghu/bootstrap/$(date -u +%Y%m%dT%H%M%SZ)

if [[ $EUID -ne 0 ]]; then echo "Run as root" >&2; exit 1; fi
. /etc/os-release
[[ ${ID:-} == ubuntu && ${VERSION_ID:-} == 22.04 ]] || { echo "Ubuntu 22.04 required" >&2; exit 1; }
[[ $(uname -m) == x86_64 ]] || { echo "x86_64 required" >&2; exit 1; }
[[ $NODE_ID =~ ^[A-Z0-9][A-Z0-9-]+$ ]] || { echo "Invalid NODE_ID" >&2; exit 1; }

mkdir -p "$BACKUP_DIR"
[[ -f /etc/guanghu/node.json ]] && cp -a /etc/guanghu/node.json "$BACKUP_DIR/node.json"
[[ -f /etc/guanghu/gatekeeper.env ]] && cp -a /etc/guanghu/gatekeeper.env "$BACKUP_DIR/gatekeeper.env"
[[ -f /etc/systemd/system/guanghu-gatekeeper.service ]] && cp -a /etc/systemd/system/guanghu-gatekeeper.service "$BACKUP_DIR/guanghu-gatekeeper.service"

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y ca-certificates curl git jq rsync unzip gnupg docker.io nginx python3 python3-venv
systemctl disable --now nginx.service || true
systemctl enable --now docker.service

node_major=$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)
if (( node_major < 20 )); then
  install -d -m 0755 /etc/apt/keyrings
  curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor --yes -o /etc/apt/keyrings/nodesource.gpg
  echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" > /etc/apt/sources.list.d/nodesource.list
  apt-get update
  apt-get install -y nodejs
fi

id -u guanghu >/dev/null 2>&1 || useradd --system --home /var/lib/guanghu --create-home --shell /usr/sbin/nologin guanghu
mkdir -p /opt/guanghu /etc/guanghu/secrets /var/lib/guanghu/gatekeeper /var/lib/guanghu/receipts /var/log/guanghu
chmod 0700 /etc/guanghu/secrets /var/lib/guanghu/gatekeeper
chown -R guanghu:guanghu /var/lib/guanghu /var/log/guanghu

if [[ -d "$REPO_DIR/.git" ]]; then
  git -C "$REPO_DIR" fetch --prune origin "$REPO_BRANCH"
  git -C "$REPO_DIR" reset --hard "origin/$REPO_BRANCH"
else
  rm -rf "$REPO_DIR"
  git clone --filter=blob:none --branch "$REPO_BRANCH" "$REPO_URL" "$REPO_DIR"
fi

roles_json=$(printf '%s' "$NODE_ROLES" | jq -Rc 'split(",") | map(select(length > 0))')
jq -n \
  --arg node_id "$NODE_ID" --arg display_name "$NODE_NAME" \
  --arg provider "$PROVIDER" --arg region "$REGION" --argjson roles "$roles_json" \
  '{schema:"guanghu.node/v1",node_id:$node_id,display_name:$display_name,owner:"ICE-GL∞",controller_persona:"ICE-GL-ZY001",provider:$provider,region:$region,roles:$roles,runtime:{os:"Ubuntu 22.04",arch:"x86_64",gatekeeper_bind:"127.0.0.1:3911"},credentials:{policy:"private material stays in /etc/guanghu/secrets",key_ids:[]}}' \
  > /etc/guanghu/node.json
chmod 0640 /etc/guanghu/node.json
chown root:guanghu /etc/guanghu/node.json

if [[ ! -f /etc/guanghu/gatekeeper.env ]]; then
  printf 'GATEKEEPER_SERVER_ID=%s\n' "$NODE_ID" > /etc/guanghu/gatekeeper.env
fi
chmod 0640 /etc/guanghu/gatekeeper.env
chown root:guanghu /etc/guanghu/gatekeeper.env

install -m 0644 "$REPO_DIR/server-tools/light-lake-node-bootstrap/guanghu-gatekeeper.service" /etc/systemd/system/guanghu-gatekeeper.service
install -m 0755 "$REPO_DIR/server-tools/light-lake-node-bootstrap/health-check.sh" /usr/local/sbin/guanghu-node-health
install -m 0755 "$REPO_DIR/server-tools/light-lake-node-bootstrap/rollback.sh" /usr/local/sbin/guanghu-node-rollback
systemctl daemon-reload
systemctl enable --now guanghu-gatekeeper.service

"$REPO_DIR/server-tools/light-lake-node-bootstrap/health-check.sh" | tee "/var/lib/guanghu/receipts/bootstrap-$(date -u +%Y%m%dT%H%M%SZ).json"
echo "Guanghu lighthouse node baseline installed: $NODE_ID"
