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

NODE_ID=${1:?usage: bootstrap.sh NODE_ID MAP_FILE}
MAP_FILE=${2:?usage: bootstrap.sh NODE_ID MAP_FILE}
test "$(id -u)" -eq 0
test -s "$MAP_FILE"

export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq ca-certificates curl git jq openssh-server python3 rsync unattended-upgrades

getent group guanghu >/dev/null || groupadd --system guanghu
for account in guanghu-authz guanghu-sentinel; do
  id -u "$account" >/dev/null 2>&1 || useradd --system --home /nonexistent --shell /usr/sbin/nologin "$account"
  usermod -aG guanghu "$account"
done

install -d -o root -g guanghu -m 750 /etc/guanghu /var/lib/guanghu
install -d -o root -g root -m 700 /etc/guanghu/secrets
install -d -o root -g root -m 755 /etc/guanghu/navigation-maps /opt/guanghu
install -m 644 "$MAP_FILE" "/etc/guanghu/navigation-maps/${NODE_ID}.json"

cat > /etc/guanghu/node.json <<EOF
{
  "schema": "guanghu.node/v1",
  "node_id": "${NODE_ID}",
  "upstream": "JD-FD-PRIMARY",
  "navigation_map": "/etc/guanghu/navigation-maps/${NODE_ID}.json",
  "secret_policy": "private material stays in /etc/guanghu/secrets"
}
EOF
chmod 644 /etc/guanghu/node.json

systemctl enable --now ssh unattended-upgrades
printf 'GUANGHU_NODE_READY=%s\n' "$NODE_ID"
