#!/usr/bin/env bash

if [ "$#" -ne 2 ]; then
    echo "Usage: wake-host <MAC> <IP>"
    echo "Example: wake-host AA:BB:CC:DD:EE:FF 100.64.0.10"
    exit 1
fi

TARGET_MAC=$1
TARGET_IP=$2

echo "Sending Magic Packet to $TARGET_MAC..."
wakeonlan "$TARGET_MAC"

echo "Waiting for $TARGET_IP to wake up..."
MAX_RETRIES=24
COUNT=0
until ping -c 1 -W 2 "$TARGET_IP" > /dev/null 2>&1; do
    COUNT=$((COUNT + 1))
    if [ $COUNT -ge $MAX_RETRIES ]; then
        echo "Error: Host failed to wake up after $MAX_RETRIES pings."
        exit 1
    fi
    echo "[$COUNT/$MAX_RETRIES] Host is still sleeping..."
    sleep 5
done

echo "Success: $TARGET_IP is awake."
