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

echo "QUESTION: Are you sure you want to set all desired service stati to 'ignored' (but keep HA services up)?"
echo "If you want to stop all 3 HA services too call pu-ha-stop instead."
echo "Press Ctrl-C to abort or Enter to continue setting stati to 'ignored' ..."
read ENTER

echo ""

if [ -f "/etc/pve/ha/pve-utils_ha-service-stati.txt" ] ; then
  echo "INFO: Already have /etc/pve/ha/pve-utils_ha-service-stati.txt, not re-creating it."
  echo "This is expected after calling pu-ha-stop on one PVE cluster node." 
  echo ""
else
  echo "INFO: Detecting states of HA guests ..."
  ha-manager status |egrep "^service" |awk '{print $2 " " $4}' |tr -d ')' |tee /etc/pve/ha/pve-utils_ha-service-stati.txt
  echo ""
  echo "INFO: Setting wanted HA service stati to 'ignored' ..."
  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: Service ${HA_SERVICE_STATE} ..."
    ha-manager set ${HA_SERVICE} --state ignored || exit 11 
  done
  echo "INFO: Done setting wanted HA service stati to 'ignored', waiting for it to be applied ..."
  echo ""
  sleep 5
fi

echo "INFO: Waiting for all HA service stati to becom 'ignored' ..."
UNIGNORED_SERVICES=$(ha-manager status |egrep "^service" |grep -v ", ignored")
while [ -n "${UNIGNORED_SERVICES}" ]
do
  echo "WARNING: The following services are not in state 'ignored' yet:"
  echo "${UNIGNORED_SERVICES}"
  echo ""
  echo "Trying again in a bit ..."
  echo ""
  sleep 5
done
echo ""

echo "GOOD: All HA service are in state set to 'ignored'."
echo ""

exit 0
