#!/bin/bash

USAGE="USAGE = reset-fpga # PASSWORD [-force]  Where '#' is 1 or 2 for node 1001 or 1002 respectfully."


if [[ $# -gt 3 || $# -lt 2 ]]; then 
   echo "$USAGE"
   exit
fi

PASS=$2
host="sert-100$1"

if [[ "$3" = "-force" ]]; then
echo Forcing reboot
else

users=$(squeue -w $host -o %u -h)

IFS=' ' read -ra user <<< $users

for i in ${user[@]}; 
do
   if [[ "$i" != "$USER" ]]; then 
       echo "You aren't unique user of the device!"
       echo "currently this users must been notified:"
       echo $users
       echo do you want to continue?
       read force
       if [[ $force == yes ]]; then
	   break
       elif [[ $force == no ]]; then
           exit
       else
           echo Wrong input, exiting...
	   exit
       fi
   fi
done
fi

ipmitool -P $PASS -U $USER -H $host-ipmi power soft
echo "Setting the machine OFF"

stat=$(ipmitool -P $PASS -U $USER -H $host-ipmi power status)
echo $stat
while true;
do 
   if grep -q off <<< $stat; then 
       break 
   fi 
   sleep 2
   echo -n "."
   stat=$(ipmitool -P $PASS -U $USER -H $host-ipmi power status)
done

echo "Machine is OFF"
echo "Restarting the machine"
stat=$(ipmitool -P $PASS -U $USER -H $host-ipmi power on)

#while ! ping -c1 $host &>/dev/null; do : echo -n "."; sleep 2; done

while ! ping -c 1 $host &>/dev/null; 
do
   echo -n "."
   sleep 2
done

echo "Machine is ON Now!"
