#!/usr/bin/env bash
# list_users.sh — показать текущих пользователей (имена + comment, без хешей)
# Usage: ./scripts/auth/list_users.sh
set -euo pipefail

# 3× dirname от $0 (.../scripts/auth/list_users.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"

if [[ ! -f "$SNIPPET" ]]; then
    echo "ERROR: snippet not found at $SNIPPET" >&2
    exit 1
fi

echo "Users in $SNIPPET:"
echo ""
printf "%-12s %s\n" "USERNAME" "COMMENT"
printf "%-12s %s\n" "--------" "-------"

# Extract lines that look like user entries (indented username + base64 hash + optional comment)
# Format: <spaces> username  <base64_hash>  # comment
grep -P '^\s+[a-z][a-z0-9-]+\s+[A-Za-z0-9+/]+=*' "$SNIPPET" | \
    sed -E 's/^\s+([a-z][a-z0-9-]+)\s+\S+\s*(#\s*)?(.*)$/\1\t\3/' | \
    while IFS=$'\t' read -r user comment; do
        printf "%-12s %s\n" "$user" "$comment"
    done

echo ""
TOTAL=$(grep -cP '^\s+[a-z][a-z0-9-]+\s+[A-Za-z0-9+/]+=*' "$SNIPPET" || true)
echo "Total: $TOTAL user(s)"
