#!/bin/bash

# Hyperliquid Trading Bot Restart Script
# This script safely restarts the bot with latest code and fresh logs

set -e  # Exit on any error

echo "🤖 Hyperliquid Trading Bot Restart Script"
echo "=========================================="

# Check if running as correct user (optional - remove if not needed)
# if [[ $EUID -eq 0 ]]; then
#    echo "❌ This script should not be run as root for security reasons"
#    exit 1
# fi

# Function to print timestamped messages
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# Function to check if service exists
check_service() {
    if ! systemctl list-unit-files | grep -q "trading-bot.service"; then
        log "âš ī¸  trading-bot.service not found in systemctl"
        log "â„šī¸  Continuing without systemctl operations..."
        return 1
    fi
    return 0
}

# Step 1: Stop the trading bot service
log "🛑 Stopping trading bot service..."
if check_service; then
    if systemctl is-active --quiet trading-bot.service; then
        sudo systemctl stop trading-bot.service
        log "✅ Service stopped successfully"
        
        # Wait a moment for graceful shutdown
        sleep 2
        
        # Verify it's stopped
        if systemctl is-active --quiet trading-bot.service; then
            log "❌ Service is still running after stop command"
            exit 1
        else
            log "✅ Service confirmed stopped"
        fi
    else
        log "â„šī¸  Service was already stopped"
    fi
else
    log "âš ī¸  Skipping service stop (service not found)"
fi

# Step 2: Pull latest code from git
log "📡 Pulling latest code from git..."
if git status &>/dev/null; then
    # Check if we have uncommitted changes
    if ! git diff-index --quiet HEAD --; then
        log "âš ī¸  You have uncommitted changes:"
        git status --porcelain
        read -p "Do you want to continue and potentially lose changes? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log "❌ Restart cancelled by user"
            exit 1
        fi
        log "âš ī¸  Proceeding with uncommitted changes..."
    fi
    
    # Save current branch
    CURRENT_BRANCH=$(git branch --show-current)
    log "â„šī¸  Current branch: $CURRENT_BRANCH"
    
    # Pull latest changes
    if git pull origin main; then
        log "✅ Git pull completed successfully"
    else
        log "❌ Git pull failed"
        exit 1
    fi
else
    log "âš ī¸  Not a git repository, skipping git pull"
fi

# Step 3: Remove old log file
log "đŸ—‘ī¸  Clearing old log file..."
if [ -f "logs/trading_bot.log" ]; then
    rm logs/trading_bot.log
    log "✅ Old log file removed"
else
    log "â„šī¸  Log file doesn't exist (already clean)"
fi

# Ensure logs directory exists
if [ ! -d "logs" ]; then
    mkdir -p logs
    log "✅ Created logs directory"
fi

# Step 4: Restart the trading bot service
log "🚀 Starting trading bot service..."
if check_service; then
    # Use reload-or-restart as requested
    sudo systemctl reload-or-restart trading-bot.service
    log "✅ Service restart command sent"
    
    # Wait a moment for startup
    sleep 3
    
    # Check if service started successfully
    if systemctl is-active --quiet trading-bot.service; then
        log "✅ Service is running successfully"
        
        # Show service status
        log "📊 Service status:"
        systemctl status trading-bot.service --no-pager -l
        
    else
        log "❌ Service failed to start"
        log "📋 Service logs:"
        sudo journalctl -u trading-bot.service --no-pager -l --since "1 minute ago"
        exit 1
    fi
else
    log "âš ī¸  Skipping service restart (service not found)"
    log "â„šī¸  You may need to start the bot manually"
fi

# Step 5: Optional - tail logs for a few seconds
log "📋 Showing recent logs..."
if [ -f "logs/trading_bot.log" ]; then
    echo "----------------------------------------"
    echo "Recent log entries:"
    tail -n 20 logs/trading_bot.log || log "âš ī¸  Could not read log file yet"
else
    log "â„šī¸  Log file not created yet, showing systemd logs:"
    sudo journalctl -u trading-bot.service --no-pager -l --since "30 seconds ago" | tail -n 10
fi

echo "=========================================="
log "🎉 Bot restart completed successfully!"
log "💡 Use 'tail -f logs/trading_bot.log' to monitor logs"
log "💡 Use 'systemctl status trading-bot.service' to check service status"