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

NODE_ID=${NODE_ID:?NODE_ID is required}
NODE_NAME=${NODE_NAME:?NODE_NAME is required}
UPSTREAM_NODE=${UPSTREAM_NODE:-AW-GZ-001}
FORGEJO_VERSION=${FORGEJO_VERSION:-16.0.0}
FORGEJO_SHA256=${FORGEJO_SHA256:-c686f95df0b025d6075eaf4722f67179b945a1556acfc552408eeab624ed4f28}
FORGEJO_MIRROR=${FORGEJO_MIRROR:-https://code.forgejo.org/forgejo/forgejo/releases/download}
FORGEJO_BINARY_CACHE=${FORGEJO_BINARY_CACHE:-/var/cache/guanghu/forgejo-${FORGEJO_VERSION}-linux-amd64}
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
BACKUP_DIR=/var/backups/guanghu/bootstrap/$(date -u +%Y%m%dT%H%M%SZ)

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

install -d -m 0700 "$BACKUP_DIR"
for item in /etc/guanghu/node.json /etc/forgejo/app.ini /etc/systemd/system/forgejo.service; do
  [[ -f $item ]] && cp -a "$item" "$BACKUP_DIR/"
done

export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq ca-certificates curl git git-lfs jq nginx rsync sqlite3 unattended-upgrades
systemctl disable --now nginx.service || true

getent group git >/dev/null || groupadd --system git
id -u git >/dev/null 2>&1 || useradd --system --shell /bin/bash --gid git --home-dir /home/git --create-home git
install -d -o root -g root -m 0755 /etc/guanghu /etc/guanghu/navigation-maps /opt/guanghu
install -d -o root -g root -m 0700 /etc/guanghu/secrets /var/backups/guanghu/forgejo
install -d -o git -g git -m 0750 /var/lib/forgejo /var/lib/forgejo/data /var/lib/forgejo/log /var/lib/forgejo/custom
install -d -o root -g git -m 0750 /etc/forgejo

binary="forgejo-${FORGEJO_VERSION}-linux-amd64"
install -d -m 0755 "$(dirname "$FORGEJO_BINARY_CACHE")"
if ! printf '%s  %s\n' "$FORGEJO_SHA256" "$FORGEJO_BINARY_CACHE" | sha256sum -c - 2>/dev/null; then
  curl -fL --retry 20 --retry-all-errors --connect-timeout 15 --continue-at - \
    "$FORGEJO_MIRROR/v${FORGEJO_VERSION}/$binary" -o "$FORGEJO_BINARY_CACHE"
fi
printf '%s  %s\n' "$FORGEJO_SHA256" "$FORGEJO_BINARY_CACHE" | sha256sum -c -
install -m 0755 "$FORGEJO_BINARY_CACHE" /usr/local/bin/forgejo

install -m 0644 "$SCRIPT_DIR/forgejo.service" /etc/systemd/system/forgejo.service
install -m 0755 "$SCRIPT_DIR/backup.sh" /usr/local/sbin/guanghu-forgejo-backup
install -m 0755 "$SCRIPT_DIR/health-check.sh" /usr/local/sbin/guanghu-zero-sense-health

if [[ ! -f /etc/forgejo/app.ini ]]; then
  install -o root -g git -m 0640 "$SCRIPT_DIR/app.ini.template" /etc/forgejo/app.ini
  secret_key=$(forgejo generate secret SECRET_KEY)
  internal_token=$(forgejo generate secret INTERNAL_TOKEN)
  sed -i "s|__SECRET_KEY__|$secret_key|; s|__INTERNAL_TOKEN__|$internal_token|" /etc/forgejo/app.ini
fi

jq -n --arg node_id "$NODE_ID" --arg name "$NODE_NAME" --arg upstream "$UPSTREAM_NODE" \
  '{schema:"guanghu.node/v1",node_id:$node_id,display_name:$name,domain_id:"DOMAIN-ZS",upstream:$upstream,role:"zero-sense-human-command-team-node",owner_boundary:"member-owned; enterprise lighthouse routing only",navigation_map:("/etc/guanghu/navigation-maps/"+$node_id+".json"),secret_policy:"private material stays in /etc/guanghu/secrets"}' \
  > /etc/guanghu/node.json
chmod 0644 /etc/guanghu/node.json

jq -n --arg node_id "$NODE_ID" --arg upstream "$UPSTREAM_NODE" \
  '{schema:"guanghu.navigation-map/v1",node_id:$node_id,domain_id:"DOMAIN-ZS",upstream:$upstream,modules:[{code:"ZS-FRG-01",name:"member Forgejo",bind:"loopback:3000",owner:"systemd"},{code:"ZS-BKP-01",name:"daily backup",bind:"local-timer",owner:"systemd"}],mandatory_order:["read-navigation-map","ack-current-map","execute-registered-action"],forbidden:["public-forgejo-before-tls","secret-in-repository","cross-node-authorization","arbitrary-shell-through-authorization-api"]}' \
  > "/etc/guanghu/navigation-maps/${NODE_ID}.json"
chmod 0644 "/etc/guanghu/navigation-maps/${NODE_ID}.json"

cat > /etc/systemd/system/guanghu-forgejo-backup.service <<'EOF'
[Unit]
Description=Guanghu Forgejo consistent backup
After=forgejo.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/guanghu-forgejo-backup
EOF
cat > /etc/systemd/system/guanghu-forgejo-backup.timer <<'EOF'
[Unit]
Description=Daily Guanghu Forgejo backup
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=30m
[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable --now forgejo.service unattended-upgrades.service guanghu-forgejo-backup.timer
guanghu-zero-sense-health | tee "/var/lib/forgejo/health-${NODE_ID}-$(date -u +%Y%m%dT%H%M%SZ).json"
printf 'ZERO_SENSE_NODE_READY=%s\n' "$NODE_ID"
