#!/bin/bash
# List sites from registry, optionally filtered by batch and status.
# Usage: tools/shared/list-sites.sh [--batch ID] [--status "S1,S2"] [--registry PATH]

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
REGISTRY="$ROOT_DIR/.smbatcher/REGISTRY.md"

BATCH=""
STATUS=""

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --batch) BATCH="$2"; shift ;;
        --status) STATUS="$2"; shift ;;
        --registry) REGISTRY="$2"; shift ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

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

# AWK script to parse markdown table
# Table format: | Domain | Title | Description | Status | Batch | Updated |
# Indices (split by |):
# 1: (empty)
# 2: Domain
# 3: Title
# 4: Description
# 5: Status
# 6: Batch
# 7: Updated

awk -v batch="$BATCH" -v status="$STATUS" -F'|' '
BEGIN {
    # Parse comma-separated status into an array
    if (status != "") {
        n = split(status, s_arr, ",")
        for (i = 1; i <= n; i++) {
            # Trim whitespace from status list args
            gsub(/^ +| +$/, "", s_arr[i])
            statuses[s_arr[i]] = 1
        }
    }
}
$0 ~ /^\|/ && !/Domain/ && !/---/ {
    # Extract fields and trim whitespace
    d = $2; gsub(/^ +| +$/, "", d)
    s = $5; gsub(/^ +| +$/, "", s)
    b = $6; gsub(/^ +| +$/, "", b)

    # Filter by batch
    if (batch != "" && b != batch) next

    # Filter by status
    if (status != "" && !(s in statuses)) next

    # Output domain
    if (d != "") print d
}' "$REGISTRY"
