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

NODE_ID=${NODE_ID:-HE-GZ-001}
CACHE=${FORGEJO_BINARY_CACHE:-/var/cache/guanghu/forgejo-16.0.0-linux-amd64}
EXPECTED_SHA256=${FORGEJO_SHA256:-c686f95df0b025d6075eaf4722f67179b945a1556acfc552408eeab624ed4f28}
TEMPLATE_DIR=${TEMPLATE_DIR:-/root/guanghu-bootstrap/zero-sense-team-node}

printf '%s  %s\n' "$EXPECTED_SHA256" "$CACHE" | sha256sum -c -
install -m 0755 "$CACHE" /usr/local/bin/forgejo

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 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
install -d -m 0700 /var/backups/guanghu/forgejo

if [[ ! -f /etc/forgejo/app.ini ]]; then
  install -o root -g git -m 0640 "$TEMPLATE_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

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

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 guanghu-forgejo-backup.timer
sleep 2
guanghu-zero-sense-health | tee "/var/lib/forgejo/health-${NODE_ID}-$(date -u +%Y%m%dT%H%M%SZ).json"
guanghu-forgejo-backup
touch /var/lib/forgejo/FORGEJO_DEPLOYED_AND_VERIFIED
printf 'ZERO_SENSE_FORGEJO_READY=%s\n' "$NODE_ID"
