#!/bin/bash

# Use this script to check that pid file and process pid are conform
#
# Works for as much processes as found in the DIRCONF folder
#
# Each file must contain 2 lines, each being a shell command to execute:
#
# Line #1      A command to retrieve the CURRENT PID of process. Ex:  pgrep name
# Line #2      A command to retrieve the stored PID of process. Ex: cat /{...}/name.pid

DIR_CONF="/var/lib/nagios/check_pid.d"
OUTPUT_FILE="/tmp/check_pid"
DEBUG=0
DEBUG_FILE="/var/lib/nagios/check_pid.debug"

debug(){
    [ 0 -eq $DEBUG ] && return
    echo "$@" >> $DEBUG_FILE
}

if [ -f $OUTPUT_FILE ]
then
    rm $OUTPUT_FILE
fi

# Don't keep debug
[[ 0 -eq $DEBUG && -f $DEBUG_FILE ]] && rm $DEBUG_FILE

debug "--- $(date '+%Y/%m/%d %H:%M:%S') ---"

ERR_COUNT=0

for file in $( find $DIR_CONF -type f )
do
    debug "le fichier a lire est $file"
    proc_ps=`sed -n 1p $file`
    proc_cat=`sed -n 2p $file`
    debug "dans fichier -f1 = $proc_ps"
    debug "dans fichier -f2 = $proc_cat"
    real_pid=`eval $proc_ps`
    store_pid=`eval $proc_cat`
    debug "real_pid = $real_pid"
    debug "store_pid = $store_pid"
    if [[ $real_pid != $store_pid ]] || [ -z $real_pid ] || [ -z $store_pid ]
    then
	 echo -e "`basename $file` " >> $OUTPUT_FILE
	 let $((ERR_COUNT++))
    fi
done

if [ -f $OUTPUT_FILE ] && [ 0 -ne $ERR_COUNT ]
then
    echo "CRITICAL - probleme avec les pid des processus `cat $OUTPUT_FILE`"
    exit 2
fi
echo "OK pour `ls /var/lib/nagios/check_pid.d/|tr "\n" ","`"
exit 0
