#!/usr/bin/env bash
# gitea-pr (24.07.2026): PR auf Gitea per REST-API anlegen — der EINZIGE Weg für
# Worker, einen Pull-Request zu erstellen. Kein Web-Login, kein Passwort: das
# HTTP-Token aus ~/.git-credentials reicht (Vorfall 23.07.: Wartung-Worker bat
# um das Gitea-Passwort für die Web-GUI und blockte — genau das nie wieder).
# Nutzung: gitea-pr <repo> <head-branch> "<titel>" ["<body>"] [base=main]
set -euo pipefail

REPO="${1:?Nutzung: gitea-pr <repo> <head-branch> \"<titel>\" [\"<body>\"] [base]}"
HEAD="${2:?head-branch fehlt}"
TITLE="${3:?titel fehlt}"
BODY="${4:-}"
BASE="${5:-main}"
OWNER="Hitonabi"
# Intern statt DDNS-Domain: die ist nachts (Zwangstrennung) oft nicht erreichbar.
HOST="http://192.168.178.153:3000"

creds="$(printf 'protocol=http\nhost=192.168.178.153:3000\n\n' | git credential fill)"
username="$(sed -n 's/^username=//p' <<<"$creds")"
password="$(sed -n 's/^password=//p' <<<"$creds")"
[ -n "$password" ] || { echo "FEHLER: kein Token in ~/.git-credentials gefunden" >&2; exit 1; }

payload="$(TITLE="$TITLE" BODY="$BODY" HEAD="$HEAD" BASE="$BASE" python3 -c '
import json, os
print(json.dumps({"title": os.environ["TITLE"], "body": os.environ["BODY"],
                  "head": os.environ["HEAD"], "base": os.environ["BASE"]}))')"

antwort="$(curl -sS -w '\n%{http_code}' -X POST \
  -u "$username:$password" -H "Content-Type: application/json" \
  -d "$payload" "$HOST/api/v1/repos/$OWNER/$REPO/pulls")"
status="${antwort##*$'\n'}"
koerper="${antwort%$'\n'*}"

if [ "$status" = "201" ]; then
    printf '%s' "$koerper" | python3 -c 'import json,sys; pr=json.load(sys.stdin); print("PR angelegt:", pr.get("html_url", pr.get("url", "?")))'
else
    echo "FEHLER: Gitea-API antwortete $status" >&2
    printf '%s\n' "$koerper" | head -c 600 >&2
    exit 1
fi
