#!/bin/sh
# postinst script for pkg-arch
#
# see: dh_installdeb(1)

set -e

action="$1"
oldversion="$2"

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package

update_check_firewall_state() {

  local PREVIOUS_STATE_INFO="/var/tmp/check_firewall_previous_state.info"
  local CHECK_CMD_FILE="/etc/nagios/nrpe.d/firewall.cfg"
  local CHECK_RUNNING="NO"
  local CHECK_STATE INIT_CMD

  echo "Test if firewall check was running"
  if grep -sq '^CHECK_RUNNING:YES$' ${PREVIOUS_STATE_INFO} ; then
    echo "  Yes, get previous firewall check state"
    CHECK_STATE=$(grep '^CHECK_STATE:.*' ${PREVIOUS_STATE_INFO} | cut -d ":" -f 2 )
    if [ "${CHECK_STATE}" = "OK" ] ; then
      echo "  Previous state was OK, we'll re-init check on all tables"
      # Get check cmd and re-init with its options
      INIT_CMD=$(cat ${CHECK_CMD_FILE} | cut -d "=" -f 2 |  sed -E 's/[-]a/-i/')
      # Running re-init
      ${INIT_CMD}
    else
      # Error, nothing to do.
      echo "  Previous state was ${CHECK_STATE}, we'll not reinit check"
    fi
  else
    echo "  No, nothing to do"
  fi

  rm -f ${PREVIOUS_STATE_INFO}
}

case "$action" in
    configure)
        if pidof /usr/sbin/nrpe >/dev/null 2>&1
        then
            invoke-rc.d nagios-nrpe-server restart || true
        fi
        usermod -a -G systemd-journal nagios

        # init firewall check, all tables checked since version 1.12.2~ee100+2
        # if $oldversion not defined, new install, nothing to do.
        if dpkg --compare-versions "$oldversion" lt-nl "1.12.2~ee100+2" ; then
          update_check_firewall_state
        fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
