#!/bin/bash

if [[ "$(id -u)" != "0" ]]; then
	echo "This script must be run as root" >&2
	exit 6
fi

MAINDIR="$(cd "$(dirname "$0")/.." || exit 64 ; pwd -P)"
ERIGONES_HOME="${ERIGONES_HOME:-"${MAINDIR}"}"
ESLIB="${ESLIB:-"${ERIGONES_HOME}/bin/eslib"}"

# shellcheck disable=SC1090
. "${ESLIB}/functions.sh"

function pcs_resource_action() {
	local action="$1"
	local resname="$2"
	local nodename="$(ha_get_my_nodename)"

	if [[ "${action}" == "status" ]]; then
		crm_resource -Wr "${resname}"
	elif crm_resource -Wr "${resname}" | grep -q "running on: ${nodename}"; then
		# touch only if the resource is running on this node
		pcs resource "${action}" "${resname}" --wait=20 > /dev/null
	else
		echo "Ignoring ${resname} on ${nodename} (not running locally)"
	fi
}

systemd_pretty_status() {
	local svcname="$1"
	echo "${svcname} is $(get_svc_prop "${svcname}" SubState)"
}

function node_status() {
	svcs svc:/application/erigonesd:*
}

function node_restart() {
	svcadm restart svc:/application/erigonesd:*
}

function node_start() {
	svcadm enable svc:/application/erigonesd:*
}

function node_stop() {
	svcadm disable -t svc:/application/erigonesd:*
}

function node_disable() {
	svcadm disable svc:/application/erigonesd:*
}

function mgmt_status() {
	if ha_is_active; then
		pcs_resource_action status postgres-ha
		pcs_resource_action status erigonesd-beat
	else
		systemd_pretty_status erigonesd-beat
	fi
	systemd_pretty_status erigonesd
	systemd_pretty_status esdc@gunicorn-api.service
	systemd_pretty_status esdc@gunicorn-gui.service
	systemd_pretty_status esdc@gunicorn-sio.service
}

function mgmt_restart() {
	if ha_is_active; then
		pcs_resource_action restart erigonesd-beat
	else
		systemctl restart erigonesd-beat
	fi
	systemctl restart esdc@{gunicorn-api.service,gunicorn-gui.service,gunicorn-sio.service} erigonesd
}

function mgmt_stop() {
	if ha_is_active; then
		pcs_resource_action disable erigonesd-beat
		systemctl stop esdc@* erigonesd
	else
		systemctl stop esdc@* erigonesd erigonesd-beat
	fi
}

function mgmt_disable() {
	if ha_is_active; then
		pcs_resource_action disable erigonesd-beat
		systemctl disable esdc@* erigonesd
	else
		systemctl disable esdc@* erigonesd erigonesd-beat
	fi
}

function is_node() {
	[[ "$(uname -s)" == "SunOS" ]] && \
	[[ -f /usr/bin/zonename ]] && \
	[[ "$(/usr/bin/zonename)" == "global" ]]
}

case "$1" in
	"status")
		if is_node; then
			node_status
		else
			mgmt_status
		fi
	;;
	"restart")
		if is_node; then
			node_restart
		else
			mgmt_restart
		fi
	;;
	"start")
		if is_node; then
			node_start
		else
			mgmt_restart
		fi
	;;
	"stop")
		if is_node; then
			node_stop
		else
			mgmt_stop
		fi
	;;
	*)
		echo "Usage: $0 {status|start|stop|restart}" >&2
		exit 1
	;;
esac
