#!/bin/bash

SUSPEND_FLAG=/var/run/shaman.suspend
LOG_PATH=/var/log/shaman/suspend-resume.log

get_node_state() {
	local host_id="$(cat /etc/vstorage/host_id)"
	local tmp=$(shaman stat -j 2>/dev/null | jq -c ".status.nodes[\"$host_id\"].status")
	[ $? -ne 0 ] && return
	# strip double quotes
	tmp="${tmp%\"}"
	tmp="${tmp#\"}"
	echo $tmp
}

log() {
	echo -e "$(date): $*" >> $LOG_PATH
}

case "$1" in
start)
	if [ ! -f "$SUSPEND_FLAG" ]; then
		log "don't resume since suspend flag is missing"
		exit 0
	fi

	if [ "$(get_node_state)" == "Suspended" ]; then
		log "resume"
		# remove suspend flag on both success and failure
		rm -f "$SUSPEND_FLAG"
		/usr/sbin/shaman resume 2>/dev/null
	fi
	# always return zero
	exit 0
	;;
stop)
	/usr/bin/systemctl list-jobs 2>/dev/null | grep -q '\sshutdown.target\s*start'
	if [ $? -eq 0 ]; then
		log "don't suspend on shutdown"
		exit 0
	fi
	
	if [ "$(get_node_state)" == "Active" ]; then
		log "suspend"
		/usr/sbin/shaman suspend 2>/dev/null
		[ $? -eq 0 ] && touch "$SUSPEND_FLAG"
	else
		log "not suspending since node is not in active state"
	fi
	# always return zero
	exit 0
	;;
*)
	echo "usage: $0 start|stop"
	exit 1
	;;
esac
