#!/bin/bash
#
# This script allows consul to be disable by creating a file in /etc/consul.
# The filename is either consul_disable or deploy_disable.
# The name of the script is used to determine what action is being requested.
# It is sym-linked to 6 names:
# consul-disable, consul-enable, consul-status
# deploy-disable, deploy-enable, deploy-status
#

set -e -o pipefail

DATA_DIR=/etc/consul

function fail() {
	echo "Failure: $1"
	# this will cause the consul to mark the check as "warning"
	exit 1
}

BASENAME=${0##*/}

case $BASENAME in
	consul-*)
		THING=consul
		;;
	deploy-*)
		THING=deploy
		;;
	*)
		fail "unknown script prefix, can't figure out the type of check"
		;;
esac

STATUS_FILE="${DATA_DIR}/${THING}_disabled"

case $BASENAME in
	*-enable)
		if [[ -f $STATUS_FILE ]]; then
			rm -f $STATUS_FILE
			echo "$STATUS_FILE has been removed. $THING is now enabled."
		else
			echo "$THING is already enabled. Doing nothing."
		fi
		exit 0
		;;
	*-disable)
		REASON=${@:-No reason specified}
		if [[ -f $STATUS_FILE ]]; then
			echo "$THING is disabled already. Updating the reason."
		fi
		echo "$REASON" > "$STATUS_FILE"
		echo "$STATUS_FILE has been created. $THING is now disabled."
		;;
	*-status)
		if [[ -f $STATUS_FILE ]]; then
			echo "$THING is disabled. Reason:"
			cat "$STATUS_FILE"
			# consul will interpret this as an error
			exit 2
		else
			echo "$THING enabled."
		fi
		exit 0
		;;
	*)
		fail "unknown script suffix, can't figure out the type of query"
		;;
esac
