#!/usr/bin/env bash
#
# onx-exim-vdomains-read — /etc/exim/virtual_domains icerigini oku
#
# UI'daki "Virtual Domains" tab'inin liste gostermesi icin.
#
# stdin: {} (bos)
# stdout: {"ok":true,"path":"...","domains":["d1","d2"],"count":N}

set -euo pipefail
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
source "${SCRIPT_DIR}/_lib/common.sh"

require_root

INPUT=$(cat 2>/dev/null || echo '{}')

VDOMAINS_FILE="/etc/exim/virtual_domains"

if [[ ! -r "$VDOMAINS_FILE" ]]; then
    # Dosya yoksa bos liste don — UI crash etmesin
    echo "{\"ok\":true,\"path\":\"${VDOMAINS_FILE}\",\"domains\":[],\"count\":0,\"exists\":false}"
    exit 0
fi

# Domains'i array olarak topla — bos satir + yorum (# prefix) atla
DOMAINS_JSON=$(awk '
    /^[[:space:]]*$/ { next }
    /^[[:space:]]*#/ { next }
    { gsub(/^[[:space:]]+|[[:space:]]+$/, ""); print }
' "$VDOMAINS_FILE" | jq -R -s -c 'split("\n") | map(select(length > 0))')

COUNT=$(echo "$DOMAINS_JSON" | jq 'length')

echo "{\"ok\":true,\"path\":\"${VDOMAINS_FILE}\",\"domains\":${DOMAINS_JSON},\"count\":${COUNT},\"exists\":true}"
exit 0
