#!/bin/bash

# simple plugin to check ipsec status
# supports strong/openswan
# made by Dju, 05/2015
# version 1.4 / 09.2015

PROGNAME=`basename $0`
PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`

. $PROGPATH/utils.sh

IPSEC_BIN=/usr/sbin/ipsec

if [ ! -x $IPSEC_BIN ]; then
  echo "UNKNOWN: ipsec bin not executable"
  exit $STATE_UNKNOWN
fi

SUDO=""
MYID=$(id -u)
if [ "$MYID" != "0" ]; then SUDO=sudo; fi

STRONG=$($SUDO $IPSEC_BIN version | egrep -c strongSwan)

if [ $STRONG -eq 1 ]; then
  status=$($SUDO $IPSEC_BIN statusall)
  TUNNELS=$(echo "$status" | awk 'BEGIN {conn=0} /Security Associations/ {conn=0} /[a-zA-Z0-9\-\_]*:\s*local:/ { if(conn==1){print $1} } /Connections:/ {conn=1}' | sed 's/://' | sort | uniq)
else
  status=$($SUDO $IPSEC_BIN whack --status)
  TUNNELS=$(echo "$status" | awk '/000 "[^"]/ {print $2}' | sed -e 's/[":]//g' | sort | uniq)
fi
nb_ok=0
nb_down=0

for tunnel in $TUNNELS; do
  if [ $STRONG -eq 1 ]; then
    installed=$(echo "$status" | egrep "${tunnel}\{[0-9]*\}:\s*(INSTALLED, |IPsec SA established)")
  else
    installed=$(echo "$status" | egrep "${tunnel}.*IPsec SA established.*newest IPSEC")
  fi
  if [ -n "$installed" ]; then
    nb_ok=$( expr $nb_ok + 1)
  else
    nb_down=$(expr $nb_down + 1)
    [ -z "$tunnels_down" ] && tunnels_down=$tunnel || tunnels_down="${tunnels_down},$tunnel"
  fi
done

if [ $nb_down -gt 0 ]; then
  STATUS=CRITICAL
  tunnels_down=" ($tunnels_down)"
else
  STATUS=OK
fi

echo -n "${STATUS}: ${nb_ok} tunnel(s) up, ${nb_down} down${tunnels_down}"
echo " | nb_ok=$nb_ok nb_down=$nb_down"
st="STATE_${STATUS}"
exit ${!st}
