#!/bin/bash
# Trojan + Let's Encrypt Automated Setup Script
# 
# This script automates the full setup process for Trojan with Let's Encrypt
# certificates, including DNS verification, certificate request, configuration updates,
# and auto-renewal setup.
#
# Usage: bash setup-letsencrypt-trojan.sh
# Prerequisites: Domain must have DNS A record pointing to server IP

set -e

# Configuration
DOMAIN="${1:-hot13399.com}"
TROJAN_CONFIG="/usr/local/etc/trojan/config.json"
CERT_DIR="/etc/letsencrypt/live/$DOMAIN"
BACKUP_DIR="/etc/trojan-cert-backup"

echo "=== Trojan + Let's Encrypt Configuration Script ==="
echo "Domain: $DOMAIN"
echo ""

# 1. Check DNS resolution
echo "1. Checking DNS resolution..."
DNS_IP=$(dig +short A $DOMAIN 2>/dev/null | head -1)
if [ -z "$DNS_IP" ]; then
    echo "   ❌ DNS not resolved, please configure DNS record first"
    exit 1
fi

SERVER_IP=$(curl -s ifconfig.me 2>/dev/null || curl -s ipinfo.io/ip 2>/dev/null)
echo "   DNS resolved IP: $DNS_IP"
echo "   Server IP: $SERVER_IP"

if [ "$DNS_IP" != "$SERVER_IP" ]; then
    echo "   ⚠️  DNS IP does not match server IP"
    echo "   Please verify DNS configuration"
    read -p "   Continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
else
    echo "   ✅ DNS resolution correct"
fi
echo ""

# 2. Backup existing certificates
echo "2. Backing up existing certificates..."
sudo mkdir -p $BACKUP_DIR
if [ -f "/etc/trojan-cert/trojan.crt" ]; then
    sudo cp /etc/trojan-cert/trojan.crt $BACKUP_DIR/trojan.crt.backup
    sudo cp /etc/trojan-cert/trojan.key $BACKUP_DIR/trojan.key.backup
    echo "   ✅ Backup completed"
fi
echo ""

# 3. Install Certbot (if not installed)
echo "3. Checking Certbot..."
if ! command -v certbot &> /dev/null; then
    echo "   Installing Certbot..."
    sudo apt update -qq
    sudo apt install -y certbot
fi
echo "   ✅ Certbot ready"
echo ""

# 4. Stop conflicting services
echo "4. Stopping conflicting services..."
SERVICES_TO_STOP=()
if systemctl is-active --quiet trojan 2>/dev/null; then
    SERVICES_TO_STOP+=("trojan")
fi
if wg show wg0 >/dev/null 2>&1; then
    SERVICES_TO_STOP+=("wireguard")
fi

for service in "${SERVICES_TO_STOP[@]}"; do
    echo "   Stopping $service..."
    if [ "$service" = "trojan" ]; then
        sudo systemctl stop trojan
    elif [ "$service" = "wireguard" ]; then
        sudo wg-quick down wg0
    fi
done
echo "   ✅ Services stopped"
echo ""

# 5. Request Let's Encrypt certificate
echo "5. Requesting Let's Encrypt certificate..."
echo "   Domain: $DOMAIN"
echo "   Using standalone mode..."

if sudo certbot certonly --standalone \
  -d $DOMAIN \
  --non-interactive \
  --agree-tos \
  --email admin@$DOMAIN \
  --preferred-challenges http \
  --quiet 2>&1 | grep -q "Successfully received certificate"; then
    echo "   ✅ Certificate requested successfully"
else
    echo "   ❌ Certificate request failed"
    echo "   Check:"
    echo "   - DNS A record is correct"
    echo "   - Port 80 is accessible from internet"
    echo "   - Firewall allows port 80 and 443"
    echo "   - Cloudflare proxy is disabled (DNS only)"
    exit 1
fi
echo ""

# 6. Update Trojan configuration
echo "6. Updating Trojan configuration..."
sudo cp $TROJAN_CONFIG $TROJAN_CONFIG.backup_$(date +%Y%m%d_%H%M%S)

# Use Python to update JSON configuration
python3 << PYTHON_EOF
import json
import sys

config_path = "/usr/local/etc/trojan/config.json"
cert_path = "/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
key_path = "/etc/letsencrypt/live/$DOMAIN/privkey.pem"

try:
    with open(config_path, 'r') as f:
        config = json.load(f)
    
    config['ssl']['cert'] = cert_path
    config['ssl']['key'] = key_path
    config['ssl']['verify_hostname'] = True
    
    with open(config_path, 'w') as f:
        json.dump(config, f, indent=4)
    
    print("✅ Configuration updated")
    print(f"   Certificate: {cert_path}")
    print(f"   Private key: {key_path}")
    sys.exit(0)
except Exception as e:
    print(f"❌ Error updating config: {e}")
    sys.exit(1)
PYTHON_EOF

if [ $? -ne 0 ]; then
    echo "   ❌ Failed to update configuration"
    exit 1
fi

# Ensure Trojan can read certificates
sudo chmod 644 $CERT_DIR/fullchain.pem
sudo chmod 600 $CERT_DIR/privkey.pem
echo "   ✅ Permissions set"
echo ""

# 7. Start fallback web server
echo "7. Starting fallback web server (port 80)..."
python3 -m http.server 80 --bind 127.0.0.1 > /dev/null 2>&1 &
WEB_SERVER_PID=$!
sleep 2
if ps -p $WEB_SERVER_PID > /dev/null; then
    echo "   ✅ Web server started (PID: $WEB_SERVER_PID)"
else
    echo "   ⚠️  Web server may not be running"
fi
echo ""

# 8. Restart Trojan
echo "8. Restarting Trojan service..."
sudo systemctl restart trojan
sleep 3

if sudo systemctl is-active --quiet trojan; then
    echo "   ✅ Trojan started successfully"
else
    echo "   ❌ Trojan failed to start"
    echo "   Checking logs..."
    sudo journalctl -u trojan -n 50 --no-pager
    exit 1
fi
echo ""

# 9. Verify certificate
echo "9. Verifying SSL certificate..."
EXPIRY=$(sudo openssl x509 -in $CERT_DIR/fullchain.pem -noout -enddate 2>/dev/null | sed 's/notAfter=/')
if [ -n "$EXPIRY" ]; then
    echo "   Valid until: $EXPIRY"
else
    echo "   ⚠️  Could not read certificate expiry"
fi

# Test TLS handshake
echo "   Testing TLS handshake..."
if timeout 3 openssl s_client -connect 127.0.0.1:443 -servername $DOMAIN </dev/null 2>/dev/null | \
   grep -q "Verify return code: 0 (ok)"; then
    echo "   ✅ TLS handshake successful"
else
    echo "   ⚠️  TLS handshake test failed or timeout"
fi
echo ""

# 10. Configure auto-renewal
echo "10. Configuring certificate auto-renewal..."
EXISTING_CRON=$(crontab -l 2>/dev/null | grep -v "certbot renew")
RENEWAL_CRON="0 3 * * * certbot renew --quiet --post-hook 'systemctl reload trojan'"

if echo "$EXISTING_CRON" | grep -q "certbot renew"; then
    echo "   ℹ️  Auto-renewal already configured"
else
    (echo "$EXISTING_CRON"; echo "$RENEWAL_CRON") | crontab -
    echo "   ✅ Auto-renewal configured (3:00 AM daily)"
fi
echo ""

# 11. Generate client configuration
echo "11. Generating client configuration..."
cat > /tmp/trojan-client-$DOMAIN.json << CLIENT_EOF
{
    "run_type": "client",
    "local_addr": "127.0.0.1",
    "local_port": 1080,
    "remote_addr": "$DOMAIN",
    "remote_port": 443,
    "password": [
        "$(grep -oP '"password":\s*\[\K"[^"]+' $TROJAN_CONFIG | head -1)"
    ],
    "log_level": 1,
    "ssl": {
        "verify": true,
        "verify_hostname": true,
        "cert": "",
        "key_password": "",
        "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384",
        "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384",
        "prefer_server_cipher": true,
        "sni": "$DOMAIN",
        "alpn": [
            "http/1.1"
        ],
        "reuse_session": true,
        "session_ticket": false,
        "tcp_fast_open": false,
        "fingerprint": ""
    },
    "tcp": {
        "prefer_ipv4": false,
        "no_delay": true,
        "keep_alive": true,
        "reuse_port": false,
        "fast_open": false,
        "fast_open_qlen": 20
    }
}
CLIENT_EOF
echo "   ✅ Client config: /tmp/trojan-client-$DOMAIN.json"
echo ""

# 12. Summary
echo "=== Setup Complete ==="
echo ""
echo "📡 Connection Information:"
echo "   Server address: $DOMAIN"
echo "   Port: 443"
echo "   Password: $(grep -oP '"password":\s*\[\K"[^"]+' $TROJAN_CONFIG | head -1)"
echo "   SNI: $DOMAIN"
echo "   Certificate verification: ✅ Enabled (no skip needed)"
echo ""
echo "📱 Client Configuration:"
echo "   JSON config: /tmp/trojan-client-$DOMAIN.json"
echo "   Important: Set verify=true and verify_hostname=true"
echo ""
echo "🔧 Management:"
echo "   Check status: sudo systemctl status trojan"
echo "   View logs: sudo journalctl -u trojan -f"
echo "   Renew cert: sudo certbot renew"
echo "   Test renewal: sudo certbot renew --dry-run"
echo ""
echo "📋 Certificate Details:"
echo "   Domain: $DOMAIN"
echo "   Issuer: Let's Encrypt"
echo "   Expiry: $EXPIRY"
echo "   Auto-renewal: ✅ Enabled (3:00 AM daily)"
echo ""
echo "✅ Setup completed successfully!"
echo ""
echo "Next steps:"
echo "1. Copy client config to your device"
echo "2. Import into Trojan client (Shadowrocket, Clash, etc.)"
echo "3. Test connection (e.g., access https://www.google.com)"
echo ""
