#!/bin/bash

# AeThex Domain Integration - Quick Start Script
# This script helps verify domain configuration and setup

set -e

echo "=========================================="
echo "AeThex Domain Integration - Quick Start"
echo "=========================================="
echo

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

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check prerequisites
echo "1. Checking prerequisites..."
echo

if ! command_exists dig; then
    echo -e "${RED}✗${NC} dig not found. Install dnsutils: sudo apt-get install dnsutils"
    exit 1
else
    echo -e "${GREEN}✓${NC} dig found"
fi

if ! command_exists curl; then
    echo -e "${RED}✗${NC} curl not found. Install curl: sudo apt-get install curl"
    exit 1
else
    echo -e "${GREEN}✓${NC} curl found"
fi

if ! command_exists openssl; then
    echo -e "${RED}✗${NC} openssl not found. Install openssl: sudo apt-get install openssl"
    exit 1
else
    echo -e "${GREEN}✓${NC} openssl found"
fi

echo

# Domain list
DOMAINS=(
    "aethex.app"
    "aethex.co"
    "aethex.network"
    "aethex.net"
    "aethex.tech"
    "aethex.id"
    "aethex.cloud"
    "aethex.education"
    "aethex.studio"
    "aethex.shop"
    "aethex.support"
    "aethex.dev"
    "aethex.info"
    "aethex.blog"
    "aethex.locker"
    "aethex.bot"
    "aethex.live"
    "aethex.fun"
    "aethex.space"
    "aethex.bio"
    "aethex.me"
    "aethex.biz"
    "aethex.pro"
    "aethex.foundation"
    "aethex.us"
    "aethex.sbs"
    "aethex.online"
    "aethex.site"
)

# Check DNS resolution
echo "2. Checking DNS resolution..."
echo

dns_ok=0
dns_failed=0

for domain in "${DOMAINS[@]}"; do
    if dig +short "$domain" @8.8.8.8 >/dev/null 2>&1; then
        result=$(dig +short "$domain" @8.8.8.8 | head -1)
        if [ -n "$result" ]; then
            echo -e "${GREEN}✓${NC} $domain → $result"
            ((dns_ok++))
        else
            echo -e "${YELLOW}⚠${NC} $domain → no records"
            ((dns_failed++))
        fi
    else
        echo -e "${RED}✗${NC} $domain → DNS lookup failed"
        ((dns_failed++))
    fi
done

echo
echo "DNS Check: $dns_ok resolved, $dns_failed failed/missing"
echo

# Check HTTPS connectivity
echo "3. Checking HTTPS connectivity..."
echo

https_ok=0
https_failed=0

for domain in "${DOMAINS[@]}"; do
    status=$(curl -s -o /dev/null -w "%{http_code}" "https://$domain" --max-time 5 2>/dev/null || echo "000")

    if [ "$status" -eq 200 ] || [ "$status" -eq 301 ] || [ "$status" -eq 302 ]; then
        echo -e "${GREEN}✓${NC} https://$domain → $status"
        ((https_ok++))
    elif [ "$status" -eq "000" ]; then
        echo -e "${RED}✗${NC} https://$domain → timeout/connection failed"
        ((https_failed++))
    else
        echo -e "${YELLOW}⚠${NC} https://$domain → $status"
        ((https_failed++))
    fi
done

echo
echo "HTTPS Check: $https_ok OK, $https_failed failed/warning"
echo

# Check SSL certificates (sample domains)
echo "4. Checking SSL certificates (sample)..."
echo

SSL_CHECK_DOMAINS=("aethex.app" "aethex.network" "aethex.tech" "aethex.cloud")

for domain in "${SSL_CHECK_DOMAINS[@]}"; do
    if openssl s_client -connect "$domain:443" -servername "$domain" </dev/null 2>/dev/null | openssl x509 -noout -dates >/dev/null 2>&1; then
        expiry=$(echo | openssl s_client -connect "$domain:443" -servername "$domain" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)
        echo -e "${GREEN}✓${NC} $domain → Valid until: $expiry"
    else
        echo -e "${RED}✗${NC} $domain → SSL certificate check failed"
    fi
done

echo

# Check CORS configuration
echo "5. Checking CORS configuration..."
echo

if [ -f "server/cors-config.ts" ]; then
    origins=$(grep -c "https://aethex" server/cors-config.ts || echo "0")
    echo -e "${GREEN}✓${NC} CORS config found with $origins domain entries"
else
    echo -e "${RED}✗${NC} CORS config not found at server/cors-config.ts"
fi

echo

# Check environment variables
echo "6. Checking environment variables..."
echo

if [ -f ".env" ] || [ -f ".env.production" ]; then
    echo -e "${GREEN}✓${NC} Environment file found"

    # Check for critical variables
    ENV_FILE=".env"
    [ -f ".env.production" ] && ENV_FILE=".env.production"

    check_env_var() {
        if grep -q "^$1=" "$ENV_FILE" 2>/dev/null; then
            echo -e "  ${GREEN}✓${NC} $1 is set"
        else
            echo -e "  ${YELLOW}⚠${NC} $1 is not set"
        fi
    }

    check_env_var "NODE_ENV"
    check_env_var "SESSION_SECRET"
    check_env_var "SUPABASE_URL"
    check_env_var "DISCORD_CLIENT_ID"
    check_env_var "GITHUB_CLIENT_ID"
else
    echo -e "${RED}✗${NC} No .env or .env.production file found"
fi

echo

# Summary
echo "=========================================="
echo "Setup Summary"
echo "=========================================="
echo
echo "DNS Resolution:    $dns_ok/$((dns_ok + dns_failed)) domains"
echo "HTTPS Connectivity: $https_ok/$((https_ok + https_failed)) domains"
echo

if [ $dns_failed -gt 0 ] || [ $https_failed -gt 0 ]; then
    echo -e "${YELLOW}⚠ Some domains need configuration${NC}"
    echo
    echo "Next steps:"
    echo "  1. Review DOMAIN_SETUP_GUIDE.md for DNS configuration"
    echo "  2. Configure SSL certificates with certbot"
    echo "  3. Deploy nginx configuration from nginx/aethex-domains.conf"
    echo "  4. Update OAuth redirect URIs (see OAUTH_SETUP.md)"
    echo "  5. Run this script again to verify"
else
    echo -e "${GREEN}✓ All domains configured correctly!${NC}"
    echo
    echo "Next steps:"
    echo "  1. Update OAuth providers with redirect URIs (OAUTH_SETUP.md)"
    echo "  2. Test authentication flows"
    echo "  3. Monitor logs for errors"
fi

echo
echo "Documentation:"
echo "  - Domain setup:  DOMAIN_SETUP_GUIDE.md"
echo "  - OAuth config:  OAUTH_SETUP.md"
echo "  - Domain mapping: config/domains.json"
echo "  - Routing logic: DOMAIN_ROUTING.md"
echo

exit 0
