#!/usr/bin/env bash
# remove_user.sh — удалить пользователя из caddy/users.caddy.snippet
# Usage: ./scripts/auth/remove_user.sh <username>
#
# НЕ коммитит изменения — это задача разработчика.
set -euo pipefail

# 3× dirname от $0 (.../scripts/auth/remove_user.sh) → repo root. Bug fix 2026-05-26.
SCRIPT_DIR="$(cd "$(dirname "$(realpath "$0")")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SNIPPET="$REPO_ROOT/caddy/users.caddy.snippet"

usage() {
    echo "Usage: $0 <username>" >&2
    exit 1
}

[[ $# -lt 1 ]] && usage

USERNAME="$1"

# Validate username format: ^[a-z][a-z0-9_.-]{1,62}$ (matches add_user.sh, #427)
if ! [[ "$USERNAME" =~ ^[a-z][a-z0-9_.-]{1,62}$ ]]; then
    echo "ERROR: invalid username '$USERNAME'. Must match ^[a-z][a-z0-9_.-]{1,62}$" >&2
    exit 1
fi

# Escape regex metachars (notably the now-allowed '.') so the username is matched
# literally — otherwise `john.doe` could match/remove an unintended line (#427).
USERNAME_RE=$(printf '%s' "$USERNAME" | sed -E 's/[.[\^$*+?(){}|]/\\&/g')

# Check user exists
if ! grep -qP "^\s+${USERNAME_RE}\s" "$SNIPPET" 2>/dev/null; then
    echo "ERROR: user '$USERNAME' not found in $SNIPPET" >&2
    exit 1
fi

# Remove the line with this username (safe in-place via temp file)
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT

grep -vP "^\s+${USERNAME_RE}\s" "$SNIPPET" > "$TMP"
mv "$TMP" "$SNIPPET"

echo "Removed user '$USERNAME' from $SNIPPET"
echo ""
echo "Next steps:"
echo "  1. Commit caddy/users.caddy.snippet → PR → merge → GHA deploy"
echo "  2. After deploy, Caddy auto-reloads — user access revoked"
