#!/bin/bash
# Copyleft ITEG IT-Engineers GmbH 2024

echo "INFO: Enabling pve-ha-lrm.service, pve-ha-crm.service and watchdog-mux.service ..."
systemctl enable pve-ha-lrm.service pve-ha-crm.service watchdog-mux.service
sleep 3
echo ""
echo "INFO: Starting pve-ha-lrm.service ..."
systemctl start pve-ha-lrm.service
sleep 3
echo ""
echo "INFO: Starting pve-ha-crm.service ..."
systemctl start pve-ha-crm.service
sleep 3
echo ""
echo "INFO: Starting watchdog-mux ..."
systemctl start watchdog-mux.service
sleep 3
echo ""

echo "INFO: Checking wether any of these services is still in-active and aborting if so ..." 
echo -n "pve-ha-lrm.service: "
systemctl is-active pve-ha-lrm.service || exit 11
echo -n "pve-ha-crm.service: "
systemctl is-active pve-ha-crm.service || exit 12
echo -n "watchdog-mux:       "
systemctl is-active watchdog-mux || exit 13
echo ""

if [ -f "/etc/pve/ha/pve-utils_ha-service-stati.txt" ] ; then
  echo "INFO: Restoring wanted HA service stati ..."
  cat /etc/pve/ha/pve-utils_ha-service-stati.txt |while read HA_SERVICE_STATE
  do
    HA_SERVICE=$(echo "${HA_SERVICE_STATE}" |cut -f1 -d ' ')
    HA_STATE=$(echo "${HA_SERVICE_STATE}" |cut -f2 -d ' ')
    echo "INFO: Setting service ${HA_SERVICE} to state ${HA_STATE} ..."
    ha-manager set ${HA_SERVICE} --state ${HA_STATE} || exit 11 
  done
  echo ""
  echo "Moving away /etc/pve/ha/pve-utils_ha-service-stati.txt ..."
  mv -v /etc/pve/ha/pve-utils_ha-service-stati.txt /etc/pve/ha/pve-utils_ha-service-stati.txt.bak
  echo ""
  echo "GOOD: Done restoring wanted HA service stati, but not waiting for distribution."
  echo "Current service stati are:"
  ha-manager status |egrep "^service"
  echo ""
  echo 'To re-check the state distribution call   ha-manager status |egrep "^service"'
  echo ""
else
  echo "INFO: Don't have /etc/pve/ha/pve-utils_ha-service-stati.txt, not trying to restore HA service states."
  echo "This is expected after calling pu-ha-start on one PVE cluster node." 
  echo ""
  echo "Current service stati are:"
  ha-manager status |egrep "^service"
  echo ""
fi

echo "GOOD: All HA service started and all wanted stati set back to previous states, mostly 'started'."
echo ""

exit 0
