#!/bin/bash
#
# Nuke Telemetry DNS Sinkhole Configuration Generator
# Generates DNS blocking configurations for various DNS servers
#
# Usage:
#   bash dns_sinkhole_config.sh               # Generate all configs
#   bash dns_sinkhole_config.sh --dnsmasq     # Generate dnsmasq config only
#   bash dns_sinkhole_config.sh --pihole      # Generate Pi-hole config only
#   bash dns_sinkhole_config.sh --adguard     # Generate AdGuard Home config only
#   bash dns_sinkhole_config.sh --bind        # Generate BIND9 config only
#   bash dns_sinkhole_config.sh --apply       # Apply to local system (if supported)
#

# Configuration
OUTPUT_DIR="./dns_configs"
DOMAINS=(
    "api.honeycomb.io"
    "learn.foundry.com"
    "sentry.foundry.com"
)

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log() {
    echo -e "$1"
}

create_output_dir() {
    mkdir -p "$OUTPUT_DIR"
    log "${GREEN}Output directory: $OUTPUT_DIR${NC}"
    echo ""
}

generate_dnsmasq() {
    local file="$OUTPUT_DIR/dnsmasq-nuke-block.conf"

    log "${BLUE}Generating dnsmasq configuration...${NC}"

    cat > "$file" << 'EOF'
# dnsmasq configuration to block Nuke/Foundry telemetry
# Installation:
#   1. Copy to /etc/dnsmasq.d/nuke-block.conf
#   2. Or append to /etc/dnsmasq.conf
#   3. Restart: sudo systemctl restart dnsmasq
#
# Test:
#   nslookup api.honeycomb.io
#   nslookup learn.foundry.com
#   (should return 0.0.0.0)

EOF

    for domain in "${DOMAINS[@]}"; do
        echo "address=/$domain/0.0.0.0" >> "$file"
    done

    cat >> "$file" << 'EOF'

# Alternative: redirect to localhost instead of 0.0.0.0
# Uncomment these and comment out the above if preferred
# address=/api.honeycomb.io/127.0.0.1
# address=/learn.foundry.com/127.0.0.1
# address=/sentry.foundry.com/127.0.0.1
EOF

    log "${GREEN}✓ Created: $file${NC}"
    echo ""
}

generate_pihole() {
    local file="$OUTPUT_DIR/pihole-nuke-block.txt"

    log "${BLUE}Generating Pi-hole blocklist...${NC}"

    cat > "$file" << 'EOF'
# Pi-hole blocklist for Nuke/Foundry telemetry
# Installation:
#   Method 1 (Web UI):
#     1. Open Pi-hole admin panel
#     2. Go to Group Management > Adlists
#     3. Add this file's URL or paste contents into Custom DNS
#
#   Method 2 (CLI):
#     1. Add domains to /etc/pihole/custom.list
#     2. Run: pihole restartdns
#
#   Method 3 (Regex blocking):
#     1. Open Pi-hole admin panel
#     2. Go to Group Management > Domains
#     3. Add each domain below
#
# Domains to block:

EOF

    for domain in "${DOMAINS[@]}"; do
        echo "$domain" >> "$file"
    done

    cat >> "$file" << 'EOF'

# Regex patterns (optional - use in Pi-hole Regex filter):
# (api\.honeycomb\.io|learn\.foundry\.com|sentry\.foundry\.com)
EOF

    log "${GREEN}✓ Created: $file${NC}"
    echo ""

    # Also create custom.list format
    local custom_file="$OUTPUT_DIR/pihole-custom.list"

    log "${BLUE}Generating Pi-hole custom.list format...${NC}"

    cat > "$custom_file" << 'EOF'
# Pi-hole custom.list format
# Copy these lines to /etc/pihole/custom.list
# Then run: pihole restartdns

EOF

    for domain in "${DOMAINS[@]}"; do
        echo "0.0.0.0 $domain" >> "$custom_file"
    done

    log "${GREEN}✓ Created: $custom_file${NC}"
    echo ""
}

generate_adguard() {
    local file="$OUTPUT_DIR/adguard-nuke-block.txt"

    log "${BLUE}Generating AdGuard Home blocklist...${NC}"

    cat > "$file" << 'EOF'
# AdGuard Home blocklist for Nuke/Foundry telemetry
# Installation:
#   Method 1 (Web UI):
#     1. Open AdGuard Home admin panel
#     2. Go to Filters > DNS blocklists
#     3. Add Custom list and paste URL to this file
#
#   Method 2 (Manual):
#     1. Copy contents to AdGuardHome/data/filters/
#     2. Or use Custom filtering rules (Filters > Custom filtering rules)
#
# AdGuard Home format (domain-only):

EOF

    for domain in "${DOMAINS[@]}"; do
        # AdGuard Home uses ||domain^ syntax for domain blocking
        echo "||$domain^" >> "$file"
    done

    cat >> "$file" << 'EOF'

# Alternative format (hosts file style):
# 0.0.0.0 api.honeycomb.io
# 0.0.0.0 learn.foundry.com
# 0.0.0.0 sentry.foundry.com

# Custom filtering rules (advanced):
# Use these in "Custom filtering rules" section for more control
# /^.*foundry\.com$/
# ||honeycomb.io^$important
EOF

    log "${GREEN}✓ Created: $file${NC}"
    echo ""
}

generate_bind() {
    local file="$OUTPUT_DIR/bind9-nuke-block.zone"

    log "${BLUE}Generating BIND9 zone file...${NC}"

    cat > "$file" << 'EOF'
; BIND9 zone file to block Nuke/Foundry telemetry
; Installation:
;   1. Create zone files for each domain
;   2. Add zone declarations to /etc/bind/named.conf.local:
;
;   zone "api.honeycomb.io" {
;       type master;
;       file "/etc/bind/zones/null.zone.file";
;   };
;
;   zone "learn.foundry.com" {
;       type master;
;       file "/etc/bind/zones/null.zone.file";
;   };
;
;   zone "sentry.foundry.com" {
;       type master;
;       file "/etc/bind/zones/null.zone.file";
;   };
;
;   3. Create /etc/bind/zones/null.zone.file with contents below
;   4. Restart BIND: sudo systemctl restart bind9 (or named)
;
; null.zone.file contents:

$TTL 86400
@   IN  SOA localhost. root.localhost. (
            1       ; Serial
            3600    ; Refresh
            1800    ; Retry
            604800  ; Expire
            86400 ) ; Minimum TTL

@   IN  NS  localhost.
@   IN  A   0.0.0.0
*   IN  A   0.0.0.0
EOF

    log "${GREEN}✓ Created: $file${NC}"
    echo ""

    # Generate named.conf snippet
    local conf_file="$OUTPUT_DIR/bind9-named.conf.snippet"

    log "${BLUE}Generating BIND9 named.conf snippet...${NC}"

    cat > "$conf_file" << 'EOF'
// BIND9 named.conf snippet for blocking Nuke telemetry
// Add these lines to /etc/bind/named.conf.local

EOF

    for domain in "${DOMAINS[@]}"; do
        cat >> "$conf_file" << EOF
zone "$domain" {
    type master;
    file "/etc/bind/zones/null.zone.file";
};

EOF
    done

    log "${GREEN}✓ Created: $conf_file${NC}"
    echo ""
}

generate_unbound() {
    local file="$OUTPUT_DIR/unbound-nuke-block.conf"

    log "${BLUE}Generating Unbound configuration...${NC}"

    cat > "$file" << 'EOF'
# Unbound configuration to block Nuke/Foundry telemetry
# Installation:
#   1. Copy to /etc/unbound/unbound.conf.d/nuke-block.conf
#   2. Or append to /etc/unbound/unbound.conf
#   3. Restart: sudo systemctl restart unbound
#
# Test:
#   dig @127.0.0.1 api.honeycomb.io
#   (should return 0.0.0.0)

server:
EOF

    for domain in "${DOMAINS[@]}"; do
        cat >> "$file" << EOF
    local-zone: "$domain" redirect
    local-data: "$domain A 0.0.0.0"
EOF
    done

    log "${GREEN}✓ Created: $file${NC}"
    echo ""
}

generate_hosts_file() {
    local file="$OUTPUT_DIR/hosts-nuke-block.txt"

    log "${BLUE}Generating hosts file format...${NC}"

    cat > "$file" << 'EOF'
# Hosts file format for blocking Nuke/Foundry telemetry
# Installation:
#   Linux/Mac: sudo bash -c 'cat >> /etc/hosts'
#   Windows: Add to C:\Windows\System32\drivers\etc\hosts (as Administrator)
#
# Note: This is already handled by block_nuke_telemetry.sh
#       Use this if you need manual installation

EOF

    for domain in "${DOMAINS[@]}"; do
        echo "127.0.0.1 $domain" >> "$file"
    done

    cat >> "$file" << 'EOF'

# IPv6 entries (optional):
# ::1 api.honeycomb.io
# ::1 learn.foundry.com
# ::1 sentry.foundry.com
EOF

    log "${GREEN}✓ Created: $file${NC}"
    echo ""
}

show_summary() {
    log "${GREEN}=== DNS Sinkhole Configurations Generated ===${NC}"
    echo ""
    log "Output directory: $OUTPUT_DIR"
    echo ""
    log "Generated files:"
    ls -lh "$OUTPUT_DIR" | tail -n +2
    echo ""

    log "${YELLOW}Next steps:${NC}"
    log "1. Identify your DNS server type:"
    log "   - Pi-hole: Use pihole-*.txt files"
    log "   - AdGuard Home: Use adguard-*.txt file"
    log "   - dnsmasq: Use dnsmasq-*.conf file"
    log "   - BIND9: Use bind9-*.zone files"
    log "   - Unbound: Use unbound-*.conf file"
    log "   - Hosts file: Use hosts-*.txt file"
    echo ""
    log "2. Follow installation instructions in each file"
    echo ""
    log "3. Test blocking:"
    log "   nslookup api.honeycomb.io"
    log "   nslookup learn.foundry.com"
    log "   (should return 0.0.0.0 or 127.0.0.1)"
    echo ""

    log "${YELLOW}Your DNS server (from network config): 75.75.75.75${NC}"
    log "If you control this DNS server, apply the appropriate config"
}

apply_local() {
    log "${BLUE}Attempting to apply configuration to local system...${NC}"
    echo ""

    # Detect which DNS server is running
    local dns_type=""

    if systemctl is-active --quiet dnsmasq; then
        dns_type="dnsmasq"
    elif systemctl is-active --quiet pihole-FTL; then
        dns_type="pihole"
    elif systemctl is-active --quiet AdGuardHome; then
        dns_type="adguard"
    elif systemctl is-active --quiet bind9 || systemctl is-active --quiet named; then
        dns_type="bind"
    elif systemctl is-active --quiet unbound; then
        dns_type="unbound"
    else
        log "${YELLOW}No DNS server detected on local system${NC}"
        log "You may be using a remote DNS server (75.75.75.75)"
        log "Apply configuration manually to that server"
        return 1
    fi

    log "${GREEN}Detected DNS server: $dns_type${NC}"
    echo ""

    read -p "Apply $dns_type configuration? (y/n): " confirm
    if [ "$confirm" != "y" ]; then
        log "Aborted"
        return 0
    fi

    case "$dns_type" in
        dnsmasq)
            sudo cp "$OUTPUT_DIR/dnsmasq-nuke-block.conf" /etc/dnsmasq.d/
            sudo systemctl restart dnsmasq
            log "${GREEN}✓ Applied to dnsmasq${NC}"
            ;;
        pihole)
            sudo cat "$OUTPUT_DIR/pihole-custom.list" >> /etc/pihole/custom.list
            pihole restartdns
            log "${GREEN}✓ Applied to Pi-hole${NC}"
            ;;
        bind)
            log "${YELLOW}BIND9 requires manual configuration${NC}"
            log "See: $OUTPUT_DIR/bind9-named.conf.snippet"
            ;;
        unbound)
            sudo cp "$OUTPUT_DIR/unbound-nuke-block.conf" /etc/unbound/unbound.conf.d/
            sudo systemctl restart unbound
            log "${GREEN}✓ Applied to Unbound${NC}"
            ;;
    esac
}

main() {
    create_output_dir

    case "$1" in
        --dnsmasq)
            generate_dnsmasq
            ;;
        --pihole)
            generate_pihole
            ;;
        --adguard)
            generate_adguard
            ;;
        --bind)
            generate_bind
            ;;
        --unbound)
            generate_unbound
            ;;
        --hosts)
            generate_hosts_file
            ;;
        --apply)
            generate_dnsmasq
            generate_pihole
            generate_adguard
            generate_bind
            generate_unbound
            generate_hosts_file
            show_summary
            echo ""
            apply_local
            ;;
        *)
            # Generate all
            generate_dnsmasq
            generate_pihole
            generate_adguard
            generate_bind
            generate_unbound
            generate_hosts_file
            show_summary
            ;;
    esac
}

main "$@"
