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

set -e

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package

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

update_check_firewall_state() {
  local PREVIOUS_STATE_INFO="/var/tmp/check_firewall_previous_state.info"
  local IPTABLES_STATE="/var/lib/nagios/check_ee_iptables/iptables.state"
  local IP6TABLES_STATE="/var/lib/nagios/check_ee_iptables/ip6tables.state"
  local CHECK_CMD_FILE="/etc/nagios/nrpe.d/firewall.cfg"
  local CHECK_RUNNING="NO"
  local CHECK_CMD CHECK_STATE

  if [ -f ${IPTABLES_STATE} -o -f ${IP6TABLES_STATE} ] ; then
    CHECK_RUNNING="YES"
  fi

  echo "CHECK_RUNNING:${CHECK_RUNNING}" > ${PREVIOUS_STATE_INFO}

  if [ "${CHECK_RUNNING}" = "YES" ] ; then
    # Get check command
    CHECK_CMD=$(cut -d "=" -f 2 ${CHECK_CMD_FILE})
    echo "CHECK_CMD:\"${CHECK_CMD}\"" >> ${PREVIOUS_STATE_INFO}
    # Get current state
    CHECK_STATE=$(${CHECK_CMD} | head -1 | cut -d ":" -f 1)
    echo "CHECK_STATE:${CHECK_STATE}" >> ${PREVIOUS_STATE_INFO}
  fi
}

case "$action" in
    install|upgrade)
        # 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)
    ;;

    *)
        echo "preinst 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
