#!/usr/bin/sh

# Hooks parameter are passed by environment variable:
#
# - RUDDER_GENERATION_DATETIME       : generation datetime: ISO-8601 YYYY-MM-ddTHH:mm:ss.sssZ date/time that identify that policy generation.
# - RUDDER_END_GENERATION_DATETIME   : generation end time: ISO-8601 YYYY-MM-ddTHH:mm:ss.sssZ date/time when the generation ended (minus these hooks)
# - RUDDER_NODE_IDS_PATH             : path to a sourceable file with variable RUDDER_NODE_IDS containing a bash array of node id updated
#                                      during the process, or the empty array if no nodes were updated.
# - RUDDER_NUMBER_NODES_UPDATED      : integer >= 0; number of nodes updated (could be found by counting $RUDDER_NODE_IDS)
# - RUDDER_ROOT_POLICY_SERVER_UPDATED: 0 if root was updated, anything else if not

# Signal to cf-serverd that it shall look-up the new promises, and apache to update its kown certs.

export PATH="/opt/rudder/bin:$PATH"

# For Windows agents
CERT_CUR="/var/rudder/lib/ssl/nodescerts.pem"
CERT_NEW="/var/rudder/cfengine-community/inputs/rudder-service-apache/1.0/apache/nodescerts.pem"
if ! cmp --silent -- "${CERT_CUR}" "${CERT_NEW}"; then
  # When no Windows nodes are present, file is empty and breaks apache
  if [ -s "${CERT_NEW}" ]; then
    cp "${CERT_NEW}" "${CERT_CUR}"
    if command -v apache2 >/dev/null 2>&1; then
      systemctl reload-or-restart apache2.service
    else
      systemctl reload-or-restart httpd.service
    fi
  fi
fi

# for Linux agents
ACL_BACK="/var/rudder/tmp/cf-serverd.sha256"
ACL_FILE="/var/rudder/cfengine-community/inputs/common/1.0/cf-serverd.cf"
ACL_HASH=$(openssl sha256 -r "${ACL_FILE}" | cut -d' ' -f 1)
if [ -f "${ACL_BACK}" ]; then
  if [ "${ACL_HASH}" = "$(cat "${ACL_BACK}")" ]; then
    exit 0
  fi
fi
echo "${ACL_HASH}" > "${ACL_BACK}"
systemctl reload-or-restart rudder-cf-serverd
