#!/bin/bash
#
# Utility script that watches for the exit of
# the Bpipe program (which runs the dna pipeline).
# When Bpipe exits, this script will shut down the
# machine as well.  Intended for use on a Google 
# Compute Engine instance (do not run on a general-
# purpose server).
# 
# NOTE: You should run this script with `sudo` if 
#       your account is non-admin; if you do not,
#       you won't be able to shut down the container
#       or the VM.

echo "Monitoring Bpipe..."

while true; do
	pidof -x bpipe >/dev/null
	if [[ $? -ne 0 ]] ; then
		COUNT=5
        echo "Bpipe finished.  Shutting down."
        echo
        while [[ $COUNT -ne 0 ]] ; do
            printf "\rShutdown in $COUNT seconds...           "
            sleep 1
            COUNT=$(($COUNT-1))
        done
        sudo docker stop $(docker ps -a -q) >/dev/null 2>&1
        sudo shutdown -h now
        exit 0
	fi
	sleep 30
done
