#!/usr/bin/env sh
set -eu

GITEA="${GITEA_URL:-http://gitea:3000}"
ADMIN_USER="${GITEA_ADMIN_USER:-giteaadmin}"
ADMIN_PASS="${GITEA_ADMIN_PASSWORD:-giteaadmin-pass}"
ADMIN_EMAIL="${GITEA_ADMIN_EMAIL:-admin@example.test}"
ORG="${GITEA_ORG:-wiggleverse}"
BOT_USER="${GITEA_BOT_USER:-rfc-bot}"
BOT_PASS="${GITEA_BOT_PASSWORD:-rfc-bot-pass}"
CONTENT_REPO="${META_REPO:-ohm-content}"
APP_URL="${APP_URL:-http://localhost:8080}"
WEBHOOK_SECRET="${GITEA_WEBHOOK_SECRET:-tier1-webhook-secret}"
OUT="${SEED_OUT:-/seed/.env.tier1.generated}"

echo "seed: waiting for gitea at $GITEA"
i=0
while ! curl -sf "$GITEA/api/healthz" >/dev/null 2>&1; do
  i=$((i+1)); [ "$i" -gt 60 ] && echo "gitea never came up" && exit 1
  sleep 2
done

auth_admin() { curl -sf -u "$ADMIN_USER:$ADMIN_PASS" "$@"; }

echo "seed: ensuring bot user"
auth_admin -X POST "$GITEA/api/v1/admin/users" \
  -H 'Content-Type: application/json' \
  -d "{\"username\":\"$BOT_USER\",\"email\":\"$BOT_USER@example.test\",\"password\":\"$BOT_PASS\",\"must_change_password\":false}" \
  || echo "seed: bot user exists, continuing"

echo "seed: ensuring owner user (for OWNER_GITEA_LOGIN)"
auth_admin -X POST "$GITEA/api/v1/admin/users" \
  -H 'Content-Type: application/json' \
  -d "{\"username\":\"owner\",\"email\":\"owner@example.test\",\"password\":\"owner-pass\",\"must_change_password\":false}" \
  || echo "seed: owner exists, continuing"

echo "seed: minting bot access token"
TOKEN=$(curl -sf -u "$BOT_USER:$BOT_PASS" -X POST "$GITEA/api/v1/users/$BOT_USER/tokens" \
  -H 'Content-Type: application/json' \
  -d '{"name":"tier1-bot","scopes":["write:repository","write:organization","write:user","write:admin"]}' \
  | sed -n 's/.*"sha1":"\([^"]*\)".*/\1/p')
[ -n "$TOKEN" ] || { echo "seed: failed to mint bot token" ; exit 1; }

echo "seed: ensuring org $ORG (owned by bot)"
curl -sf -H "Authorization: token $TOKEN" -X POST "$GITEA/api/v1/orgs" \
  -H 'Content-Type: application/json' \
  -d "{\"username\":\"$ORG\"}" || echo "seed: org exists, continuing"

echo "seed: ensuring content repo $ORG/$CONTENT_REPO"
curl -sf -H "Authorization: token $TOKEN" -X POST "$GITEA/api/v1/orgs/$ORG/repos" \
  -H 'Content-Type: application/json' \
  -d "{\"name\":\"$CONTENT_REPO\",\"auto_init\":true,\"default_branch\":\"main\"}" \
  || echo "seed: content repo exists, continuing"

echo "seed: seeding one entry under rfcs/ so the catalog is non-empty"
B64=$(printf '%s' '---
title: Intro
status: graduated
id: RFC-0001
owners: [owner]
---

# Intro

Seed entry for Tier-1 e2e.
' | base64 | tr -d '\n')
curl -s -H "Authorization: token $TOKEN" -X POST \
  "$GITEA/api/v1/repos/$ORG/$CONTENT_REPO/contents/rfcs/intro.md" \
  -H 'Content-Type: application/json' \
  -d "{\"message\":\"seed intro\",\"content\":\"$B64\",\"branch\":\"main\"}" \
  || echo "seed: intro.md exists, continuing"

echo "seed: registering OAuth application"
OAUTH_JSON=$(curl -sf -u "$ADMIN_USER:$ADMIN_PASS" -X POST "$GITEA/api/v1/user/applications/oauth2" \
  -H 'Content-Type: application/json' \
  -d "{\"name\":\"rfc-app-tier1\",\"redirect_uris\":[\"$APP_URL/auth/callback\"],\"confidential_client\":true}")
CLIENT_ID=$(printf '%s' "$OAUTH_JSON" | sed -n 's/.*"client_id":"\([^"]*\)".*/\1/p')
CLIENT_SECRET=$(printf '%s' "$OAUTH_JSON" | sed -n 's/.*"client_secret":"\([^"]*\)".*/\1/p')

echo "seed: registering webhook on content repo -> backend"
curl -s -H "Authorization: token $TOKEN" -X POST \
  "$GITEA/api/v1/repos/$ORG/$CONTENT_REPO/hooks" \
  -H 'Content-Type: application/json' \
  -d "{\"type\":\"gitea\",\"active\":true,\"events\":[\"push\",\"pull_request\"],\"config\":{\"url\":\"http://backend:8000/api/webhooks/gitea\",\"content_type\":\"json\",\"secret\":\"$WEBHOOK_SECRET\"}}" \
  || echo "seed: webhook exists, continuing"

echo "seed: writing generated env to $OUT"
cat > "$OUT" <<EOF
GITEA_BOT_TOKEN=$TOKEN
OAUTH_CLIENT_ID=$CLIENT_ID
OAUTH_CLIENT_SECRET=$CLIENT_SECRET
EOF
echo "seed: done"
