#!/bin/sh

#%# family=auto
#%# capabilities=autoconf

case "$1" in
    autoconf|detect)
	if [ -z "${pid_file}" ]; then
            echo "no (PID file isn't specified by env.pid_file)"
	    exit 1
        elif [ -f "${pid_file}" ]; then
            echo "yes"
	    exit 0
        else
            echo "no (PID file doesn't exist: ${pid_file})"
	    exit 1
        fi
        ;;
    config)
	if [ -z "${label}" ]; then
	    title="groonga: CPU load"
	else
	    title="groonga: ${label}: CPU load"
	fi
        cat <<EOF
graph_title ${title}
graph_vlabel CPU load (%)
graph_category groonga
graph_info groonga CPU load

cpu_load.label CPU load
cpu_load.type GAUGE
EOF
        exit 0
        ;;
    *)
esac

if [ -z "${pid_file}" ]; then
    echo "PID file isn't specified by env.pid_file"
    exit 1
fi

groonga_pid=$(cat ${pid_file})
top_for_groonga=$(top -b -n 1 -p ${groonga_pid} | tail -2 | head -1)
load_in_percent=$(echo ${top_for_groonga} | sed -r -e 's/ +/ /g' | cut -d' ' -f 9)
echo "cpu_load.value ${load_in_percent}"
