#!/usr/bin/env bash

set -euo pipefail

# Usage: HOST=agent02 PHASE=install ./waitForReboot.sh

HOST=${HOST:-}
PHASE=${PHASE:-install}

# Require HOST to be specified
if [ -z "$HOST" ]; then
  echo "❌ ERROR: HOST environment variable is required"
  echo ""
  echo "Usage:"
  echo "  HOST=agent01 yarn macmini:wait:install"
  echo "  HOST=agent02 yarn macmini:wait:full"
  echo ""
  exit 1
fi

echo "🔍 Checking if $HOST is online..."

# Try to resolve hostname first
HOSTNAME="jenkinsagent@$HOST"

# Try immediate connection first (quick check)
if ssh -o ConnectTimeout=3 -o BatchMode=yes -o StrictHostKeyChecking=no "$HOSTNAME" "echo 2>&1" >/dev/null 2>&1; then
    echo "✅ $HOST is already online!"
    echo ""

    # Execute the phase if specified
    if [ -n "${PHASE:-}" ]; then
        echo "▶️  Running phase: $PHASE"
        if [ "$PHASE" = "full" ]; then
            AGENT=$AGENT yarn macmini:full
        else
            AGENT=$AGENT PHASE=$PHASE yarn macmini
        fi
    fi

    exit 0
fi

echo "⏳ $HOST is not reachable yet, waiting for it to come back online..."
echo "🔍 Will check SSH connectivity every 10 seconds..."
echo ""

# Wait for machine to go down (if it hasn't already)
sleep 5

# Counter for attempts
ATTEMPTS=0
MAX_ATTEMPTS=60  # 10 minutes max

while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; do
    ATTEMPTS=$((ATTEMPTS + 1))
    
    # Try to connect with a 5 second timeout
    if ssh -o ConnectTimeout=5 -o BatchMode=yes -o StrictHostKeyChecking=no "$HOSTNAME" "echo 2>&1" >/dev/null 2>&1; then
        echo ""
        echo "✅ $HOST is back online!"
        echo ""
        
        # Give the system a few more seconds to fully stabilize
        echo "⏳ Waiting 10 seconds for system to stabilize..."
        sleep 10
        
        # Now continue with the requested phase
        if [ "$PHASE" = "full" ]; then
            echo "🚀 Running full setup (init -> install -> setup -> about)..."
            AGENT=$AGENT yarn macmini:full
        elif [ "$PHASE" = "install" ]; then
            echo "🚀 Running install phase..."
            AGENT=$AGENT PHASE=install yarn macmini
        else
            echo "🚀 Running $PHASE phase..."
            AGENT=$AGENT PHASE=$PHASE yarn macmini
        fi
        
        exit 0
    fi
    
    # Show progress every 30 seconds
    if [ $((ATTEMPTS % 3)) -eq 0 ]; then
        ELAPSED=$((ATTEMPTS * 10))
        echo "⏳ Still waiting... (${ELAPSED}s elapsed)"
    fi
    
    sleep 10
done

echo ""
echo "❌ Timeout: $HOST did not come back online after $((MAX_ATTEMPTS * 10)) seconds"
echo "💡 Try manually: yarn macmini:${HOST}:${PHASE}"
exit 1
