#!/bin/bash
verbose=0
set -e
KEYFILE="/var/lib/nagios/.ssh/inmon"

while getopts "i:H:u:t:a;" opt; do
    case $opt in
        i ) KEYFILE="$OPTARG"
            ;;
        H ) HSTNAME="$OPTARG"
            ;;
        u ) USRNAME="$OPTARG"
            ;;
        t ) firewallType="$OPTARG"
            ;;
	a ) HSTADDR="$OPTARG"
	    ;;
    esac
done

fwTypes="opnsense|pfsense"

if ! [[ $HSTNAME ]] ; then
    echo "Please provide a hostname with the -H flag."
    exit 3
fi
if ! [[ $USRNAME ]] ; then
    echo "Please provide a username with the -u flag."
    exit 3
fi
if ! [[ $KEYFILE ]] ; then
    echo "Please provide a keyfile location with the -i flag."
    exit 3
fi
if ! [[ $firewallType ]] ; then
    echo "Firewall type must be specified with -t [$fwTypes]"
    exit 3
fi
if ! [[ $(echo $fwTypes | grep $firewallType) ]] ; then
    echo "Firewall type must be of type $fwTypes."
    exit 3
fi

if [[ $firewallType -eq "opnsense" ]] ; then
    dir="/tmp"
elif [[ $firewallType -eq "pfsense" ]] ; then
    dir="/var/run"
else
    echo "SOMETHING WRONG"
fi

if [ -z ${var+x} ] ; then
    HSTFINAL=$HSTNAME
else
    HSTFINAL=$HSTADDR
fi

dirList=$(ssh -i $KEYFILE -o StrictHostKeyChecking=accept-new -o UpdateHostKeys=no $USRNAME@$HSTFINAL ls $dir)

if $(echo $dirList | grep -q dirty) ; then
    for each in $dirList ; do
        if $(echo $each | grep -q dirty) ; then
            result="$result, $(echo $each | sed 's/.dirty//g')"
        fi
    done
    echo "CRITICAL - Changes need to be applied in $result."
    exit 2
else
    echo "OK - No changes need to be applied."
    exit 0
fi
