#!/usr/bin/env bash
# Generate strong, unique secrets for a Vallorix self-hosted deployment.
# Writes ./.env (single-line secrets + your config) and ./secrets/oauth2_signing_key.pem,
# and renders ./compose/seaweedfs/s3.json. Safe to re-run only on a FRESH install —
# re-running rotates secrets and will orphan existing encrypted data.
set -euo pipefail
cd "$(dirname "$0")"

if [ -f .env ] && ! [ "${FORCE:-0}" = "1" ]; then
  echo "Refusing to overwrite an existing .env (rotating secrets breaks existing data)." >&2
  echo "To regenerate on a fresh install: FORCE=1 ./generate-secrets.sh" >&2
  exit 1
fi

command -v openssl >/dev/null || { echo "openssl is required." >&2; exit 1; }

echo "Generating secrets…"
ENC=$(openssl rand -base64 32)
COOKIE=$(openssl rand -hex 32)
PEPPER=$(openssl rand -hex 32)
TRUST=$(openssl rand -hex 32)
PGPW=$(openssl rand -hex 24)
S3AK="vallorix-$(openssl rand -hex 4)"
S3SK=$(openssl rand -hex 24)

mkdir -p secrets compose/seaweedfs
chmod 700 secrets
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out secrets/oauth2_signing_key.pem 2>/dev/null
# 644 so the in-container app user (uid may differ from host) can read the bind-mount;
# host-side protection comes from the 700 secrets/ dir above.
chmod 644 secrets/oauth2_signing_key.pem

# Start .env from the example, then substitute the generated secret values.
cp .env.example .env
set_kv() { # key value  — replace "key=" line (value may contain / and +)
  awk -v k="$1" -v v="$2" 'BEGIN{FS=OFS="="} $1==k{print k"="v; next} {print}' .env > .env.tmp && mv .env.tmp .env
}
set_kv PROBOD_ENCRYPTION_KEY "$ENC"
set_kv PROBOD_AUTH_COOKIE_SECRET "$COOKIE"
set_kv PROBOD_AUTH_PASSWORD_PEPPER "$PEPPER"
set_kv PROBOD_TRUST_AUTH_TOKEN_SECRET "$TRUST"
set_kv POSTGRES_PASSWORD "$PGPW"
set_kv S3_ACCESS_KEY "$S3AK"
set_kv S3_SECRET_KEY "$S3SK"
chmod 600 .env

# Render the seaweedfs S3 identity file with the generated internal creds.
cat > compose/seaweedfs/s3.json <<JSON
{
  "identities": [
    {
      "name": "vallorix",
      "credentials": [
        { "accessKey": "${S3AK}", "secretKey": "${S3SK}" }
      ],
      "actions": ["Admin","Read","Write","List","Tagging","Lock"]
    }
  ]
}
JSON

echo "✓ Wrote .env (chmod 600), secrets/oauth2_signing_key.pem, compose/seaweedfs/s3.json"
echo
echo "Next:"
echo "  1) Review .env — set VALLORIX_BASE_URL, email, and LLM options."
echo "  2) Make sure an LLM endpoint is reachable (e.g. 'ollama serve && ollama pull llama3')."
echo "  3) docker compose up -d   (or: podman compose up -d)"
