#!/bin/bash

set -euf -o pipefail

# Reboot script for tcwg-qc-*.tcwglab machines.
# See https://linaro.atlassian.net/browse/STG-3331 for background.
#
# !!! This script should be installed on BARE machine under
#     /usr/local/sbin/reboot -- this location is searched by PATH first.

qbootctl=/root/qbootctl/build/qbootctl
try=0

while true; do
    try=$(($try + 1))
    echo "Try #$try"

    qbootctl_ok=true

    for cmd in "-n a" "-n b" "-m a" "-n a" "-m b" "-n b"; do
	if $qbootctl $cmd 2>&1 | grep Failed; then
	    qbootctl_ok=false
	    break
	fi
    done

    if $qbootctl_ok; then
	break
    fi

    # Loop until we complete the whole reboot sequence.
done

echo "SUCCESS: Rebooting"
/usr/sbin/reboot
