#!/bin/sh

#
# This file is released under the terms of the Artistic License.
# Please see the file LICENSE, included in this package, for details.
#
# Copyright (C) 2002-2008 Open Source Development Labs, Inc.
#               2002-2014 Mark Wong
#               2014      2ndQuadrant, Ltd.
#

#
# Check if sar is in the user's path.  If not, set to true so the script
# doesn't complain.
#

which sar > /dev/null 2>&1
if [ $? -eq 0 ]; then
	SAR=sar
else
	SAR=true
fi

which pidstat > /dev/null 2>&1
if [ $? -eq 0 ]; then
	PIDSTAT="pidstat -H -h -l -d -r -s -U -u -w -v"
	$PIDSTAT 1 1 > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		PIDSTAT="pidstat -h -l -d -r -s -U -u -w"
		$PIDSTAT 1 1 > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			PIDSTAT="pidstat -h -l -d -r -U -u -w"
			$PIDSTAT 1 1 > /dev/null 2>&1
			if [ $? -ne 0 ]; then
				echo "WARNING: Cannot determine propper pidstat flags"
				PIDSTAT="true"
			fi
		fi
	fi
else
	PIDSTAT=true
fi

if [ $# -lt 1 ]; then
    echo "usage: $0 --outdir <output_dir> --iter <iterations> -sample <sample_length>"
    echo "	<output_dir> will be created if it doesn't exist"
    exit 1
fi

COUNTER=0

while :
do
	case $# in
	0)
		break
		;;
	esac

	option=$1
	shift

	orig_option=$option
	case $option in
	--*)
		;;
	-*)
		option=-$option
		;;
	esac

	case $option in
	--*=*)
		optarg=`echo $option | sed -e 's/^[^=]*=//'`
		arguments="$arguments $option"
		;;
	--db | --dbname | --outdir | --iter | --sample)
		optarg=$1
		shift
		arguments="$arguments $option=$optarg"
		;;
	esac

	case $option in
	--db)
		DBTYPE=$optarg
		;;
	--dbname)
		DBTYPE_NAME=$optarg
		;;
	--outdir)
		OUTPUT_DIR=$optarg
		;;
	--iter)
		ITERATIONS=$optarg
		;;
	--sample)
		SAMPLE_LENGTH=$optarg
		;;
	esac
done

if [ -z $OUTPUT_DIR ]; then
	echo "use --outdir"
	exit 1
fi

if [ -z $ITERATIONS ]; then
	echo "use --iter"
	exit 1
fi

if [ -z $SAMPLE_LENGTH ]; then
	echo "use --sample"
	exit 1
fi

# create the output directory in case it doesn't exist
mkdir -p $OUTPUT_DIR

echo "starting system statistics data collection"

# collect all sar data in binary form
${SAR} -o ${OUTPUT_DIR}/sar_raw.out ${SAMPLE_LENGTH} ${ITERATIONS} &

# collect per process statistics as best we can...
${PIDSTAT} -h -l -d -r -s -u -w ${SAMPLE_LENGTH} ${ITERATIONS} \
		> ${OUTPUT_DIR}/pidstat.txt &

exit 0
