#!/bin/bash
# Copyright (c) 2008,2009,2010 Citrix Systems, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only. with the special
# exception on linking described in file LICENSE.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
. /etc/init.d/functions

FILENAME=`basename $0`
LOCKFILE='/dev/shm/xe_toolstack_restart.lock'

(
flock -x -n 200
if [ "$?" != 0 ]; then
	echo "Exiting: cannot lock $LOCKFILE. Is an instance of $0 running already?"
	exit 1
fi

echo "Executing $FILENAME"

POOLCONF=`cat /etc/xensource/pool.conf`
if [ $POOLCONF == "master" ]; then MPATHALERT="mpathalert"; else MPATHALERT=""; fi

tmp_file=$(mktemp --suffix="xe-toolstack-restart")
systemctl stop stunnel@xapi > $tmp_file 2>&1
kill_stunnel_exit_code=$?
if [[ $kill_stunnel_exit_code != 0 ]]; then
  printf "\nFailed to kill stunnel processes! Output:\n"
  cat $tmp_file
  printf "\n"
fi
rm -f $tmp_file

set -e

systemctl restart $MPATHALERT toolstack.target

# Check the status of toolstack services
for service in $(systemctl list-dependencies --plain --no-pager toolstack.target) $MPATHALERT; do

  # Skip check if the service is not enabled
  systemctl is-enabled "$service" >/dev/null 2>&1 || continue

  # During system bootup, xcp-rrdd-dcmi.service often fail as
  # `ipmitool dcmi discover` discover nothing, just ignore it for now
  if [ "$service" == "xcp-rrdd-dcmi.service" ]; then
     continue
  fi

  if ! systemctl is-active --quiet "$service"; then
     echo "$service failed to restart, $(systemctl status $service)"
     exit 1
  fi
done

rm -f $LOCKFILE
echo "done."
)200>$LOCKFILE

exit $?
