#!/bin/bash
# ============================================================================
# Pounce DNS Server Setup (CoreDNS)
# ============================================================================
# This script sets up CoreDNS as an authoritative DNS server for Yield domains.
# Users point their domains' NS records to ns1.pounce.ch and ns2.pounce.ch,
# which both resolve to this server's IP.
#
# Usage: sudo bash setup_dns_server.sh
# ============================================================================

set -e

echo "=========================================="
echo "Pounce DNS Server Setup (CoreDNS)"
echo "=========================================="

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "ERROR: Please run as root (sudo)"
    exit 1
fi

SERVER_IP="46.235.147.194"
COREDNS_VERSION="1.11.1"
COREDNS_DIR="/opt/coredns"
ZONES_DIR="/opt/coredns/zones"

echo "[1/6] Installing dependencies..."
apt-get update -qq
apt-get install -y -qq wget curl jq

echo "[2/6] Downloading CoreDNS ${COREDNS_VERSION}..."
mkdir -p "$COREDNS_DIR"
cd "$COREDNS_DIR"

if [ ! -f "coredns" ]; then
    wget -q "https://github.com/coredns/coredns/releases/download/v${COREDNS_VERSION}/coredns_${COREDNS_VERSION}_linux_amd64.tgz"
    tar -xzf "coredns_${COREDNS_VERSION}_linux_amd64.tgz"
    rm "coredns_${COREDNS_VERSION}_linux_amd64.tgz"
    chmod +x coredns
fi

echo "[3/6] Creating zone directory..."
mkdir -p "$ZONES_DIR"

echo "[4/6] Creating CoreDNS config (Corefile)..."
cat > "$COREDNS_DIR/Corefile" << 'COREFILE'
# CoreDNS Configuration for Pounce Yield
# Serves authoritative DNS for delegated yield domains

# Default zone - serves A record pointing to our server
. {
    # Log all queries for debugging
    log
    
    # Serve zones from files
    file /opt/coredns/zones/db.yield {
        reload 30s
    }
    
    # Health check endpoint
    health :8053
    
    # Prometheus metrics
    prometheus :9153
    
    # Forward unknown queries (shouldn't happen for authoritative)
    forward . 8.8.8.8 8.8.4.4 {
        max_concurrent 1000
    }
    
    # Cache responses
    cache 300
    
    # Error handling
    errors
}
COREFILE

echo "[5/6] Creating initial zone file..."
cat > "$ZONES_DIR/db.yield" << ZONEFILE
; Pounce Yield DNS Zone
; This file is dynamically updated by the Pounce backend
; DO NOT EDIT MANUALLY - changes will be overwritten

\$TTL 300
\$ORIGIN yield.pounce.ch.

@       IN      SOA     ns1.pounce.ch. admin.pounce.ch. (
                        $(date +%Y%m%d)01 ; Serial (YYYYMMDDNN)
                        3600       ; Refresh (1 hour)
                        600        ; Retry (10 minutes)
                        604800     ; Expire (1 week)
                        300        ; Minimum TTL (5 minutes)
                        )

; Nameservers
@       IN      NS      ns1.pounce.ch.
@       IN      NS      ns2.pounce.ch.

; A record for the zone apex
@       IN      A       ${SERVER_IP}

; Wildcard - all subdomains point to our server
*       IN      A       ${SERVER_IP}

; ============================================
; YIELD DOMAINS
; Add domains below in format:
; domainname    IN      A       ${SERVER_IP}
; ============================================

; Example (uncomment to test):
; akaya.ch.     IN      A       ${SERVER_IP}

ZONEFILE

echo "[6/6] Creating systemd service..."
cat > /etc/systemd/system/coredns.service << 'SERVICE'
[Unit]
Description=CoreDNS DNS Server
Documentation=https://coredns.io
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/coredns
ExecStart=/opt/coredns/coredns -conf /opt/coredns/Corefile
ExecReload=/bin/kill -SIGUSR1 $MAINPID
Restart=on-failure
RestartSec=5s
LimitNOFILE=1048576
LimitNPROC=512

# Security
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
SERVICE

echo "[7/6] Opening firewall port 53..."
if command -v ufw &> /dev/null; then
    ufw allow 53/tcp
    ufw allow 53/udp
    echo "UFW: Port 53 opened"
elif command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-port=53/tcp
    firewall-cmd --permanent --add-port=53/udp
    firewall-cmd --reload
    echo "firewalld: Port 53 opened"
else
    echo "WARNING: No firewall detected. Make sure port 53 is open!"
fi

echo "[8/6] Starting CoreDNS..."
systemctl daemon-reload
systemctl enable coredns
systemctl start coredns

echo ""
echo "=========================================="
echo "✅ CoreDNS installed and running!"
echo "=========================================="
echo ""
echo "Status: $(systemctl is-active coredns)"
echo "Config: $COREDNS_DIR/Corefile"
echo "Zones:  $ZONES_DIR/db.yield"
echo ""
echo "To add a yield domain, append to $ZONES_DIR/db.yield:"
echo "  akaya.ch.     IN      A       $SERVER_IP"
echo ""
echo "Then reload: systemctl reload coredns"
echo ""
echo "Test with: dig @localhost akaya.ch"
echo "=========================================="

