#!/bin/bash
# Trojan Service Status Check Script
#
# This script checks the health and status of a running Trojan service,
# including service status, port binding, SSL certificate validity,
# and configuration verification.
#
# Usage: bash check-trojan.sh [domain]
# Default domain: hot13399.com

DOMAIN="${1:-hot13399.com}"
TROJAN_CONFIG="/usr/local/etc/trojan/config.json"

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

echo "=== Trojan Service Status Check ==="
echo "Domain: $DOMAIN"
echo ""

# 1. Check Trojan service status
echo "1. Trojan Service Status:"
if systemctl is-active --quiet trojan 2>/dev/null; then
    echo -e "   ${GREEN}✅${NC} Trojan is running"
else
    echo -e "   ${RED}❌${NC} Trojan is not running"
    echo "   Try: sudo systemctl start trojan"
    exit 1
fi
echo ""

# 2. Check port 443 binding
echo "2. Port 443 Binding Status:"
if ss -tlnp 2>/dev/null | grep -q ":443.*trojan"; then
    echo -e "   ${GREEN}✅${NC} Port 443 is listening (Trojan)"
else
    echo -e "   ${RED}❌${NC} Port 443 is not listening or not bound to Trojan"
    echo "   Check: sudo ss -tlnp | grep 443"
    exit 1
fi
echo ""

# 3. Check SSL certificate
echo "3. SSL Certificate Status:"
CERT_PATH="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
if [ -f "$CERT_PATH" ]; then
    echo -e "   ${GREEN}✅${NC} Certificate file exists"
    
    # Extract certificate details
    EXPIRY=$(sudo openssl x509 -in $CERT_PATH -noout -enddate 2>/dev/null | sed 's/notAfter=/')
    SUBJECT=$(sudo openssl x509 -in $CERT_PATH -noout -subject 2>/dev/null | sed -n 's/.*CN = //p')
    ISSUER=$(sudo openssl x509 -in $CERT_PATH -noout -issuer 2>/dev/null | sed -n 's/.*CN = //p')
    
    echo "   Subject: $SUBJECT"
    echo "   Issuer: $ISSUER"
    echo "   Expiry: $EXPIRY"
    
    # Check if certificate is expiring soon
    EXPIRY_DATE=$(date -d "$EXPIRY" +%s 2>/dev/null || echo 0)
    CURRENT_DATE=$(date +%s)
    DAYS_LEFT=$(( ($EXPIRY_DATE - $CURRENT_DATE) / 86400 ))
    
    if [ $DAYS_LEFT -lt 30 ]; then
        echo -e "   ${YELLOW}⚠️  WARNING: Certificate expires in $DAYS_LEFT days${NC}"
        echo "   Run: sudo certbot renew"
    else
        echo -e "   ${GREEN}✅${NC} Certificate valid for $DAYS_LEFT days"
    fi
else
    echo -e "   ${YELLOW}⚠️${NC} Let's Encrypt certificate not found"
    echo "   Checking for self-signed certificate..."
    
    SELF_SIGNED_CERT="/etc/trojan-cert/trojan.crt"
    if [ -f "$SELF_SIGNED_CERT" ]; then
        echo -e "   ${YELLOW}⚠️${NC} Using self-signed certificate"
        echo "   Consider upgrading to Let's Encrypt"
    else
        echo -e "   ${RED}❌${NC} No certificate found"
        exit 1
    fi
fi
echo ""

# 4. Test TLS handshake
echo "4. TLS Handshake Test:"
HANDSHAKE_RESULT=$(echo | timeout 3 openssl s_client -connect 127.0.0.1:443 -servername $DOMAIN 2>/dev/null | \
  grep "Verify return code" | head -1)

if [ -n "$HANDSHAKE_RESULT" ]; then
    echo "   $HANDSHAKE_RESULT"
    if echo "$HANDSHAKE_RESULT" | grep -q "0 (ok)"; then
        echo -e "   ${GREEN}✅${NC} TLS handshake successful"
    else
        echo -e "   ${RED}❌${NC} TLS handshake verification failed"
    fi
    
    # Show protocol and cipher
    PROTOCOL=$(echo | timeout 3 openssl s_client -connect 127.0.0.1:443 -servername $DOMAIN 2>/dev/null | \
      grep "Protocol" | head -1)
    CIPHER=$(echo | timeout 3 openssl s_client -connect 127.0.0.1:443 -servername $DOMAIN 2>/dev/null | \
      grep "Cipher" | head -1)
    echo "   $PROTOCOL"
    echo "   $CIPHER"
else
    echo -e "   ${YELLOW}⚠️${NC} TLS handshake test timeout (may be normal)"
fi
echo ""

# 5. Check configuration file
echo "5. Configuration File Status:"
if [ -f "$TROJAN_CONFIG" ]; then
    echo -e "   ${GREEN}✅${NC} Configuration file exists"
    
    # Extract and display key configuration values
    LISTEN_PORT=$(grep -oP '"local_port":\s*\K\d+' $TROJAN_CONFIG)
    PASSWORD_COUNT=$(grep -c '"password"' $TROJAN_CONFIG | head -1)
    
    echo "   Listen port: $LISTEN_PORT"
    echo "   Password count: $PASSWORD_COUNT"
    
    # Check if using Let's Encrypt or self-signed
    if grep -q "/etc/letsencrypt/live/" $TROJAN_CONFIG; then
        echo -e "   ${GREEN}✅${NC} Using Let's Encrypt certificate"
    elif grep -q "/etc/trojan-cert/" $TROJAN_CONFIG; then
        echo -e "   ${YELLOW}⚠️${NC} Using self-signed certificate"
    fi
else
    echo -e "   ${RED}❌${NC} Configuration file not found: $TROJAN_CONFIG"
    exit 1
fi
echo ""

# 6. Check for common issues
echo "6. Common Issues Check:"

# Check if port 80 is available (for cert renewal)
if ss -tlnp 2>/dev/null | grep -q ":80"; then
    echo -e "   ${YELLOW}⚠️${NC} Port 80 is in use"
    echo "   This may block cert renewal. Check: sudo ss -tlnp | grep 80"
else
    echo -e "   ${GREEN}✅${NC} Port 80 is available (good for cert renewal)"
fi

# Check if crontab has renewal configured
if crontab -l 2>/dev/null | grep -q "certbot renew"; then
    echo -e "   ${GREEN}✅${NC} Auto-renewal cron configured"
else
    echo -e "   ${YELLOW}⚠️${NC} Auto-renewal not configured"
    echo "   Add: 0 3 * * * certbot renew --quiet --post-hook 'systemctl reload trojan'"
fi

# Check disk space for certificates
DISK_AVAILABLE=$(df / | tail -1 | awk '{print $4}')
if [ "$DISK_AVAILABLE" -lt 1048576 ]; then  # Less than 1GB
    echo -e "   ${YELLOW}⚠️${NC} Low disk space: $DISK_AVAILABLE KB available"
else
    echo -e "   ${GREEN}✅${NC} Disk space sufficient"
fi
echo ""

# 7. Service summary
echo "=== Service Summary ==="
echo ""

# Determine connection info
REMOTE_ADDR=$(grep -oP '"remote_addr":\s*"\K[^"]+' $TROJAN_CONFIG)
PASSWORD=$(grep -oP '"password":\s*\[\K"[^"]+' $TROJAN_CONFIG | head -1)

echo "📡 Connection Information:"
echo "   Domain: $DOMAIN"
echo "   Remote address: $REMOTE_ADDR"
echo "   Port: 443"
echo "   Password: $PASSWORD"
echo "   SNI: $DOMAIN"
echo ""

echo "📊 Service Status:"
if systemctl is-active --quiet trojan && ss -tlnp 2>/dev/null | grep -q ":443.*trojan"; then
    echo -e "   ${GREEN}✅${NC} All services operational"
else
    echo -e "   ${RED}❌${NC} Service issues detected"
fi
echo ""

echo "🔧 Quick Actions:"
echo "   Restart Trojan:     sudo systemctl restart trojan"
echo "   Check logs:        sudo journalctl -u trojan -f"
echo "   Renew certificate:  sudo certbot renew"
echo "   Test renewal:      sudo certbot renew --dry-run"
echo "   View config:       cat $TROJAN_CONFIG"
echo ""

echo "📱 Client Configuration:"
if grep -q "/etc/letsencrypt/live/" $TROJAN_CONFIG; then
    echo "   Type: Trojan"
    echo "   Server: $DOMAIN"
    echo "   Port: 443"
    echo "   Password: $PASSWORD"
    echo "   SNI: $DOMAIN"
    echo -e "   ${GREEN}skip-cert-verify: false${NC} (production)"
    echo ""
    echo "   ✅ Production ready - use domain with real certificate"
else
    echo "   Type: Trojan"
    echo "   Server: $REMOTE_ADDR"
    echo "   Port: 443"
    echo "   Password: $PASSWORD"
    echo "   SNI: $REMOTE_ADDR"
    echo -e "   ${YELLOW}skip-cert-verify: true${NC} (self-signed)"
    echo ""
    echo "   ⚠️  Using self-signed certificate - skip-cert-verify required on client"
fi
echo ""

echo "✅ Status check complete!"
