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

CENTER_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$CENTER_DIR"

mkdir -p secrets
chmod 700 secrets

write_secret() {
  local name="$1" value="$2"
  printf '%s\n' "$value" > "secrets/$name"
  chmod 600 "secrets/$name"
}

RPC_SECRET="$(openssl rand -hex 32)"
ADMIN_TOKEN="$(openssl rand -base64 32 | tr -d '\n')"
METRICS_TOKEN="$(openssl rand -base64 32 | tr -d '\n')"
ZOT_PASSWORD="$(openssl rand -hex 16)"
GITEA_PASSWORD="$(openssl rand -hex 16)"

write_secret garage-rpc-secret "$RPC_SECRET"
write_secret garage-admin-token "$ADMIN_TOKEN"
write_secret garage-metrics-token "$METRICS_TOKEN"
write_secret zot-admin-password "$ZOT_PASSWORD"
write_secret gitea-admin-password "$GITEA_PASSWORD"

if [ ! -f .env ]; then
  cp .env.example .env
fi

python3 - "$RPC_SECRET" "$ADMIN_TOKEN" "$METRICS_TOKEN" <<'PY'
import sys, pathlib
rpc, admin, metrics = sys.argv[1:4]
src = pathlib.Path("garage/garage.toml.template").read_text()
out = (src
  .replace("@RPC_SECRET@", rpc)
  .replace("@ADMIN_TOKEN@", admin)
  .replace("@METRICS_TOKEN@", metrics))
pathlib.Path("garage/garage.toml").write_text(out)
PY

htpasswd -bBn admin "$ZOT_PASSWORD" > zot/htpasswd
chmod 600 zot/htpasswd

echo
echo "secrets/ 写入完成，garage/garage.toml、zot/htpasswd 已渲染"
echo
echo "Zot:    admin / $ZOT_PASSWORD"
echo "Gitea:  admin / $GITEA_PASSWORD"
