#!/bin/sh
# Isolated dev container only: temporarily remaps roles/headers and restarts APIs.
set -eu
B=http://localhost:8080
CF=/etc/signet/signet.conf
BACKUP=$(mktemp /tmp/signet-identity.XXXXXX)
cp "$CF" "$BACKUP"
stop_apis() {
	pkill -f '^kfcgi .* /run/signet/(api|pim).sock' 2>/dev/null || true
	pkill -f '^/usr/local/libexec/(signet-api|pim-api)' 2>/dev/null || true
	i=0
	while pgrep -f '^kfcgi .* /run/signet/(api|pim).sock' >/dev/null; do
		[ "$i" -lt 5 ] || return 1
		i=$((i + 1))
		sleep 1
	done
	rm -f /run/signet/api.sock /run/signet/pim.sock
}
start_apis() {
	kfcgi -d -n 2 -N 2 -s /run/signet/api.sock -u lighttpd -U signet -p / -- /usr/local/libexec/signet-api >>/proc/1/fd/2 2>&1 &
	api=$!
	kfcgi -d -n 1 -N 1 -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api >>/proc/1/fd/2 2>&1 &
	pim=$!
	i=0
	while [ ! -S /run/signet/api.sock ] || [ ! -S /run/signet/pim.sock ]; do
		kill -0 "$api" && kill -0 "$pim" && [ "$i" -lt 5 ] || return 1
		i=$((i + 1))
		sleep 1
	done
}
cleanup() {
	cp "$BACKUP" "$CF"
	stop_apis
	start_apis
	rm -f "$BACKUP" "$BACKUP.html" "$BACKUP.js"
}
trap cleanup 0
fail() { echo "FAIL - $*"; exit 1; }
status() {
	want=$1; shift
	got=$(curl -sS -o /tmp/identity-response -w '%{http_code}' "$@")
	[ "$got" = "$want" ] || fail "HTTP $got expected $want: $*"
}
for endpoint in api/me pim-api/me; do
	status 401 "$B/$endpoint"
	status 401 -H 'Remote-Groups: signet-admins' "$B/$endpoint"
	for user in '../admin' 'bad name' 'bad@user'; do
		status 401 -H "Remote-User: $user" -H 'Remote-Groups: signet-admins' "$B/$endpoint"
	done
	status 200 -H 'Remote-User: unaffiliated' "$B/$endpoint"
	jq -e '.user == "unaffiliated" and ([.roles[]] | all(. == false))' /tmp/identity-response >/dev/null || fail 'missing groups manufactured roles'
	status 200 -H 'Remote-User: unaffiliated' -H 'Remote-Groups: xsignet-adminsx,not-a-role' "$B/$endpoint"
	jq -e '[.roles[]] | all(. == false)' /tmp/identity-response >/dev/null || fail 'unknown group manufactured roles'
done
curl -fsS "$B/" > "$BACKUP.html"
curl -fsS "$B/app.js?v=beta-1" > "$BACKUP.js"
grep -F 'aria-label="Beta release">BETA</span>' "$BACKUP.html" >/dev/null || fail 'missing beta label'
grep -F 'Sign-in required' "$BACKUP.js" >/dev/null || fail 'missing sign-in state'
if grep -E "prompt\('Dev identity|prompt\('Groups \(comma separated\)" "$BACKUP.js" >/dev/null; then fail 'startup identity prompts remain'; fi
echo 'ok   - beta branding and prompt-free sign-in state served; missing identity still fails closed'
status 401 -H 'X-Requested-With: signet' -d '' "$B/api/docs"
status 401 -H 'X-Requested-With: signet' -d '' "$B/pim-api/attrs"
status 403 -H 'Remote-User: unaffiliated' -H 'X-Requested-With: signet' -d '' "$B/api/docs"
status 403 -H 'Remote-User: unaffiliated' -H 'X-Requested-With: signet' -d '' "$B/pim-api/resync"
status 200 -H 'Remote-User: unaffiliated' "$B/pim-api/attrs"
status 200 -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "$B/api/me"
jq -e '.roles == {drafter:true,signer:false,admin:false}' /tmp/identity-response >/dev/null || fail 'configured drafter roles'
echo 'ok   - absent/invalid identity fails closed in both APIs; absent/unknown groups grant no roles'

# No hardcoded role names and no CGI/environment dev backdoor.
awk '
$1 == "role.drafter" { print "role.drafter = test-drafter-13"; next }
$1 == "role.signer" { print "role.signer = test-signer-13"; next }
$1 == "role.admin" { print "role.admin = test-admin-13"; next }
$1 == "role.pim_admin" { print "role.pim_admin = test-pim-13"; next }
{ print }
' "$BACKUP" > "$CF"
export DEV_MODE=1 DEV_REMOTE_USER=admin DEV_REMOTE_GROUPS=signet-admins
stop_apis
start_apis
status 401 "$B/api/me"
status 401 "$B/pim-api/me"
status 200 -H 'Remote-User: root' -H 'Remote-Groups: signet-admins,clerks,management' "$B/api/me"
jq -e '[.roles[]] | all(. == false)' /tmp/identity-response >/dev/null || fail 'old groups still privileged'
status 200 -H 'Remote-User: asha' -H 'Remote-Groups: test-drafter-13,test-signer-13' "$B/api/me"
jq -e '.roles == {drafter:true,signer:true,admin:false}' /tmp/identity-response >/dev/null || fail 'remapped roles not honored'
status 200 -H 'Remote-User: root' -H 'Remote-Groups: test-admin-13' "$B/api/me"
jq -e '.roles.admin' /tmp/identity-response >/dev/null || fail 'remapped admin not honored'
status 403 -H 'Remote-User: root' -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d '' "$B/pim-api/resync"
status 200 -H 'Remote-User: pim' -H 'Remote-Groups: test-pim-13' "$B/pim-api/me"
jq -e '.roles.pim_admin' /tmp/identity-response >/dev/null || fail 'remapped PIM role not honored'
status 200 -H 'Remote-User: pim' -H 'Remote-Groups: test-pim-13' -H 'X-Requested-With: signet' --form-string org=IDENTITY13 --form-string key=contract --form-string type=text --form-string value=explicit "$B/pim-api/attrs"
echo 'ok   - roles are config-only; development environment variables cannot grant identity'

awk '
$1 == "role.drafter" { print "role.drafter = Office Staff, test-drafter-13"; next }
$1 == "role.pim_admin" { print "role.pim_admin = Office Staff, test-pim-13"; next }
{ print }
' "$CF" > "$CF.identity-tmp"
mv "$CF.identity-tmp" "$CF"
stop_apis
start_apis
for endpoint in api/me pim-api/me; do
	status 200 -H 'Remote-User: explicit' -H 'Remote-Groups: Office Staff' "$B/$endpoint"
	jq -e '[.roles[]] | any(. == true)' /tmp/identity-response >/dev/null || fail 'group containing spaces did not match'
	for groups in 'Delivery Staff' 'Staff' 'Office' 'office staff' 'test-drafter-13-other'; do
		status 200 -H 'Remote-User: explicit' -H "Remote-Groups: $groups" "$B/$endpoint"
		jq -e '[.roles[]] | all(. == false)' /tmp/identity-response >/dev/null || fail 'partial group name granted a role'
	done
	status 200 -H 'Remote-User: explicit' -H 'Remote-Groups: unrelated, Office Staff , test-signer-13' "$B/$endpoint"
	case $endpoint in
	api/me) jq -e '.roles.drafter and .roles.signer and (.roles.admin | not)' /tmp/identity-response >/dev/null ;;
	pim-api/me) jq -e '.roles.pim_admin' /tmp/identity-response >/dev/null ;;
	esac || fail 'comma-separated complete group names did not match'
done
echo 'ok   - group names containing spaces match exactly; shared words grant no roles'

awk '
$1 == "auth.user_header" { print "auth.user_header = Signet-Test-User"; next }
$1 == "auth.groups_header" { print "auth.groups_header = Signet-Test-Groups"; next }
{ print }
' "$CF" > "$CF.identity-tmp"
mv "$CF.identity-tmp" "$CF"
stop_apis
start_apis
for endpoint in api/me pim-api/me; do
	status 401 -H 'Remote-User: root' -H 'Remote-Groups: test-admin-13,test-pim-13' "$B/$endpoint"
	status 200 -H 'Signet-Test-User: explicit' "$B/$endpoint"
	jq -e '[.roles[]] | all(. == false)' /tmp/identity-response >/dev/null || fail 'custom missing groups privileged'
done
status 200 -H 'Signet-Test-User: explicit' -H 'Signet-Test-Groups: test-admin-13' "$B/api/me"
jq -e '.roles.admin' /tmp/identity-response >/dev/null || fail 'custom identity headers ignored'
status 200 -H 'Signet-Test-User: explicit' -H 'Signet-Test-Groups: test-pim-13' "$B/pim-api/me"
jq -e '.roles.pim_admin' /tmp/identity-response >/dev/null || fail 'custom PIM identity headers ignored'
echo 'ok   - configurable header names honored by both APIs'
echo 'identity contract: all passed'
