#!/usr/bin/env bash
# onx-pdns-promote — PowerDNS zone notify veya slave zone listesi
# Input:  {"action":"notify","zone":"example.com"} | {"action":"list-zones"}
# Output: {"ok":true,...}

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

require_root
require_cmd pdns_control
onx_json_input

ACTION="$(onx_json_field action 'notify')"

case "$ACTION" in
    notify)
        ZONE="$(onx_json_field zone)"
        [[ -z "$ZONE" ]] && onx_die 1 "zone zorunlu"
        onx_log "pdns-promote: notify zone=${ZONE}"
        RESULT=$(pdns_control notify "$ZONE" 2>&1) || onx_die 3 "pdns_control notify basarisiz: ${RESULT}"
        RESULT_JSON=$(printf '%s' "$RESULT" | jq -Rs '.')
        json_ok "{\"ok\":true,\"action\":\"notify\",\"zone\":\"${ZONE}\",\"result\":${RESULT_JSON}}"
        ;;

    list-zones)
        onx_log "pdns-promote: list-zones"
        ZONES_RAW=$(pdnsutil list-all-zones 2>/dev/null) || onx_die 3 "pdnsutil list-all-zones basarisiz"
        ZONES_JSON=$(printf '%s' "$ZONES_RAW" | jq -Rs 'split("\n") | map(select(. != ""))')
        json_ok "{\"ok\":true,\"action\":\"list-zones\",\"zones\":${ZONES_JSON}}"
        ;;

    *)
        onx_die 1 "Bilinmeyen action: '${ACTION}' (notify | list-zones)"
        ;;
esac
