#!/usr/bin/env python3
"""
Cloudflare Domain Monitor - TRAEFIK VERSION
Automatically discovers ALL domains and subdomains from Traefik configurations.
"""

import subprocess
import json
import sys
import os
import re
from datetime import datetime
from typing import Dict, List, Any, Set
import socket
import time
import threading
from pathlib import Path

# Configuration
TIMEOUT = 10  # seconds for each check
OUTPUT_DIR = "/home/administrator/shared/cloudflare-monitoring"
os.makedirs(OUTPUT_DIR, exist_ok=True)

def discover_traefik_domains() -> Set[str]:
    """
    Discover all domains from Traefik dynamic configurations.
    """
    domains = set()
    
    traefik_dir = Path('/home/administrator/portainer-stacks/traefik/dynamic')
    
    print("🔍 Scanning Traefik configurations...")
    
    if not traefik_dir.exists():
        print(f"  ⚠ Traefik config directory not found: {traefik_dir}")
        return domains
    
    for yaml_file in traefik_dir.glob('*.yaml'):
        try:
            with open(yaml_file, 'r', errors='ignore') as f:
                content = f.read()
            
            # Find Host() directives in Traefik YAML
            matches = re.findall(r'Host\(`([^`]+)`\)', content)
            
            for match in matches:
                domain = match.strip()
                # Skip path-based rules (e.g., "kids.maszatai.com/api")
                if '/' not in domain and domain and '.' in domain:
                    domains.add(domain)
                    print(f"  ✓ Found: {domain}")
                    
        except Exception as e:
            print(f"  ⚠ Error reading {yaml_file.name}: {e}")
    
    print(f"Found {len(domains)} domain(s) from Traefik configs")
    return domains

def discover_certbot_domains() -> Set[str]:
    """
    Discover all domains from certbot certificates.
    """
    domains = set()
    
    print("\n🔍 Scanning certbot certificates...")
    
    try:
        result = subprocess.run(
            ['sudo', 'certbot', 'certificates'],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if result.returncode == 0:
            lines = result.stdout.split('\n')
            current_cert = None
            
            for line in lines:
                if 'Certificate Name:' in line:
                    current_cert = line.split('Certificate Name:')[1].strip()
                elif 'Domains:' in line and current_cert:
                    domains_part = line.split('Domains:')[1].strip()
                    for domain in domains_part.split():
                        domain = domain.strip()
                        if domain and '.' in domain:
                            domains.add(domain)
                            print(f"  ✓ Found: {domain}")
    
    except Exception as e:
        print(f"  ⚠ Error reading certbot certificates: {e}")
    
    print(f"Found {len(domains)} domain(s) from certbot")
    return domains

def check_ssl(domain: str, timeout: int = TIMEOUT) -> Dict[str, Any]:
    """
    Check SSL certificate for a domain.
    """
    result = {
        'domain': domain,
        'success': False,
        'days_until_expiry': None,
        'issuer': None,
        'error': None
    }
    
    try:
        # Use openssl to get certificate info
        cmd = f'echo | openssl s_client -servername {domain} -connect {domain}:443 2>/dev/null | openssl x509 -noout -dates -issuer 2>/dev/null'
        output = subprocess.check_output(cmd, shell=True, timeout=timeout, text=True)
        
        # Parse expiry date
        for line in output.split('\n'):
            if 'notAfter=' in line:
                expiry_str = line.split('notAfter=')[1].strip()
                expiry_date = datetime.strptime(expiry_str, '%b %d %H:%M:%S %Y %Z')
                days_until = (expiry_date - datetime.utcnow()).days
                result['days_until_expiry'] = days_until
        
        # Parse issuer
        for line in output.split('\n'):
            if 'issuer=' in line:
                result['issuer'] = line.split('issuer=')[1].strip()
        
        result['success'] = True
        
    except subprocess.TimeoutExpired:
        result['error'] = 'Timeout'
    except Exception as e:
        result['error'] = str(e)
    
    return result

def check_https(domain: str, timeout: int = TIMEOUT) -> Dict[str, Any]:
    """
    Check if HTTPS endpoint is responding.
    """
    result = {
        'domain': domain,
        'success': False,
        'status_code': None,
        'error': None
    }
    
    try:
        # Use curl to check HTTPS (insecure to bypass cert validation for monitoring)
        cmd = ['curl', '-sI', '--insecure', f'https://{domain}', '--connect-timeout', str(timeout)]
        output = subprocess.check_output(cmd, timeout=timeout + 2, text=True)
        
        # Parse status code
        for line in output.split('\n'):
            if line.startswith('HTTP/'):
                status_parts = line.split()
                if len(status_parts) >= 2:
                    result['status_code'] = int(status_parts[1])
                    result['success'] = True
                break
    
    except subprocess.TimeoutExpired:
        result['error'] = 'Timeout'
    except Exception as e:
        result['error'] = str(e)
    
    return result

def check_dns(domain: str, timeout: int = TIMEOUT) -> Dict[str, Any]:
    """
    Check DNS resolution for a domain with timeout support.
    """
    result = {
        'domain': domain,
        'success': False,
        'ip_address': None,
        'error': None
    }
    
    # Custom timeout implementation for DNS resolution
    def resolve_dns():
        try:
            ip = socket.gethostbyname(domain)
            result['ip_address'] = ip
            result['success'] = True
            return True
        except Exception:
            result['error'] = str(e)
            return False
    
    thread = threading.Thread(target=resolve_dns)
    thread.start()
    thread.join(timeout=timeout)
    
    if thread.is_alive():
        # Thread is still running, meaning timeout occurred
        result['error'] = 'DNS Timeout'
        # We don't have a clean way to kill the thread, but we can mark it as failed
        return result
    
    return result

def determine_status(dns: Dict, ssl: Dict, https: Dict) -> str:
    """
    Determine overall status based on checks.
    """
    if not dns['success']:
        return 'down'
    if not ssl['success']:
        return 'degraded'
    if not https['success']:
        return 'degraded'
    
    # Check SSL expiry
    if ssl.get('days_until_expiry', 999) < 7:
        return 'degraded'
    
    return 'up'

def main():
    print("=" * 60)
    print("CLOUDFLARE DOMAIN MONITOR - TRAEFIK VERSION")
    print("=" * 60)
    print()
    
    # Discover domains from Traefik
    traefik_domains = discover_traefik_domains()
    
    # Also discover from certbot (for backup)
    certbot_domains = discover_certbot_domains()
    
    # Combine domains
    all_domains = traefik_domains | certbot_domains
    
    if not all_domains:
        print("❌ No domains found!")
        sys.exit(1)
    
    print(f"\n📊 Total unique domains to monitor: {len(all_domains)}")
    print(f"   - From Traefik: {len(traefik_domains)}")
    print(f"   - From Certbot: {len(certbot_domains)}")

    # Skip domains whose backing docker is deep-hibernated (container+image removed).
    # Checking them = false 'degraded' + risk of waking them; regenerate skip map fresh each run.
    skip_domains = set()
    try:
        subprocess.run(['python3', '/home/administrator/shared/hibernate_skip_map.py'],
                       capture_output=True, text=True, timeout=15)
        with open('/home/administrator/shared/cloudflare-monitoring/hibernate_skip.json') as f:
            skip_domains = set(json.load(f).get('skip_domains', []))
        if skip_domains:
            print(f"\n💤 Skipping deep-hibernated domains (no live check, no wake): {len(skip_domains)}")
            for d in sorted(skip_domains):
                print(f"   💤 {d}")
    except Exception as e:
        print(f"  ⚠ hibernate skip map unavailable ({e}) — checking all domains")

    print()
    
    # Check each domain
    results = []
    
    print("🔍 Checking domains...")
    for i, domain in enumerate(sorted(all_domains), 1):
        if domain in skip_domains:
            print(f"\n[{i}/{len(all_domains)}] {domain} — 💤 deep-hibernated, SKIPPED (no curl, no wake)")
            results.append({
                'domain': domain,
                'overall_status': 'hibernating',
                'dns': {'domain': domain, 'success': None, 'error': 'skipped: deep-hibernated'},
                'ssl': {'domain': domain, 'success': None, 'error': 'skipped: deep-hibernated'},
                'https': {'domain': domain, 'success': None, 'error': 'skipped: deep-hibernated'},
                'checked_at': datetime.utcnow().isoformat()
            })
            continue

        print(f"\n[{i}/{len(all_domains)}] Checking {domain}...", flush=True)
        
        dns_result = check_dns(domain)
        ssl_result = check_ssl(domain)
        https_result = check_https(domain)
        
        overall_status = determine_status(dns_result, ssl_result, https_result)
        
        result = {
            'domain': domain,
            'overall_status': overall_status,
            'dns': dns_result,
            'ssl': ssl_result,
            'https': https_result,
            'checked_at': datetime.utcnow().isoformat()
        }
        
        results.append(result)
        
        # Print status
        status_emoji = '✓' if overall_status == 'up' else ('⚠' if overall_status == 'degraded' else '✗')
        print(f"  {status_emoji} DNS: {'✓' if dns_result['success'] else '✗'} | "
              f"SSL: {'✓' if ssl_result['success'] else '✗'} | "
              f"HTTPS: {'✓' if https_result['success'] else '✗'}")
        
        if ssl_result.get('days_until_expiry'):
            print(f"     SSL expires in {ssl_result['days_until_expiry']} days")
        
        if not overall_status == 'up':
            print(f"     Status: {overall_status.upper()}")
    
    # Generate summary
    print("\n" + "=" * 60)
    print("SUMMARY")
    print("=" * 60)
    
    up_count = sum(1 for r in results if r['overall_status'] == 'up')
    degraded_count = sum(1 for r in results if r['overall_status'] == 'degraded')
    down_count = sum(1 for r in results if r['overall_status'] == 'down')
    
    print(f"Total: {len(results)}")
    print(f"✓ Up: {up_count}")
    print(f"⚠ Degraded: {degraded_count}")
    print(f"✗ Down: {down_count}")
    
    # Save results
    output_file = os.path.join(OUTPUT_DIR, 'latest.json')
    with open(output_file, 'w') as f:
        json.dump({
            'checked_at': datetime.utcnow().isoformat(),
            'source': 'traefik',
            'total_domains': len(results),
            'up': up_count,
            'degraded': degraded_count,
            'down': down_count,
            'domains': results
        }, f, indent=2)
    
    print(f"\n💾 Results saved to: {output_file}")
    
    # Exit with appropriate code
    if down_count > 0:
        print("\n❌ Some domains are DOWN")
        sys.exit(2)
    elif degraded_count > 0:
        print("\n⚠ Some domains are DEGRADED")
        sys.exit(1)
    else:
        print("\n✓ All domains are UP!")
        sys.exit(0)

if __name__ == '__main__':
    main()