#!/bin/sh

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

case "$1" in
    autoconf|detect)
	pid_paths=
	if [ -n "${pid_path}" ]; then
	    pid_paths="${pid_paths}${pid_paths:+ }${pid_path}"
	fi
	# For backward compatibility. Remove me when 5.0.0.
	if [ -n "${pid_file}" ]; then
	    pid_paths="${pid_paths}${pid_paths:+ }${pid_file}"
	fi
	if [ -n "${http_pid_path}" ]; then
	    pid_paths="${pid_paths}${pid_paths:+ }${http_pid_path}"
	fi
	if [ -n "${httpd_pid_path}" ]; then
	    pid_paths="${pid_paths}${pid_paths:+ }${httpd_pid_path}"
	fi
	if [ -n "${gqtp_pid_path}" ]; then
	    pid_paths="${pid_paths}${pid_paths:+ }${gqtp_pid_path}"
	fi
	if [ -z "${pid_paths}" ]; then
	    message="no (No PID path is specified. Specify "
	    message="${message} env.pid_path, env.http_pid_path, "
	    message="${message} env.httpd_pid_path and/or env.gqtp_pid_path.)"
	    echo "${message}"
	    exit 1
	fi

	for _pid_path in ${pid_paths}; do
	    if [ -f "${_pid_path}" ]; then
		echo "yes"
		exit 0
	    fi
	done

	echo "no (All PID paths don't exist: ${pid_paths})"
	exit 1
	;;
    suggest)
	if [ -n "${http_pid_path}" -a -f "${http_pid_path}" ]; then
	    echo "http"
	fi
	if [ -n "${httpd_pid_path}" -a -f "${httpd_pid_path}" ]; then
	    echo "httpd"
	fi
	if [ -n "${gqtp_pid_path}" -a -f "${gqtp_pid_path}" ]; then
	    echo "gqtp"
	fi
	exit 0
	;;
    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

server_type="${0##*_}"
if [ -n "${server_type}" ]; then
    pid_path_variable_name="${server_type}_pid_path"
else
    # For backward compatibility. Remove me when 5.0.0.
    if [ -z "${pid_path}" -a -n "${pid_file}" ]; then
	pid_path_variable_name="pid_file"
    else
	pid_path_variable_name="pid_path"
    fi
fi
_pid_path=$(eval "echo \${${pid_path_variable_name}}")
if [ -z "${_pid_path}" ]; then
    echo "PID path isn't specified by env.${pid_path_variable_name}" 1>&2
    exit 1
fi
if [ ! -f "${_pid_path}" ]; then
    echo "PID path doesn't exist: ${_pid_path}" 1>&2
    exit 1
fi

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