#!/usr/bin/env bash
# Set up basic monitoring for Nginx on VMID 2500
# - Nginx status page
# - Log rotation
# - Basic health check script

set -e

VMID=2500
PROXMOX_HOST="192.168.11.10"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "Setting up monitoring for Nginx on VMID $VMID"
echo ""

# Enable Nginx status page
log_info "1. Enabling Nginx status page..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'STATUS_EOF'
# Add status location to nginx.conf if not present
if ! grep -q "stub_status" /etc/nginx/nginx.conf; then
    # Add status location in http block
    cat >> /etc/nginx/nginx.conf <<'NGINX_STATUS'
    # Nginx status page (internal only)
    server {
        listen 127.0.0.1:8080;
        server_name localhost;
        
        location /nginx_status {
            stub_status on;
            access_log off;
            allow 127.0.0.1;
            deny all;
        }
    }
NGINX_STATUS
fi

# Test configuration
nginx -t
STATUS_EOF

if [ $? -eq 0 ]; then
    log_success "Nginx status page enabled on port 8080"
else
    log_warn "Status page configuration may need manual adjustment"
fi

# Configure log rotation
log_info ""
log_info "2. Configuring log rotation..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'LOGROTATE_EOF'
cat > /etc/logrotate.d/nginx-rpc <<'LOGROTATE_CONFIG'
/var/log/nginx/rpc-core-*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}
LOGROTATE_CONFIG

# Test logrotate configuration
logrotate -d /etc/logrotate.d/nginx-rpc
LOGROTATE_EOF

if [ $? -eq 0 ]; then
    log_success "Log rotation configured (14 days retention)"
else
    log_warn "Log rotation may need manual configuration"
fi

# Create health check script
log_info ""
log_info "3. Creating health check script..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'HEALTH_EOF'
cat > /usr/local/bin/nginx-health-check.sh <<'HEALTH_SCRIPT'
#!/bin/bash
# Nginx health check script

EXIT_CODE=0

# Check Nginx service
if ! systemctl is-active --quiet nginx; then
    echo "ERROR: Nginx service is not active"
    EXIT_CODE=1
fi

# Check Nginx status page
if ! curl -s http://127.0.0.1:8080/nginx_status >/dev/null 2>&1; then
    echo "WARNING: Nginx status page not accessible"
fi

# Check RPC endpoint
RPC_RESPONSE=$(curl -k -s -X POST https://localhost:443 \
    -H 'Content-Type: application/json' \
    -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>&1)

if echo "$RPC_RESPONSE" | grep -q "result"; then
    echo "OK: RPC endpoint responding"
else
    echo "ERROR: RPC endpoint not responding"
    EXIT_CODE=1
fi

# Check ports
for port in 80 443 8443; do
    if ! ss -tln | grep -q ":$port "; then
        echo "ERROR: Port $port not listening"
        EXIT_CODE=1
    fi
done

exit $EXIT_CODE
HEALTH_SCRIPT

chmod +x /usr/local/bin/nginx-health-check.sh
HEALTH_EOF

if [ $? -eq 0 ]; then
    log_success "Health check script created at /usr/local/bin/nginx-health-check.sh"
else
    log_warn "Health check script creation failed"
fi

# Create systemd service for health monitoring (optional)
log_info ""
log_info "4. Creating monitoring service..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'SERVICE_EOF'
cat > /etc/systemd/system/nginx-health-monitor.service <<'SERVICE_CONFIG'
[Unit]
Description=Nginx Health Monitor
After=nginx.service
Requires=nginx.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/nginx-health-check.sh
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
SERVICE_CONFIG

# Create timer for periodic health checks
cat > /etc/systemd/system/nginx-health-monitor.timer <<'TIMER_CONFIG'
[Unit]
Description=Run Nginx Health Check Every 5 Minutes
Requires=nginx-health-monitor.service

[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
Unit=nginx-health-monitor.service

[Install]
WantedBy=timers.target
TIMER_CONFIG

systemctl daemon-reload
systemctl enable nginx-health-monitor.timer
systemctl start nginx-health-monitor.timer
SERVICE_EOF

if [ $? -eq 0 ]; then
    log_success "Health monitoring service enabled (checks every 5 minutes)"
else
    log_warn "Health monitoring service may need manual setup"
fi

# Reload Nginx
log_info ""
log_info "5. Reloading Nginx..."
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl reload nginx"

if [ $? -eq 0 ]; then
    log_success "Nginx reloaded"
else
    log_error "Failed to reload Nginx"
    exit 1
fi

# Test health check
log_info ""
log_info "6. Testing health check..."
HEALTH_RESULT=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- /usr/local/bin/nginx-health-check.sh 2>&1")

echo "$HEALTH_RESULT"

if echo "$HEALTH_RESULT" | grep -q "OK"; then
    log_success "Health check passed"
else
    log_warn "Health check found issues (review output above)"
fi

echo ""
log_success "Monitoring setup complete!"
echo ""
log_info "Monitoring Summary:"
log_info "  ✓ Nginx status page: http://127.0.0.1:8080/nginx_status"
log_info "  ✓ Log rotation: 14 days retention, daily rotation"
log_info "  ✓ Health check script: /usr/local/bin/nginx-health-check.sh"
log_info "  ✓ Health monitoring service: Runs every 5 minutes"
echo ""
log_info "View status: pct exec $VMID -- curl http://127.0.0.1:8080/nginx_status"
log_info "Run health check: pct exec $VMID -- /usr/local/bin/nginx-health-check.sh"

