#!/bin/bash
set -euo pipefail

DEBUG=false
ZONE="inxs.be"

usage() {
  cat <<EOF
Usage: $0 --add --hostname FQDN --ip IP_ADDRESS [--zone DOMAIN] [--debug]

Options:
  --add             Add DNS records
  --hostname NAME   Full hostname (e.g., vmx-down.inxs.be)
  --ip IP           IP address
  --zone DOMAIN     DNS zone (default: inxs.be)
  --debug           Enable debug output
  --help            Show this help
EOF
}

if [[ $EUID -ne 0 ]]; then
  echo "❌ This script must be run as root or with sudo privileges" >&2
  exit 1
fi

TECHNITIUM_API_CONF="/root/.technitium_api"
if [[ ! -f "$TECHNITIUM_API_CONF" ]]; then
  echo "❌ Missing Technitium credentials file: $TECHNITIUM_API_CONF" >&2
  exit 1
fi

TECHNITIUM_API_HOST="$(grep -E '^API_HOST=' "$TECHNITIUM_API_CONF" | cut -d'=' -f2-)"
TECHNITIUM_API_KEY="$(grep -E '^API_KEY=' "$TECHNITIUM_API_CONF" | cut -d'=' -f2-)"

ADD=false
HOSTNAME=""
IP=""

if [[ $# -eq 0 ]]; then usage; exit 1; fi

while [[ $# -gt 0 ]]; do
  case $1 in
    --add) ADD=true; shift ;;
    --hostname) HOSTNAME="$2"; shift 2 ;;
    --ip) IP="$2"; shift 2 ;;
    --zone) ZONE="$2"; shift 2 ;;
    --debug) DEBUG=true; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option: $1"; usage; exit 1 ;;
  esac
done

# --- Debug output ---
if [[ "$DEBUG" == true ]]; then
  set -x
  echo "🔍 Debug mode ON"
  echo "→ TECHNITIUM_API_HOST: $TECHNITIUM_API_HOST"
  echo "→ ZONE: $ZONE"
  echo "→ HOSTNAME: $HOSTNAME"
  echo "→ IP: $IP"
fi

# --- Validation ---
if [[ "$ADD" != true ]]; then echo "❌ Must specify --add"; usage; exit 1; fi
if [[ -z "$HOSTNAME" || -z "$IP" ]]; then echo "❌ --hostname and --ip are required"; usage; exit 1; fi
if [[ "$HOSTNAME" != *.$ZONE ]]; then echo "❌ Hostname must belong to the zone ($ZONE)"; exit 1; fi

SHORT_HOST="${HOSTNAME%%.$ZONE}"
CNAME_PREFIX="${SHORT_HOST#*-}"

# --- Check existing A record ---
existing_a=$(curl -s -H "X-API-Key: $TECHNITIUM_API_KEY" \
  "$TECHNITIUM_API_HOST/api/record/get?zone=$ZONE&type=A&name=$SHORT_HOST")

if [[ "$existing_a" == "[]" ]]; then
  echo "➕ Adding A record for $SHORT_HOST → $IP"
  response_a=$(curl -s -w "%{http_code}" -o /tmp/resp_a.json -X POST "$TECHNITIUM_API_HOST/api/record/add" \
    -H "X-API-Key: $TECHNITIUM_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"ZoneName\":\"$ZONE\",\"Name\":\"$SHORT_HOST\",\"Type\":\"A\",\"Address\":\"$IP\",\"TTL\":3600}")
  if [[ "$response_a" != "200" ]]; then
    echo "❌ Failed to add A record. HTTP $response_a"
    [[ "$DEBUG" == true ]] && cat /tmp/resp_a.json
    exit 1
  fi
else
  echo "✅ A record for $SHORT_HOST already exists. Skipping."
fi

# --- Check existing CNAME ---
existing_cname=$(curl -s -H "X-API-Key: $TECHNITIUM_API_KEY" \
  "$TECHNITIUM_API_HOST/api/record/get?zone=$ZONE&type=CNAME&name=$CNAME_PREFIX")

if [[ "$existing_cname" == "[]" ]]; then
  echo "➕ Adding CNAME $CNAME_PREFIX → $SHORT_HOST.$ZONE"
  response_cname=$(curl -s -w "%{http_code}" -o /tmp/resp_cname.json -X POST "$TECHNITIUM_API_HOST/api/record/add" \
    -H "X-API-Key: $TECHNITIUM_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"ZoneName\":\"$ZONE\",\"Name\":\"$CNAME_PREFIX\",\"Type\":\"CNAME\",\"Alias\":\"$SHORT_HOST.$ZONE\",\"TTL\":3600}")
  if [[ "$response_cname" != "200" ]]; then
    echo "❌ Failed to add CNAME record. HTTP $response_cname"
    [[ "$DEBUG" == true ]] && cat /tmp/resp_cname.json
    exit 1
  fi
else
  echo "✅ CNAME record for $CNAME_PREFIX already exists. Skipping."
fi

echo "🎉 Operation completed."