#!/bin/bash

# First check if we deal with a heartbeat aware openvpn setup
if [ -f "/etc/ha.d/haresources" ] && \
   [ $(cat /etc/ha.d/haresources | grep -c "openvpn") -gt 0 ] && \
   [ -x "/usr/sbin/fliwi-simple-heartbeat-info" ] && \
   [ `/usr/sbin/fliwi-simple-heartbeat-info | grep -c -F "PASSIV/"` -eq 1 ]; then
  echo "I am a hot-standby server"
  exit 0
fi

exit_code=0

/usr/sbin/service openvpn status 2>&1 || exit_code=2
if [ $exit_code -ne 0 ]; then
  exit $exit_code
fi

exit $exit_code
## The logic below is disabled for now, since it delivers false alerts
for file in $(find /var/run/openvpn.*status -mindepth 0 -maxdepth 0 -type f)
do
  vpn_name=$(basename $file)
  auth_bytes=$(grep -F 'Auth read bytes,' $file | cut -d ',' -f 2 | sed -r 's/[^0-9]//g')
  if [ -z "$auth_bytes" ]; then
    echo "E: Can not get auth read bytes for vpn '$vpn_name'"
    exit_code=2
  elif [ "$auth_bytes" = "0" ]; then
    echo "E: VPN '$vpn_name' seems to be offline"
    exit_code=2
  fi
done

exit $exit_code
