#!/bin/sh
# Monitor VPN status and call /etc/daemon.d/vpn-up.d/* on VPN up

# Files and Directories
GUEST_DAEMON_VPN_UP_D="/etc/daemon.d/vpn-up.d"
HOST_DAEMON_VPN_UP_D="${MEDIACASTER_DIR}${GUEST_DAEMON_VPN_UP_D}"

GUEST_DAEMON_VPN_DOWN_D="/etc/daemon.d/vpn-down.d"
HOST_DAEMON_VPN_DOWN_D="${MEDIACASTER_DIR}${GUEST_DAEMON_VPN_DOWN_D}"

GUEST_OE_ADMIN_CONF="/etc/oe-admin.conf"
HOST_OE_ADMIN_CONF="${MEDIACASTER_DIR}${GUEST_OE_ADMIN_CONF}"

GUEST_VPN_DOWN_STAMP="/tmpHost/vpn-down.stamp"
HOST_VPN_DOWN_STAMP="${MEDIACASTER_DIR}${GUEST_VPN_DOWN_STAMP}"

VPN_DOWN=1
VPN_UP=0
VPN_STATE=${VPN_DOWN}
VPN_STATE_OLD=${VPN_DOWN}

daemon_vpn_get_tun_iface () {
        grep "^TUNInterface " ${HOST_OE_ADMIN_CONF} \
                | sed "s/^TUNInterface \(.*\)/\1/g"
}

# Return 0 if the VPN is up, 1 if it is down
daemon_vpn_check_connectivity () {
        local TUNInterface=`daemon_vpn_get_tun_iface`
        VPN_STATE_OLD=${VPN_STATE}
        VPN_STATE=${VPN_DOWN}

        if [ -f "${HOST_VPN_DOWN_STAMP}" ]; then
                # OpenVPN down.sh script will create ${HOST_VPN_DOWN_STAMP} when it goes down
                rm -f ${HOST_VPN_DOWN_STAMP}
        elif [ "${TUNInterface}" != "" ]; then
                # OpenVPN up.sh script will add "TUNInterface"
                ifconfig ${TUNInterface} > /dev/null 2>&1
                if [ "$?" == "0" ]; then
                        VPN_STATE=${VPN_UP}
                fi
        fi
        return ${VPN_STATE}
}

daemon_vpn_compare_state () {
        # Return 0 if the VPN state has not changed, 1 if it has
        daemon_vpn_check_connectivity

#        if [ "$VPN_STATE" == "$VPN_DOWN" ]; then
#                daemon_log_debug "VPN state is down."
#        else
#                daemon_log_debug "VPN state is up."
#        fi

        [ "$VPN_STATE_OLD" == "$VPN_STATE" ] && return 0
        return 1
}

daemon_vpn_state_changed () {
	if [ "$VPN_STATE" == "$VPN_DOWN" ]; then
		daemon_vpn_down
	else
		daemon_vpn_up
	fi

	return $?
}

daemon_vpn_up () {
	local SCRIPT_DIR

	SCRIPT_DIR="${HOST_DAEMON_VPN_UP_D}"
	daemon_log_info "Running daemon vpn-up scripts"

	# Run target-specific HOST_DAEMON_VPN_UP_D/* parts
	if [ "`ls -A ${SCRIPT_DIR}/* 2>/dev/null`" != "" ]; then
			for each in ${SCRIPT_DIR}/*; do
					daemon_log_info "Running $each"
					sh ${each}
			done
	fi

	return 0
}

daemon_vpn_down () {
	local SCRIPT_DIR
	SCRIPT_DIR="${HOST_DAEMON_VPN_DOWN_D}"
	daemon_log_info "Running daemon vpn-down scripts"

	# Run target-specific HOST_DAEMON_VPN_DOWN_D/* parts
	if [ "`ls -A ${SCRIPT_DIR}/* 2>/dev/null`" != "" ]; then
			for each in ${SCRIPT_DIR}/*; do
					daemon_log_info "Running $each"
					sh ${each}
			done
	fi

	return 0
}
