#!/usr/bin/bash
# Retrieve eapol secret from RADIUS clients conf
RADSECRET=$(
cat /etc/raddb/clients.conf | perl -MData::Dumper -MJSON -ne '
    BEGIN {
        my $CONF={};
        my @PATH=($CONF);
    }
    if (m/^\s*([^#]+?)\s+{\s*$/) {
        $_ = $1;
        s/(^\s+|\s+$)//g;
        s/\s\s+/ /g;
        $CONF->{$_} = {};
        push(@PATH, $CONF->{$_});
    } elsif (m/^\s*\}\s*$/) {
        pop(@PATH);
    } elsif (m/^\s*([^#\s]+)\s*=\s*([^\s]+)/) {
        $PATH[$#PATH]->{$1} = $2;
    }
    END {
        print to_json($CONF, { utf8=>1, pretty=>1 });
    }
' | jq -r '."client localhost".secret')

# If we didn't get a secret this won't work, so just set the expiry to today which will trigger zabbix to alert
[[ -z $RADSECRET ]] && echo $(date +%s) && exit 1

# We need this file
! [[ -r /etc/raddb/peap-mschapv2.conf ]] && echo $(date +%s) && exit 1
eapol_test -s "$RADSECRET" -c /etc/raddb/peap-mschapv2.conf -o/dev/stdout | sed -nre '/BEGIN CERTIFICATE/,/END CERTIFICATE/p' -e '/-----END CERTIFICATE-----/q' | openssl x509 -noout -dates \
              | perl -MDate::Parse -ne '
                s/^.*?= *//g; push(@ts, str2time($_));
                END {
                    my $now=time();
                    printf("%s\n", (($now < $ts[0] || $now > $ts[1]) ? 0 : ($ts[1] - $now)))
                }
              '

