#!/bin/bash

########Script to manage services for the AI tools###################
# Usage: ./r.sh [option]
# Options: restart, stop-python, start-python, clear-cache, stop-apache, start-apache, help

# Service names - Separate services for each project
OAT_NATURE_SERVICE="oat-nature-park.service"
OAT_QUIZ_SERVICE="oat-quiz.service"
OAT_DOC_SERVICE="oat-doc.service"
OAT_DOC_WEBSOCKET_SERVICE="oat-doc-websocket.service"
APACHE_SERVICE="apache2"

# All Python services (for bulk operations)
PYTHON_SERVICES=("$OAT_NATURE_SERVICE" "$OAT_QUIZ_SERVICE" "$OAT_DOC_SERVICE")

# Function to display menu
show_menu() {
    echo "=========================================="
    echo "OAT AI Tools Service Management"
    echo "=========================================="
    echo "1) Restart all Python services (Apache optional)"
    echo "2) Stop all Python services"
    echo "3) Start all Python services"
    echo "4) Restart OAT Nature Park service"
    echo "5) Restart OAT Quiz service"
    echo "6) Restart OAT Doc service"
    echo "7) Restart OAT Doc WebSocket service"
    echo "8) Clear Apache cache"
    echo "9) Restart Apache"
    echo "10) Restart all services (Python + Apache)"
    echo "11) Show service status"
    echo "0) Exit"
    echo "=========================================="
}

# Function to restart all Python services
restart_all_python() {
    echo "Reloading systemd daemon..."
    sudo systemctl daemon-reload
    
    echo "Restarting all Python services..."
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  Restarting $service..."
        sudo systemctl restart "$service"
    done
    
    echo ""
    echo "✓ All Python services restarted:"
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  - $service: $(sudo systemctl is-active $service)"
    done
    echo ""
    echo "Note: Apache typically doesn't need restarting when Python services restart."
    echo "      Apache will automatically reconnect to the new backend instances."
    echo ""
    read -p "Do you want to restart Apache anyway? (y/N): " restart_apache
    if [[ $restart_apache =~ ^[Yy]$ ]]; then
        echo "Restarting Apache..."
        sudo systemctl restart $APACHE_SERVICE
        echo "✓ Apache restarted"
    else
        echo "Skipping Apache restart (not required)"
    fi
    
    echo ""
    echo "✓ Successfully Restarted!"
}

# Function to stop all Python services
stop_python() {
    echo "Stopping all Python services..."
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  Stopping $service..."
        sudo systemctl stop "$service"
    done
    
    echo ""
    echo "✓ All Python services stopped:"
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  - $service: $(sudo systemctl is-active $service)"
    done
}

# Function to start all Python services
start_python() {
    echo "Starting all Python services..."
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  Starting $service..."
        sudo systemctl start "$service"
    done
    
    echo ""
    echo "✓ All Python services started:"
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  - $service: $(sudo systemctl is-active $service)"
    done
}

# Function to clear Apache cache
clear_apache_cache() {
    echo "Clearing Apache cache..."
    
    # Clear various Apache cache directories
    if [ -d "/var/cache/apache2" ]; then
        sudo rm -rf /var/cache/apache2/*
        echo "✓ Cleared /var/cache/apache2/"
    fi
    
    if [ -d "/var/www/.cache" ]; then
        sudo rm -rf /var/www/.cache/*
        echo "✓ Cleared /var/www/.cache/"
    fi
    
    # Clear mod_cache if enabled
    if command -v apache2ctl &> /dev/null; then
        sudo apache2ctl clean 2>/dev/null || echo "  (mod_cache clean not available)"
    fi
    
    echo ""
    echo "✓ Apache cache cleared"
}

# Function to stop Apache
stop_apache() {
    echo "Stopping Apache..."
    sudo systemctl stop $APACHE_SERVICE
    
    echo ""
    echo "✓ Apache stopped"
    echo "  Status: $(sudo systemctl is-active $APACHE_SERVICE)"
}

# Function to start Apache
start_apache() {
    echo "Starting Apache..."
    sudo systemctl start $APACHE_SERVICE
    
    echo ""
    echo "✓ Apache started"
    echo "  Status: $(sudo systemctl is-active $APACHE_SERVICE)"
}

# Function to restart Apache
restart_apache() {
    echo "Restarting Apache..."
    sudo systemctl restart $APACHE_SERVICE
    
    echo ""
    echo "✓ Apache restarted"
    echo "  Status: $(sudo systemctl is-active $APACHE_SERVICE)"
}

# Function to show service status
show_status() {
    echo ""
    echo "Service Status:"
    echo "=========================================="
    echo "OAT Nature Park:"
    echo "  $OAT_NATURE_SERVICE: $(sudo systemctl is-active $OAT_NATURE_SERVICE)"
    echo ""
    echo "OAT Quiz:"
    echo "  $OAT_QUIZ_SERVICE: $(sudo systemctl is-active $OAT_QUIZ_SERVICE)"
    echo ""
    echo "OAT Doc:"
    echo "  $OAT_DOC_SERVICE: $(sudo systemctl is-active $OAT_DOC_SERVICE)"
    echo ""
    echo "OAT Doc WebSocket:"
    echo "  $OAT_DOC_WEBSOCKET_SERVICE: $(sudo systemctl is-active $OAT_DOC_WEBSOCKET_SERVICE)"
    echo ""
    echo "Apache:"
    echo "  $APACHE_SERVICE: $(sudo systemctl is-active $APACHE_SERVICE)"
    echo "=========================================="
}

# Function to restart OAT Doc WebSocket service
restart_oat_doc_websocket() {
    echo "Restarting OAT Doc WebSocket service..."
    sudo systemctl restart $OAT_DOC_WEBSOCKET_SERVICE
    
    # Wait a moment for service to start
    sleep 2
    
    # Check service status
    STATUS=$(sudo systemctl is-active $OAT_DOC_WEBSOCKET_SERVICE)
    
    echo ""
    if [ "$STATUS" = "active" ]; then
        echo "✓ OAT Doc WebSocket service restarted successfully"
        echo "  Status: $STATUS"
        
        # Show additional status info
        echo ""
        echo "Service Details:"
        sudo systemctl status $OAT_DOC_WEBSOCKET_SERVICE --no-pager -l | head -10
    else
        echo "✗ OAT Doc WebSocket service restart failed or is not active"
        echo "  Status: $STATUS"
        echo ""
        echo "Recent logs:"
        sudo journalctl -u $OAT_DOC_WEBSOCKET_SERVICE -n 10 --no-pager
    fi
}

# Function to show help
show_help() {
    echo "Usage: ./r.sh [option]"
    echo ""
    echo "Options:"
    echo "  restart        - Restart all Python services (Apache not required)"
    echo "  restart-all    - Restart all Python services AND Apache"
    echo "  stop-python    - Stop all Python services"
    echo "  start-python   - Start all Python services"
    echo "  restart-nature - Restart OAT Nature Park service"
    echo "  restart-quiz   - Restart OAT Quiz service"
    echo "  restart-doc    - Restart OAT Doc service"
    echo "  clear-cache    - Clear Apache cache"
    echo "  restart-apache - Restart Apache"
    echo "  restart-oat-doc-ws - Restart OAT Doc WebSocket service"
    echo "  status         - Show service status"
    echo "  help           - Show this help message"
    echo ""
    echo "Note: Apache typically doesn't need restarting when Python services restart."
    echo "      Apache will automatically reconnect to the new backend instances."
    echo ""
    echo "If no option is provided, an interactive menu will be shown."
}

# Function to restart Python services only (without Apache)
restart_python() {
    echo "Reloading systemd daemon..."
    sudo systemctl daemon-reload
    
    echo "Restarting all Python services..."
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  Restarting $service..."
        sudo systemctl restart "$service"
    done
    
    echo ""
    echo "✓ All Python services restarted:"
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  - $service: $(sudo systemctl is-active $service)"
    done
    echo ""
    echo "Note: Apache doesn't need restarting - it will automatically reconnect."
}

# Function to restart all services (Python + Apache)
restart_all_with_apache() {
    echo "Reloading systemd daemon..."
    sudo systemctl daemon-reload
    
    echo "Restarting all Python services..."
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  Restarting $service..."
        sudo systemctl restart "$service"
    done
    
    echo "Restarting Apache..."
    sudo systemctl restart $APACHE_SERVICE
    
    echo ""
    echo "✓ All services restarted:"
    for service in "${PYTHON_SERVICES[@]}"; do
        echo "  - $service: $(sudo systemctl is-active $service)"
    done
    echo "  - $APACHE_SERVICE: $(sudo systemctl is-active $APACHE_SERVICE)"
    echo ""
    echo "✓ Successfully Restarted!"
}

# Main script logic
if [ $# -eq 0 ]; then
    # Interactive mode
    while true; do
        show_menu
        read -p "Select an option [0-9]: " choice
        
        case $choice in
            1)
                restart_python
                echo ""
                read -p "Press Enter to continue..."
                ;;
            2)
                stop_python
                echo ""
                read -p "Press Enter to continue..."
                ;;
            3)
                start_python
                echo ""
                read -p "Press Enter to continue..."
                ;;
            4)
                echo "Restarting OAT Nature Park service..."
                sudo systemctl restart $OAT_NATURE_SERVICE
                echo "  Status: $(sudo systemctl is-active $OAT_NATURE_SERVICE)"
                echo ""
                read -p "Press Enter to continue..."
                ;;
            5)
                echo "Restarting OAT Quiz service..."
                sudo systemctl restart $OAT_QUIZ_SERVICE
                echo "  Status: $(sudo systemctl is-active $OAT_QUIZ_SERVICE)"
                echo ""
                read -p "Press Enter to continue..."
                ;;
            6)
                echo "Restarting OAT Doc service..."
                sudo systemctl restart $OAT_DOC_SERVICE
                echo "  Status: $(sudo systemctl is-active $OAT_DOC_SERVICE)"
                echo ""
                read -p "Press Enter to continue..."
                ;;
            7)
                restart_oat_doc_websocket
                echo ""
                read -p "Press Enter to continue..."
                ;;
            8)
                clear_apache_cache
                echo ""
                read -p "Press Enter to continue..."
                ;;
            9)
                restart_apache
                echo ""
                read -p "Press Enter to continue..."
                ;;
            10)
                restart_all_with_apache
                echo ""
                read -p "Press Enter to continue..."
                ;;
            11)
                show_status
                echo ""
                read -p "Press Enter to continue..."
                ;;
            0)
                echo "Exiting..."
                exit 0
                ;;
            *)
                echo "Invalid option. Please try again."
                sleep 1
                ;;
        esac
        clear
    done
else
    # Command-line argument mode
    case $1 in
        restart)
            restart_python
            ;;
        restart-all)
            restart_all_with_apache
            ;;
        stop-python)
            stop_python
            ;;
        start-python)
            start_python
            ;;
        clear-cache)
            clear_apache_cache
            ;;
        stop-apache)
            stop_apache
            ;;
        start-apache)
            start_apache
            ;;
        restart-apache)
            restart_apache
            ;;
        restart-nature)
            echo "Restarting OAT Nature Park service..."
            sudo systemctl restart $OAT_NATURE_SERVICE
            echo "  Status: $(sudo systemctl is-active $OAT_NATURE_SERVICE)"
            ;;
        restart-quiz)
            echo "Restarting OAT Quiz service..."
            sudo systemctl restart $OAT_QUIZ_SERVICE
            echo "  Status: $(sudo systemctl is-active $OAT_QUIZ_SERVICE)"
            ;;
        restart-doc)
            echo "Restarting OAT Doc service..."
            sudo systemctl restart $OAT_DOC_SERVICE
            echo "  Status: $(sudo systemctl is-active $OAT_DOC_SERVICE)"
            ;;
        restart-oat-doc-ws)
            restart_oat_doc_websocket
            ;;
        status)
            show_status
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            echo "Unknown option: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
fi
