#!/bin/bash
# Info: Zombienet service management script
# Author: Provisioning System

ZOMBIENET_BIN="{{ polkadot_zombienet.bin_path }}/{{ polkadot_zombienet.zombienet_binary }}"
NETWORKS_PATH="{{ polkadot_zombienet.networks_path }}"
LOGS_PATH="{{ polkadot_zombienet.logs_path }}"
CONFIG_PATH="{{ polkadot_zombienet.config_path }}"
PROVIDER="{{ polkadot_zombienet.settings.provider }}"
RUN_USER="{{ polkadot_zombienet.run_user.name }}"

# Default network configuration
DEFAULT_NETWORK="$NETWORKS_PATH/simple-network.toml"
CURRENT_NETWORK_FILE="$CONFIG_PATH/current-network.toml"
PID_FILE="$CONFIG_PATH/zombienet.pid"

case "$1" in
    start)
        NETWORK_FILE="${2:-$DEFAULT_NETWORK}"
        
        if [ ! -f "$NETWORK_FILE" ]; then
            echo "Network file not found: $NETWORK_FILE"
            exit 1
        fi
        
        if [ -f "$PID_FILE" ]; then
            PID=$(cat "$PID_FILE")
            if kill -0 "$PID" 2>/dev/null; then
                echo "Zombienet is already running (PID: $PID)"
                exit 1
            else
                rm -f "$PID_FILE"
            fi
        fi
        
        echo "Starting Zombienet with network: $NETWORK_FILE"
        echo "Provider: $PROVIDER"
        echo "Logs will be written to: $LOGS_PATH"
        
        # Copy network file to current
        cp "$NETWORK_FILE" "$CURRENT_NETWORK_FILE"
        
        # Start zombienet in background
        nohup sudo -u "$RUN_USER" "$ZOMBIENET_BIN" spawn \
            --provider "$PROVIDER" \
            "$CURRENT_NETWORK_FILE" \
            > "$LOGS_PATH/zombienet.log" 2>&1 &
        
        echo $! > "$PID_FILE"
        echo "Zombienet started with PID: $(cat $PID_FILE)"
        echo "Monitor logs with: tail -f $LOGS_PATH/zombienet.log"
        ;;
        
    stop)
        if [ ! -f "$PID_FILE" ]; then
            echo "Zombienet is not running (no PID file)"
            exit 1
        fi
        
        PID=$(cat "$PID_FILE")
        if ! kill -0 "$PID" 2>/dev/null; then
            echo "Zombienet process not found (stale PID file)"
            rm -f "$PID_FILE"
            exit 1
        fi
        
        echo "Stopping Zombienet (PID: $PID)..."
        
        # Kill the process tree
        pkill -P "$PID" 2>/dev/null || true
        kill "$PID" 2>/dev/null || true
        
        # Wait for graceful shutdown
        for i in {1..30}; do
            if ! kill -0 "$PID" 2>/dev/null; then
                break
            fi
            sleep 1
        done
        
        # Force kill if still running
        if kill -0 "$PID" 2>/dev/null; then
            echo "Force killing Zombienet..."
            kill -9 "$PID" 2>/dev/null || true
        fi
        
        rm -f "$PID_FILE"
        echo "Zombienet stopped"
        ;;
        
    restart)
        $0 stop
        sleep 2
        $0 start "$2"
        ;;
        
    status)
        if [ -f "$PID_FILE" ]; then
            PID=$(cat "$PID_FILE")
            if kill -0 "$PID" 2>/dev/null; then
                echo "Zombienet is running (PID: $PID)"
                if [ -f "$CURRENT_NETWORK_FILE" ]; then
                    echo "Current network: $CURRENT_NETWORK_FILE"
                fi
                
                # Show some network info
                echo ""
                echo "Network processes:"
                pgrep -f "polkadot\|zombienet" | head -10
                
                exit 0
            else
                echo "Zombienet is not running (stale PID file)"
                rm -f "$PID_FILE"
                exit 1
            fi
        else
            echo "Zombienet is not running"
            exit 1
        fi
        ;;
        
    logs)
        if [ -f "$LOGS_PATH/zombienet.log" ]; then
            tail -f "$LOGS_PATH/zombienet.log"
        else
            echo "No logs found at $LOGS_PATH/zombienet.log"
            exit 1
        fi
        ;;
        
    test)
        TEST_FILE="$2"
        if [ -z "$TEST_FILE" ]; then
            echo "Usage: $0 test <test-file.zndsl>"
            exit 1
        fi
        
        if [ ! -f "$TEST_FILE" ]; then
            echo "Test file not found: $TEST_FILE"
            exit 1
        fi
        
        echo "Running test: $TEST_FILE"
        sudo -u "$RUN_USER" "$ZOMBIENET_BIN" test --provider "$PROVIDER" "$TEST_FILE"
        ;;
        
    *)
        echo "Zombienet Service Management"
        echo "Usage: $0 {start|stop|restart|status|logs|test} [options]"
        echo ""
        echo "Commands:"
        echo "  start [network.toml]  Start Zombienet with specified network"
        echo "  stop                  Stop running Zombienet"
        echo "  restart [network.toml] Restart Zombienet"
        echo "  status                Show Zombienet status"
        echo "  logs                  Follow Zombienet logs"
        echo "  test <file.zndsl>     Run a test file"
        echo ""
        echo "Provider: $PROVIDER"
        echo "Default network: $DEFAULT_NETWORK"
        exit 1
        ;;
esac