#!/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: memory usage"
	else
	    title="groonga: ${label}: memory usage"
	fi
	cat <<EOF
graph_title ${title}
graph_vlabel memory usage
graph_category groonga
graph_info groonga memory usage

rss.label resident set size
rss.type GAUGE
vsz.label virtual memory size
vsz.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})
read rss_in_kb vsz_in_kb <<EOC
$(ps h -o rss,vsz -p ${groonga_pid})
EOC
echo "rss.value ${rss_in_kb}000"
echo "vsz.value ${vsz_in_kb}000"
