#!/usr/bin/env bash

# Enhanced PowerDNS Setup Script for WHP
# This script sets up PowerDNS with MySQL backend and integrates with existing WHP infrastructure

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}Setting up PowerDNS for WHP...${NC}"

# Create directories for PowerDNS
mkdir -p /docker/powerdns/{data,config,logs}

# Generate secure passwords and keys (alphanumeric only to avoid shell escaping issues)
PDNS_API_KEY=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 32)
SECRET_KEY=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 50)
PDNS_DB_PASSWORD=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 32)

# Get MySQL root password from root configuration
if [ ! -f /root/.my.cnf ]; then
    echo -e "${RED}Error: MySQL configuration not found at /root/.my.cnf${NC}"
    exit 1
fi

MYSQL_ROOT_PASSWORD=$(grep password /root/.my.cnf | cut -d= -f2- | tr -d ' ')
if [ -z "$MYSQL_ROOT_PASSWORD" ]; then
    echo -e "${RED}Error: Could not extract MySQL root password from /root/.my.cnf${NC}"
    exit 1
fi

echo -e "${GREEN}MySQL root password extracted successfully${NC}"
echo -e "${GREEN}Generated secure passwords for PowerDNS services${NC}"

# Create enhanced PowerDNS configuration
cat > /docker/powerdns/config/pdns.conf << EOF
# PowerDNS Configuration for WHP
# Generated on $(date)

# Backend configuration
launch=gmysql
gmysql-host=mysql
gmysql-port=3306
gmysql-dbname=powerdns
gmysql-user=pdns
gmysql-password=${PDNS_DB_PASSWORD}
gmysql-dnssec=yes

# API configuration
api=yes
api-key=${PDNS_API_KEY}
webserver=yes
webserver-address=0.0.0.0
webserver-port=8081
webserver-allow-from=0.0.0.0/0
webserver-password=${SECRET_KEY}

# Performance and security settings
cache-ttl=20
query-cache-ttl=20
default-ttl=3600
max-cache-entries=1000000

# DNSSEC settings
dnssec-key-cache-ttl=30

# Logging
loglevel=4
log-dns-queries=yes
log-dns-details=yes

# Security settings
disable-axfr=yes
allow-axfr-ips=127.0.0.1
allow-notify-from=127.0.0.1

# Zone settings
zone-metadata-cache-ttl=60
zone-cache-refresh-interval=60
EOF

echo -e "${GREEN}PowerDNS configuration created${NC}"

# Set up PowerDNS database with enhanced schema
echo -e "${BLUE}Setting up PowerDNS database...${NC}"

# Create database
if ! mysql -h 127.0.0.1 -u root -p"${MYSQL_ROOT_PASSWORD}" -e "CREATE DATABASE IF NOT EXISTS powerdns CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null; then
    echo -e "${RED}Error: Failed to create PowerDNS database${NC}"
    exit 1
fi
echo -e "${GREEN}PowerDNS database created/verified${NC}"

# Create PowerDNS user with proper host patterns for Docker networking
echo -e "${BLUE}Creating PowerDNS database users...${NC}"
for host_pattern in "'%'" "'172.18.0.%'" "'localhost'"; do
    if ! mysql -h 127.0.0.1 -u root -p"${MYSQL_ROOT_PASSWORD}" -e "CREATE USER IF NOT EXISTS 'pdns'@${host_pattern} IDENTIFIED BY '${PDNS_DB_PASSWORD}';" 2>/dev/null; then
        echo -e "${YELLOW}Warning: Failed to create pdns@${host_pattern} user (may already exist)${NC}"
    fi
    
    if ! mysql -h 127.0.0.1 -u root -p"${MYSQL_ROOT_PASSWORD}" -e "GRANT ALL PRIVILEGES ON powerdns.* TO 'pdns'@${host_pattern};" 2>/dev/null; then
        echo -e "${YELLOW}Warning: Failed to grant privileges to pdns@${host_pattern}${NC}"
    fi
    
    if ! mysql -h 127.0.0.1 -u root -p"${MYSQL_ROOT_PASSWORD}" -e "ALTER USER 'pdns'@${host_pattern} IDENTIFIED BY '${PDNS_DB_PASSWORD}';" 2>/dev/null; then
        echo -e "${YELLOW}Warning: Failed to update password for pdns@${host_pattern}${NC}"
    fi
done

if ! mysql -h 127.0.0.1 -u root -p"${MYSQL_ROOT_PASSWORD}" -e "FLUSH PRIVILEGES;" 2>/dev/null; then
    echo -e "${RED}Error: Failed to flush MySQL privileges${NC}"
    exit 1
fi

echo -e "${GREEN}PowerDNS database users configured successfully${NC}"

# Download and import PowerDNS schema
echo -e "${BLUE}Downloading PowerDNS schema...${NC}"
wget -q -O /tmp/schema.mysql.sql https://raw.githubusercontent.com/PowerDNS/pdns/master/modules/gmysqlbackend/schema.mysql.sql

if [ ! -f /tmp/schema.mysql.sql ]; then
    echo -e "${RED}Error: Failed to download PowerDNS schema${NC}"
    exit 1
fi

# Check if the 'domains' table exists before importing schema
echo -e "${BLUE}Checking PowerDNS schema...${NC}"
TABLE_EXISTS=$(mysql -h 127.0.0.1 -u pdns -p"${PDNS_DB_PASSWORD}" -D powerdns -e "SHOW TABLES LIKE 'domains';" 2>/dev/null | grep domains || echo "")
if [ -z "$TABLE_EXISTS" ]; then
    echo -e "${BLUE}Importing PowerDNS schema...${NC}"
    if mysql -h 127.0.0.1 -u pdns -p"${PDNS_DB_PASSWORD}" powerdns < /tmp/schema.mysql.sql 2>/dev/null; then
        echo -e "${GREEN}PowerDNS database schema imported successfully${NC}"
    else
        echo -e "${RED}Error: Failed to import PowerDNS schema${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}PowerDNS schema already exists, skipping import${NC}"
fi
rm /tmp/schema.mysql.sql

# Create additional indexes for better performance
echo -e "${BLUE}Creating performance indexes...${NC}"
if mysql -h 127.0.0.1 -u pdns -p"${PDNS_DB_PASSWORD}" powerdns << EOF 2>/dev/null
CREATE INDEX IF NOT EXISTS idx_records_name_type ON records(name, type);
CREATE INDEX IF NOT EXISTS idx_records_domain_id ON records(domain_id);
CREATE INDEX IF NOT EXISTS idx_domains_name ON domains(name);
CREATE INDEX IF NOT EXISTS idx_domains_type ON domains(type);
EOF
then
    echo -e "${GREEN}Performance indexes created successfully${NC}"
else
    echo -e "${YELLOW}Warning: Some indexes may already exist or failed to create${NC}"
fi

# Stop existing PowerDNS container if running
if docker ps -q -f name=powerdns | grep -q .; then
    echo -e "${YELLOW}Stopping existing PowerDNS container...${NC}"
    docker stop powerdns
    docker rm powerdns
fi

# Start PowerDNS server with enhanced configuration
echo -e "${BLUE}Starting PowerDNS server...${NC}"
docker run -d --name powerdns \
  --network client-net \
  -p 53:53/tcp -p 53:53/udp \
  -p 8081:8081 \
  -v /docker/powerdns/config/pdns.conf:/etc/powerdns/pdns.conf:ro \
  -v /docker/powerdns/logs:/var/log \
  -e PDNS_launch=gmysql \
  -e PDNS_gmysql_host=mysql \
  -e PDNS_gmysql_port=3306 \
  -e PDNS_gmysql_dbname=powerdns \
  -e PDNS_gmysql_user=pdns \
  -e PDNS_gmysql_password=${PDNS_DB_PASSWORD} \
  -e PDNS_api=yes \
  -e PDNS_api_key=${PDNS_API_KEY} \
  -e PDNS_webserver=yes \
  -e PDNS_webserver_address=0.0.0.0 \
  -e PDNS_webserver_port=8081 \
  -e PDNS_webserver_allow_from=0.0.0.0/0 \
  -e PDNS_webserver_password=${SECRET_KEY} \
  -e PDNS_dnssec_key_cache_ttl=30 \
  -e PDNS_cache_ttl=20 \
  -e PDNS_query_cache_ttl=20 \
  -e PDNS_default_ttl=3600 \
  -e PDNS_max_cache_entries=1000000 \
  -e PDNS_loglevel=4 \
  -e PDNS_log_dns_queries=yes \
  -e PDNS_log_dns_details=yes \
  -e PDNS_disable_axfr=yes \
  -e PDNS_allow_axfr_ips=127.0.0.1 \
  -e PDNS_allow_notify_from=127.0.0.1 \
  -e PDNS_zone_metadata_cache_ttl=60 \
  -e PDNS_zone_cache_refresh_interval=60 \
  --restart unless-stopped \
  --log-driver json-file \
  --log-opt max-size=10m \
  --log-opt max-file=3 \
  powerdns/pdns-auth-49:latest

# Wait for PowerDNS to start
echo -e "${BLUE}Waiting for PowerDNS to start...${NC}"
sleep 10

# Test PowerDNS API
if curl -s -H "X-API-Key: ${PDNS_API_KEY}" http://localhost:8081/api/v1/servers/localhost > /dev/null; then
    echo -e "${GREEN}PowerDNS API is responding correctly${NC}"
else
    echo -e "${RED}Warning: PowerDNS API is not responding${NC}"
fi

# Create secure password storage file
cat > /docker/powerdns/config/passwords.conf << EOF
# PowerDNS Password Configuration
# Generated on $(date)
# WARNING: This file contains sensitive information - restrict access!

# PowerDNS Database User Password
PDNS_DB_PASSWORD=${PDNS_DB_PASSWORD}

# PowerDNS API Key
PDNS_API_KEY=${PDNS_API_KEY}

# PowerDNS Secret Key
SECRET_KEY=${SECRET_KEY}
EOF

# Create configuration file for WHP integration (without passwords)
cat > /docker/powerdns/config/whp-integration.conf << EOF
# WHP PowerDNS Integration Configuration
# Generated on $(date)

# API Configuration
PDNS_API_URL=http://localhost:8081/api/v1
PDNS_API_KEY=${PDNS_API_KEY}
PDNS_SERVER_ID=localhost

# Database Configuration
PDNS_DB_HOST=mysql
PDNS_DB_PORT=3306
PDNS_DB_NAME=powerdns
PDNS_DB_USER=pdns
# Password stored in /docker/powerdns/config/passwords.conf

# Default Settings
DEFAULT_TTL=3600
DEFAULT_NAMESERVERS=ns1.example.com,ns2.example.com
EOF

# Set proper permissions
chmod 600 /docker/powerdns/config/whp-integration.conf
chmod 600 /docker/powerdns/config/passwords.conf
chown root:root /docker/powerdns/config/whp-integration.conf
chown root:root /docker/powerdns/config/passwords.conf

# Update firewall rules
echo -e "${BLUE}Updating firewall rules...${NC}"
firewall-cmd --permanent --add-port=53/tcp > /dev/null 2>&1 || true
firewall-cmd --permanent --add-port=53/udp > /dev/null 2>&1 || true
firewall-cmd --permanent --add-port=8081/tcp > /dev/null 2>&1 || true
firewall-cmd --reload > /dev/null 2>&1 || true

# Create health check script
cat > /docker/powerdns/health-check.sh << 'EOF'
#!/bin/bash
# PowerDNS Health Check Script

PDNS_API_KEY=$(grep PDNS_API_KEY /docker/powerdns/config/whp-integration.conf | cut -d= -f2)

# Check PowerDNS API
if curl -s -H "X-API-Key: ${PDNS_API_KEY}" http://localhost:8081/api/v1/servers/localhost > /dev/null; then
    echo "PowerDNS API: OK"
else
    echo "PowerDNS API: FAILED"
    exit 1
fi

echo "PowerDNS service is running correctly"
EOF

chmod +x /docker/powerdns/health-check.sh

# Create backup script
cat > /docker/powerdns/backup.sh << 'EOF'
#!/bin/bash
# PowerDNS Backup Script

BACKUP_DIR="/docker/backups/powerdns"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p ${BACKUP_DIR}

# Backup PowerDNS database
mysqldump -h 127.0.0.1 -u root -p$(grep password /root/.my.cnf | cut -d= -f2- | tr -d ' ') powerdns > ${BACKUP_DIR}/powerdns_${DATE}.sql

# Backup configuration
tar -czf ${BACKUP_DIR}/powerdns_config_${DATE}.tar.gz -C /docker powerdns/config/

echo "PowerDNS backup completed: ${BACKUP_DIR}"
EOF

chmod +x /docker/powerdns/backup.sh

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}PowerDNS Setup Completed Successfully!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${BLUE}Configuration Details:${NC}"
echo -e "PowerDNS API Key: ${YELLOW}${PDNS_API_KEY}${NC}"
echo -e "PowerDNS API URL: ${YELLOW}http://localhost:8081${NC}"
echo ""
echo -e "${BLUE}Security Information:${NC}"
echo -e "PowerDNS DB Password: ${YELLOW}${PDNS_DB_PASSWORD}${NC}"
echo -e "All passwords are stored in: ${YELLOW}/docker/powerdns/config/passwords.conf${NC}"
echo ""
echo -e "${BLUE}Integration Files:${NC}"
echo -e "Configuration: ${YELLOW}/docker/powerdns/config/whp-integration.conf${NC}"
echo -e "Health Check: ${YELLOW}/docker/powerdns/health-check.sh${NC}"
echo -e "Backup Script: ${YELLOW}/docker/powerdns/backup.sh${NC}"
echo ""
echo -e "${YELLOW}Important:${NC}"
echo -e "1. Update your WHP configuration to use the new API key"
echo -e "2. Test DNS resolution for your domains"
echo -e "3. Consider setting up regular backups using the backup script"
echo ""
echo -e "${GREEN}Setup completed!${NC}" 