#!/bin/bash

# The first time this script gets called IS_FLOCKED_BY_FIREWALL_RELOAD is not
# set, so we set it and call flock to acquire the lock and recursively call
# this script. In the recursive call we can be assured the lock is held, so we
# simply invoke the python code to reload the firewall.

# 30min timeout trying to aquire the lock
FLOCK_TIMEOUT_SEC=1800
SCRIPT=$(readlink -f "${0}")

# Check if the lock is held by a parent process.
# If the lock is held by a parent process don't call flock again to avoid deadlock/infinite recursion
if [ "${IS_FLOCKED_BY_FIREWALL_RELOAD}" = "Yes" ]; then
   unset IS_FLOCKED_BY_FIREWALL_RELOAD

   SCRIPTDIR=$(dirname "${SCRIPT}")
   PARENTDIR=$(dirname "${SCRIPTDIR}")
   BASEDIR=$(dirname "${PARENTDIR}")

   if [ -z "$VHERDRUNNER" ]; then
      VHERDRUNNER=${BASEDIR}/base/bin/vherdrunner
   fi

   exec ${VHERDRUNNER} ${PARENTDIR}/bin/firewall-reload.py
else
   export IS_FLOCKED_BY_FIREWALL_RELOAD="Yes"
   flock -o -w "${FLOCK_TIMEOUT_SEC}" /var/tmp/vmware-firewall-reload.flock "${SCRIPT}"
fi
