#!/bin/sh
# -*- sh -*-

mktempfile () {
    #cmd=`echo $MUNIN_MKTEMP | sed s/\\$1/$1/`
    #$cmd
    touch /tmp/$1
    echo /tmp/$1
}

FREERADIUS_LOG=${freeradiuslog:-/var/log/wifi/global.log}
LOGTAIL=${logtail:-/usr/sbin/logtail}
MUNIN_PLUGSTATE=${MUNIN_PLUGSTATE:-/var/lib/munin/plugin-state/}
STATEFILE=$MUNIN_PLUGSTATE/wifi_auth.offset

if [ "$1" = "autoconf" ]; then
        if [ -f "${FREERADIUS_LOG}" -a -n "${LOGTAIL}" -a -x "${LOGTAIL}" ] ; then
		echo yes
		exit 0
	else
		echo no
		exit 0
	fi
fi

# Try tailing a random file to check how arguments are passed
ARGS=0
`$LOGTAIL /etc/hosts 2>/dev/null >/dev/null`
if [ $? = 66 ]; then
    if [ ! -n "$logtail" ]; then
	ARGS=1
    fi
fi

if [ "$1" = "config" ]; then
	echo 'graph_title Authentifications WiFi'
	echo 'graph_vlabel Auth'
	echo 'graph_category wifi'
    echo 'failures.label Échecs'
    echo 'failures.draw AREASTACK'
    echo 'failures.colour FF0000'
    echo 'success.label Succès'
    echo 'success.draw AREASTACK'
    echo 'success.colour 00FF00'
    echo 'peap.label Authentifications PEAP'
    echo 'ttls.label Authentifications TTLS'
    echo 'peap.draw LINE1'
    echo 'peap.colour 000000'
    echo 'ttls.draw LINE2'
    echo 'ttls.colour F6FF00'
	exit 0
fi

success=U
failures=U

TEMP_FILE=$(mktempfile munin-radius-wifi.XXXXXX)

if [ -n "$TEMP_FILE" -a -f "$TEMP_FILE" ]
then
	if [ $ARGS != 0 ]; then
	    $LOGTAIL -f ${FREERADIUS_LOG} -o ${STATEFILE} > ${TEMP_FILE}
	else
	    $LOGTAIL ${FREERADIUS_LOG} ${STATEFILE} > ${TEMP_FILE}
	fi
    success=$(grep -c 'Login OK' ${TEMP_FILE})
    failures=$(grep -c 'Login incorrect' ${TEMP_FILE})
    peap=$(grep -c 'authenticated - EAP type: 25' ${TEMP_FILE})
    ttls=$(grep -c 'authenticated - EAP type: 21' ${TEMP_FILE})

	/bin/rm -f $TEMP_FILE
fi

echo "success.value ${success}"
echo "failures.value ${failures}"
# NB: chaque authentification réussie en TTLS ou PEAP produit deux "succès"
# (inner et outer-tunnels)
echo "peap.value ${peap}"
echo "ttls.value ${ttls}"


