#!/usr/bin/env bash


if [ "$HOSTNAME" = "iver28" ] || [ "$HOSTNAME" = "iver31" ]; then
    local=1
else
    local=0
fi

TIMEOUT=45
if [ $local = 1 ]; then
    sudo sleep 0 # force a valid sudo test
    wafer-shutdown $HOSTNAME
    ret=$?
    if [ $ret -eq 0 ] || [ $ret -eq 1 ]; then
        echo "shutting down stack"
        echo ">>>wait $TIMEOUT seconds before killing power<<<"
        sudo shutdown -H now
        exit $ret
    else
        echo "aborting"
        exit -1
    fi
else
    ssh -f root@$1 "iver-shutdown"
    if [ $? -eq 0 ]; then
        for ((i=1; i<=$TIMEOUT; i++)); do
            echo -ne "."
            let mod=$i%10
            if [ $i -gt 0 ] && [ $mod -eq 0 ]; then
                echo -ne "\b$i"
            fi
            sleep 1;
        done
        echo ""
        echo "safe to power down"
    else
        echo "usage: iver-shutdown host"
        echo "where host = iver28, iver28-wifi, iver31, or iver31-wifi"
    fi
fi
