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

: << =cut

=head1 NAME

openvpn_as_time -Indicate user logged time.

=head1 CONFIGURATION

Require jsonpipe software:
https://github.com/dvxhouse/jsonpipe

[openvpn_*]
user root

=head1 AUTHOR

Ricardo Fraile <rfrail3@yahoo.es>

=head1 LICENSE

GPLv2

=head1 MAGICK MARKERS

 #%# family=auto
 #%# capabilities=autoconf

=cut

. $MUNIN_LIBDIR/plugins/plugin.sh




if [ "$1" = "autoconf" ]; then
	echo yes 
	exit 0
fi

SUM=0
COUNT=1
NOW=`date +%s`
# Script folder
D_BIN="/usr/local/openvpn_as/scripts"

# List with users time
LIST1=`$D_BIN/sacli VPNStatus | tr '/' - |  jsonpipe  | grep "/openvpn_[0-9]/client_list/[0-9]/6" | tr -d '"'  | awk '{print $2} '`
# List with users names
LIST2=`$D_BIN/sacli VPNStatus | tr '/' - |  jsonpipe  | grep "/openvpn_[0-9]/client_list/[0-9]/0" | tr -d '"'  | awk '{print $2} '`

if [ "$1" = "config" ]; then

	echo 'graph_title OpenVPN User logged time'
	echo 'graph_args --base 1000 -l 0 '
	echo 'graph_vlabel Time in minutes'
	echo 'graph_scale no'
	echo 'graph_category network'
	echo 'graph_info Indicate the user logged time.'

	# If none, print 0
	if [ -z $LIST1 ]; then
        	LIST1=$NOW
		LIST2="none"
	fi

	for i in $LIST1; do
		NAME=`echo $LIST2 | cut -d " " -f $COUNT`
        	echo "$NAME.label User $NAME"
	        echo "$NAME.type GAUGE"
        	echo "$NAME.min 0"
		COUNT=$((COUNT + 1))
	done
	
	exit 0
fi

# If none, print 0
if [ -z $LIST1 ]; then
        LIST1=$NOW
	LIST2="none"
fi

# Print values
for i in $LIST1; do
	NAME=`echo $LIST2 | cut -d " " -f $COUNT`
	echo "$NAME.value $(($((NOW - $i)) / 60))"
	COUNT=$((COUNT + 1))
done
