#!/usr/bin/bash
#
# Starts a take-down pass on a NODE_CRASH about this node: after a restart that
# no master saw, restore plumbed this node's VIPs before the master decided, and
# the master then moved them away. The pass waits for this node to leave
# Pending and takes down what shaman now lists elsewhere; it never plumbs.
# Run on every node by shaman's cluster-wide notify.
#
# Provided environment variables:
# - EVENT - name of the cluster-wide event
# - SRC_NODE_ID - id of the node the event is about
#

. /usr/share/shaman/functions

verify_caller

if [ -z "$EVENT" ]; then
	echo "EVENT environment variable undefined" 1>&2
	exit 1
fi

[ "$EVENT" = NODE_CRASH ] || exit 0
[ -n "$SRC_NODE_ID" ] || exit 0
read -r host_id 2>/dev/null < /etc/vstorage/host_id
[ "$SRC_NODE_ID" = "$host_id" ] || exit 0

/usr/bin/ostor-s3ep is-cluster-member --quiet
case $? in
0)	;;
3)	exit 0 ;;
*)	echo "Cannot check ostor cluster membership: starting the take-down pass anyway" 1>&2 ;;
esac

PASS_UNIT=ostor-s3ep-crash-pass.service

# One pass at a time: a unit of that name is loaded while it runs.
[ "$(/usr/bin/systemctl show -p LoadState --value $PASS_UNIT 2>/dev/null)" = loaded ] && exit 0

/usr/bin/systemd-run --no-block --collect --quiet --unit=$PASS_UNIT \
	--description="Cleanup of stale S3 endpoint VIPs after a crash of this node" \
	-p RuntimeMaxSec=5min \
	/usr/bin/ostor-s3ep endpoint restore --converge-only --wait-pending ||
	echo "Cannot start $PASS_UNIT: the take-down timer ends the copy" 1>&2
exit 0
