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

readonly stack_root="/srv/gitea-security"
readonly env_file="${ENV_FILE:-$stack_root/.env}"
readonly openresty_root="$stack_root/openresty"
readonly gitea_conf="$openresty_root/conf.d/gitea.conf"
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
readonly timestamp
readonly backup_dir="$stack_root/backups/rollback-$timestamp"

fail() {
  printf 'error=%s\n' "$1" >&2
  exit 1
}

[[ $(id -u) -eq 0 ]] || fail "run as root"
[[ -f "$env_file" ]] || fail "missing environment file: $env_file"
set -a
# shellcheck source=/dev/null
source "$env_file"
set +a
[[ "$PUBLIC_REPOSITORY" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ && "$PUBLIC_REPOSITORY" != *.git ]] || fail "PUBLIC_REPOSITORY must be org/repository without .git"

install -d -m 0700 "$backup_dir"
install -m 0644 "$gitea_conf" "$backup_dir/gitea.conf"
if grep -q 'server 127.0.0.1:19080;' "$gitea_conf"; then
  sed -i 's/server 127\.0\.0\.1:19080;/server 127.0.0.1:3000;/' "$gitea_conf"
fi
[[ "$(grep -c 'server 127.0.0.1:3000;' "$gitea_conf")" -eq 1 ]] || fail "direct Gitea upstream was not restored"
openresty -t -c "$openresty_root/nginx.conf"
systemctl reload openresty
(
  cd "$stack_root/openappsec"
  docker compose stop
)
status_code="$(curl --insecure --silent --show-error --resolve "$GIT_DOMAIN:443:127.0.0.1" -o /dev/null -w '%{http_code}' "https://$GIT_DOMAIN/$PUBLIC_REPOSITORY")"
[[ "$status_code" == 200 ]] || fail "direct Gitea check returned $status_code"
printf 'rollback=pass upstream=127.0.0.1:3000 openappsec=stopped backup=%s\n' "$backup_dir"
