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

# Pbench tool scripts must provide the following functions
# 1) Install the tool
# 2) Start data collection
# 3) Stop data collection
# 4) Post-process the data

# The "external-data-source" tool does not actually get executed, but is here
# so that the tool verification process work.

# Defaults
tool="$(basename ${0})"
mode=""
source=""
type=""

function usage {
    printf -- "The following options are available:\n"
    printf -- "\t--install                 install this perf tool\n\n"
    printf -- "\t--start|stop|postprocess  start/stop/post-process the data collection\n"
    printf -- "\t--dir=str                 directory to store data collection (required)\n"
    printf -- "\t--type=str                the type of the external data source (required, currently only \"url\" is supported)\n"
    printf -- "\t--source=str              the only supported \"type\" of external data source currently is \"url\", to which one\n"
    printf -- "\t                          provides the URL for the data source via \"--source\" parameter (required)\n"
}

# Process options and arguments
opts="$(getopt -q -o d --longoptions "install,postprocess,start,stop,dir:,source:,type:" -n "getopt.sh" -- "${@}")"
if [[ ${?} -ne 0 ]]; then
    printf -- "\n%s: you specified an invalid option\n\n" "${tool}" >&2
    usage >&2
    exit 1
fi
eval set -- "${opts}"
while true; do
    case "${1}" in
	--install)
	    mode="install"
	    shift
	    ;;
	--postprocess)
	    mode="postprocess"
	    shift
	    ;;
	--start)
	    mode="start"
	    shift
	    ;;
	--stop)
	    mode="stop"
	    shift
	    ;;
	-d|--dir)
	    shift
	    if [[ -n "${1}" ]]; then
		tool_dir="${1}"
		shift
	    fi
	    ;;
	--source)
            shift
            if [[ -n "${1}" ]]; then
		source="${1}"
		shift
            fi
            ;;
	--type)
	    shift
	    if [[ -n "${1}" ]]; then
		type="${1}"
		shift
	    fi
	    ;;
	--)
	    shift
	    break
	    ;;
    esac
done

if [[ -z "${mode}" ]]; then
    printf -- "%s: Error, one of the following options is required, --install|--start|--stop|--postprocess\n\n" "${tool}" >&2
    usage >&2
    exit 1
fi

if [[ -z "${source}" || -z "${type}" ]]; then
    printf -- "%s: Error, --type and --source parameters are mandatory\n\n" "${tool}" >&2
    usage >&2
    exit 1
fi

if [[ "${mode}" == "start" ]]; then
    if [[ -z "${tool_dir}" || ! -d "${tool_dir}" ]]; then
       	printf -- "%s: Error, --dir argument is required with a valid directory\n\n" "${tool}" >&2
	usage >&2
	exit 1
    fi
    tool_output_dir=${tool_dir}/${tool}
    mkdir -p ${tool_output_dir}
    if [[ $? -ne 0 ]]; then
	printf -- "%s: failed to create tool output directory, '%s'\n" "${tool}" "${tool_output_dir}" >&2
        exit 1
    fi
    printf -- "{ \"type\": \"%s\", \"source\": \"%s\" }\n" "${type}" "${source}" > ${tool_output_dir}/data-source.json
fi
