#!/usr/bin/env bash
# onx-bind-zone-parse — BIND zone dosyasını JSON kayıt dizisine çevir
# Input:  {"zone_file":"/tmp/onx_cpanel_xxx/dnszones/domain.com.db"}
# Output: {"domain":"domain.com","record_count":N,"records":[{"name":"@","type":"A","ttl":14400,"rdata":"1.2.3.4"},...]}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib/common.sh"

require_root
require_cmd jq
onx_json_input

# ─── Parse input ─────────────────────────────────────────────────────────────
ZONE_FILE="$(onx_json_field zone_file)"
[[ -z "$ZONE_FILE" ]] && onx_die 1 "zone_file zorunlu"

ZONE_REAL="$(realpath -e "$ZONE_FILE" 2>/dev/null)" \
    || onx_die 1 "Zone dosyası bulunamadı: $ZONE_FILE"

[[ "$ZONE_REAL" == /tmp/* || "$ZONE_REAL" == /var/lib/onox/* ]] \
    || onx_die 1 "zone_file güvenli alanda değil: $ZONE_REAL"

[[ -f "$ZONE_REAL" ]] || onx_die 1 "zone_file bir dosya değil: $ZONE_REAL"

# ─── Derive domain from filename ─────────────────────────────────────────────
BASENAME="$(basename "$ZONE_REAL")"
DOMAIN="${BASENAME%.db}"

# ─── Parse BIND zone file → JSON records ─────────────────────────────────────
# Uses awk for line-by-line parsing; handles: A AAAA MX CNAME TXT NS SRV records
# Skips: SOA, RRSIG, NSEC, DNSKEY, DS

RECORDS_JSON="$(awk '
BEGIN {
    ttl_default = 14400
    print "["
    first = 1
}

# Skip comments and blank lines
/^;/ || /^$/ { next }

# $TTL directive
/^\$TTL/ {
    gsub(/[^0-9]/, "", $2)
    ttl_default = $2
    next
}

# Skip $ORIGIN, $GENERATE
/^\$/ { next }

# Remove inline comments
{ gsub(/[ \t]+;.*$/, "") }

# Skip SOA / DNSSEC meta records
/SOA|RRSIG|NSEC|DNSKEY|\bDS\b/ { next }

# Standard resource record: name [ttl] [IN] type rdata
/^[A-Za-z0-9@_\.*-]/ {
    name = $1
    idx  = 2

    # Optional TTL
    ttl = ttl_default
    if ($idx ~ /^[0-9]+$/) {
        ttl = $idx
        idx++
    }

    # Optional class (IN)
    if (toupper($idx) == "IN") idx++

    # Type
    type = toupper($idx)
    idx++

    # Remaining fields = rdata
    rdata = ""
    for (i = idx; i <= NF; i++) {
        if (i > idx) rdata = rdata " "
        rdata = rdata $i
    }

    # Skip unsupported types
    if (type == "SOA" || type == "RRSIG" || type == "NSEC" || type == "DNSKEY" || type == "DS") next

    # JSON escape rdata (basic: backslash and double-quote)
    gsub(/\\/, "\\\\", rdata)
    gsub(/"/, "\\\"", rdata)
    gsub(/\\/, "\\\\", name)
    gsub(/"/, "\\\"", name)

    if (!first) printf ","
    first = 0
    printf "{\"name\":\"%s\",\"type\":\"%s\",\"ttl\":%d,\"rdata\":\"%s\"}", name, type, ttl, rdata
    print ""
}

END {
    print "]"
}
' "$ZONE_REAL")"

RECORD_COUNT="$(echo "$RECORDS_JSON" | jq 'length' 2>/dev/null || echo 0)"

onx_log "bind-zone-parse: domain=${DOMAIN} file=${ZONE_REAL} records=${RECORD_COUNT}"

printf '{"domain":"%s","record_count":%s,"records":%s}\n' \
    "$DOMAIN" "$RECORD_COUNT" "$RECORDS_JSON"
