#!/bin/bash
cfagent="/usr/sbin/cfagent"
cfexecd="/usr/sbin/cfexecd"

case $(lsb_release -si) in 
  RedHatEnterpriseServer )
    cfdir="/var/cfengine"
    ;;
  * )
    cfdir="/var/lib/cfengine2"
    ;;
esac

procfs="/proc"
hz=100
pidof=$(which pidof)

if [ -z $1 ]; then
    echo "WARNING - configuration error"
    exit 1
else
    threshold="$1"
fi

# cfexecd pid
pid=`${pidof} ${cfexecd} || echo 0`

if [ "$pid" -eq "0" ]; then
    echo "CRITICAL - cfexecd process not found"
    exit 2
fi

# cfagent runtime
if [ -e /proc/cmdline ]; then
    rtime=0
    btime=$(grep btime ${procfs}/stat | cut -f2 -d\ )
    now=$(date +%s)
    pids=$(find ${procfs} -mindepth 2 -maxdepth 2 -type l -name exe \
            -lname ${cfagent} -printf '%h ' 2>/dev/null )

    for pid in ${pids}
    do
        stime=$(cut -f22 -d\ < ${pid}/stat)
        stime=$((stime / hz ))
        prtime=$((now - (btime + stime)))

        if [ ${prtime} -ge ${rtime} ]; then
            rtime=${prtime};
        fi
    done
fi

if [ "$rtime" -gt "$threshold" ]; then
    echo "CRITICAL - cfagent with runtime ${rtime} seconds found"
    exit 2
fi

lastrun=0;

for log in ${cfdir}/cfengine.*.runlog
do
    runtime=$(/usr/bin/stat -c '%Y' ${log})

    if [ ${runtime} -ge ${lastrun} ]; then
        lastrun=${runtime};
    fi
done

now=`date +%s`
lastrun=$((now-lastrun))
if [ "$lastrun" -gt "$threshold" ]; then
    echo "CRITICAL - cfagent hasn't run for ${lastrun} seconds"
    exit 2
fi


echo "OK - cfexecd (pid ${pid}) , cfagent (lastrun ${lastrun} seconds ago)"
exit 0
