#!/bin/bash

CHECK_INTERVAL=60 #minutes

cvmfs_talk_cfg=()
cvmfs_talk_cfg+=("")


[ -f /etc/check_mk/cvmfs_talk.cfg ] && source /etc/check_mk/cvmfs_talk.cfg

echo "<<<cvmfs_talk>>>"

client=`echo $SSH_CLIENT | awk '{print $1}'`
for i in $(seq 0 $((${#cvmfs_talk_cfg[@]}-1))) ; do
    repo="${cvmfs_talk_cfg[$i]}"
    pidfile="/tmp/pid.cvmfs_talk_${client}_${repo}"
    outputfile="/tmp/output.cvmfs_talk_${client}_${repo}"
    
    still_running="no"
	pid=$(cat $pidfile 2>/dev/null)
	if [ ${#pid} -gt 0 ] ; then
		ps ax | awk -v PID=$pid '{if($1==PID)exit 1}' > /dev/null 2> /dev/null
		if [ $? -eq 1 ] ; then
			still_running="$pid"
		fi
	fi

	if [ "$still_running" != "no" ]; then
        echo "${repo} is being checked; pid ${still_running} still exists"
        continue
    fi
    
    if [[ -f $outputfile ]] ; then
		res=$(cat $outputfile | grep "Current cache size")
		echo "$repo $res"
    fi

    if [[ -s $outputfile ]] && [[ $(find $outputfile -mmin -$CHECK_INTERVAL 2>/dev/null | wc -l) -gt "0" ]] ; then
        continue
    fi

	ls /cvmfs/$repo &>/dev/null && cvmfs_talk -i $repo cache size >$outputfile 2>&1 & disown 2>/dev/null
	echo "$!" > $pidfile
done
