#!/bin/bash
# Setup health check script and cron job

set -e

echo "Setting up health check system..."

# Create health check script
cat > /usr/local/bin/explorer-health-check.sh << 'EOF'
#!/bin/bash
API_URL="http://localhost:8080/health"
LOG_FILE="/var/log/explorer-health-check.log"

# Check API health
STATUS=$(curl -s -o /dev/null -w "%{http_code}" $API_URL 2>/dev/null || echo "000")

if [ "$STATUS" != "200" ]; then
    echo "$(date): Health check failed - Status: $STATUS" >> $LOG_FILE
    
    # Restart API service
    systemctl restart explorer-api
    
    # Wait a bit and check again
    sleep 10
    STATUS2=$(curl -s -o /dev/null -w "%{http_code}" $API_URL 2>/dev/null || echo "000")
    
    if [ "$STATUS2" != "200" ]; then
        echo "$(date): API still unhealthy after restart - Status: $STATUS2" >> $LOG_FILE
        # Send alert (configure email/Slack/etc here)
    else
        echo "$(date): API recovered after restart" >> $LOG_FILE
    fi
fi
EOF

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

# Add to crontab (every 5 minutes)
(crontab -l 2>/dev/null | grep -v explorer-health-check.sh; echo "*/5 * * * * /usr/local/bin/explorer-health-check.sh") | crontab -

echo "Health check system configured!"
echo "Health checks will run every 5 minutes"
echo "Log file: /var/log/explorer-health-check.log"

