#!/bin/bash
# -*- mode: shell-script; indent-tabs-mode: t; sh-basic-offset: 8; sh-indentation: 8; tab-width: 8 -*-

PROG="$(basename ${0})"

tool_output_dir="${1}"
if [[ ! -d "${tool_output_dir}" ]]; then
	printf -- "%s: invalid tool output directory, '%s'\n" "${PROG}" "${tool_output_dir}" >&2
	exit 1
fi

interval="${2}"
if [[ -z "${interval}" ]]; then
	printf -- "%s: missing required 'interval' argument\n" "${PROG}" >&2
	exit 1
fi

command -v pmlogger > /dev/null
if [[ ${?} -ne 0 ]]; then
	printf -- "%s: missing required 'pmlogger' command\n" "${PROG}" >&2
	exit 1
fi

# We add the PCP libexec path to our PATH so that we can reference the
# commands below without using an explicit path, thus allowing unit tests to
# mock out the behavior.
export PATH="${PATH}:/usr/libexec/pcp/bin"

pmcd_wait -v -t 10
if [[ ${?} -ne 0 ]]; then
	printf -- "%s: no pmcd daemon running (waited 10 seconds)\n" "${PROG}" >&2
	exit 1
fi

pmlogconf -c -r ${tool_output_dir}/pmlogger.conf
if [[ ${?} -ne 0 ]]; then
	printf -- "%s: failed to create pmlogger config file, '%s'\n" "${PROG}" "${tool_output_dir}/pmlogger.conf" >&2
	exit 1
fi

# Save the interval for use by post-processing step.
printf -- "%s\n" "${interval}" > ${tool_output_dir}/interval

exec pmlogger -c ${tool_output_dir}/pmlogger.conf -t ${interval} archive
