#!/bin/bash
# caddy-pihole-sync.sh
# Syncs all domain names from Caddyfile to Pi-hole local DNS entries.
# Replaces the NPM SQLite-based sync script.
#
# Usage:
#   ./caddy-pihole-sync.sh [--dry-run]
#
# Reads the Caddyfile, extracts domain blocks, and writes local DNS
# entries to both Pi-holes pointing all domains to the Caddy host IP.

set -euo pipefail

CADDY_IP="10.10.0.16"
CADDYFILE="/home/cal/caddy/Caddyfile"
PRIMARY_PIHOLE_CONTAINER="pihole"
SECONDARY_PIHOLE_HOST="ubuntu-manticore"
SECONDARY_PIHOLE_CONTAINER="pihole"
CUSTOM_LIST_PATH="/etc/pihole/custom.list"
DRY_RUN=false

if [[ "${1:-}" == "--dry-run" ]]; then
    DRY_RUN=true
fi

# Extract domain names from Caddyfile site blocks
# Matches lines like "subdomain.manticorum.com {" at the start of a block
extract_domains() {
    grep -oP '^[a-zA-Z0-9._-]+\.manticorum\.com' "$CADDYFILE" | sort -u
}

DOMAINS=$(extract_domains)

if [[ -z "$DOMAINS" ]]; then
    echo "ERROR: No domains found in $CADDYFILE"
    exit 1
fi

echo "=== Caddy -> Pi-hole DNS Sync ==="
echo "Caddy IP: $CADDY_IP"
echo "Domains found: $(echo "$DOMAINS" | wc -l)"
echo ""

# Build custom.list content (Pi-hole local DNS format: "IP domain")
CUSTOM_ENTRIES=""
while IFS= read -r domain; do
    CUSTOM_ENTRIES+="${CADDY_IP} ${domain}"$'\n'
    echo "  ${CADDY_IP} -> ${domain}"
done <<< "$DOMAINS"

if $DRY_RUN; then
    echo ""
    echo "[DRY RUN] Would write to both Pi-holes:"
    echo "$CUSTOM_ENTRIES"
    exit 0
fi

echo ""

# Sync to primary Pi-hole (local container)
echo "Syncing to primary Pi-hole..."
echo "$CUSTOM_ENTRIES" | docker exec -i "$PRIMARY_PIHOLE_CONTAINER" tee "$CUSTOM_LIST_PATH" > /dev/null
docker exec "$PRIMARY_PIHOLE_CONTAINER" pihole restartdns reload
echo "  Primary Pi-hole updated."

# Sync to secondary Pi-hole (remote host)
echo "Syncing to secondary Pi-hole ($SECONDARY_PIHOLE_HOST)..."
echo "$CUSTOM_ENTRIES" | ssh "$SECONDARY_PIHOLE_HOST" "docker exec -i $SECONDARY_PIHOLE_CONTAINER tee $CUSTOM_LIST_PATH > /dev/null"
ssh "$SECONDARY_PIHOLE_HOST" "docker exec $SECONDARY_PIHOLE_CONTAINER pihole restartdns reload"
echo "  Secondary Pi-hole updated."

echo ""
echo "Sync complete. $(echo "$DOMAINS" | wc -l) domains pointed to $CADDY_IP on both Pi-holes."
