#!/bin/bash
echo '<<<cfengine>>>'

cfroot="/var/cfengine"
outputs="${cfroot}/outputs/cf*"
plog="${cfroot}/promise_summary.log"
cfbin="${cfroot}/bin/cf-agent"
policy="${cfroot}/policy_path.dat"

# truncate the last digit from timestamp to allow for a little wiggle room in comparison
lastrun=`ls -lt --time-style=+"%s" ${plog} | head -1 | awk '{print $6}' | head -c -2`
outlong=`ls -lt --time-style=+"%s" ${outputs} | head -1`
outfile=`echo ${outlong} | awk '{print $7}'`
lastout=`echo ${outlong} | awk '{print $6}' | head -c -2`
psum=`tail -n2 $plog | grep -v FAILSAFE | awk -F, '{print $1" "$2" "$3" "$4}' | tr ':' ' ' | awk '{print "Start:"$1", End:"$2", Version:"$6", PromKept:"$13", PromRepair:"$16", PromNotRepair:"$20}'`

if [ ! -f "${cfbin}" ]; then
        echo "Installed not installed"
        exit 1
else
        echo "Installed installed"
fi

/sbin/service cfengine3 status | grep 'running' 2>&1 > /dev/null
if [ $? -eq 0 ]; then
        echo "Service enabled"
else
        echo "Service disabled"
fi

if [ -f "${policy}" ]; then
        echo "PolicyPath" `cat $policy`
else
        echo "PolicyPath none"
fi
echo "RunStatus $psum"
if [ "${lastrun}" == "${lastout}" ]; then
        if [ -f "${outfile}" ]; then
                cat ${outfile}
        else 
                echo "Output plugin error - expected file ${outfile} not found"
        fi
else
        echo "Output none"
fi
