#!/usr/bin/env bash
# wait_for_reboot is the only thing standing between "sshd answered" and "the host
# actually came back from a boot", so it is tested against a stub host that keeps
# answering with the old boot id for a while — the shutdown window that made an
# answer-only wait return too early. Contacts no host.
set -uo pipefail

SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/bin/buildbox"
pass=0; fail=0
ok() { pass=$((pass+1)); echo "ok   $1"; }
bad() { fail=$((fail+1)); echo "FAIL $1"; }

eval "$(awk '/^wait_for_reboot\(\)/,/^}$/' "$SRC")"
[ "$(type -t wait_for_reboot)" = function ] || { echo "FAIL could not extract wait_for_reboot from $SRC"; exit 1; }

STATE="$(mktemp -d)"
trap 'rm -rf "$STATE"' EXIT
echo 0 >"$STATE/n"

# Answers with the old boot id for the first 2 polls (sshd still up on the way down),
# nothing for the next 2 (the box is off), then the new boot id.
boot_id_of() {
  local n; n=$(cat "$STATE/n"); echo $((n+1)) >"$STATE/n"
  if [ "$n" -lt 2 ]; then echo old
  elif [ "$n" -lt 4 ]; then echo ""
  else echo new
  fi
}
got="$(wait_for_reboot host 60 old)"
[ "$got" = new ] && ok "waits through the shutdown window and returns the new boot id" \
  || bad "returned '$got' — an answer with the old boot id must not end the wait"

echo 0 >"$STATE/n"
boot_id_of() { echo old; }
if wait_for_reboot host 6 old >/dev/null; then
  bad "a host that never changes boot id must time out, not be accepted"
else
  ok "a host that answers but never rebooted times out"
fi

boot_id_of() { echo ""; }
if wait_for_reboot host 6 old >/dev/null; then bad "an unreachable host must time out"; else ok "an unreachable host times out"; fi

echo "$pass passed, $fail failed"
[ "$fail" = 0 ]
