#!/usr/bin/env bash

# Wurkzen Wurker Parametric Test Bee
# ----------------------------------
#
# A Bee may be any command-line executable script, command or program which exits
# with a unix-like exit code. Both stdout and stderr will be captured and debug
# or error logged in Wurker based on that exit code.
#
# Unlike PyBees, Bees should be completely independent, with their own interface
# that accepts command-line arguments, provided in the Bee's definition in the
# configuration database `wurker_bee` table.
#
# This script accepts the following parameters:
#
#     -d    How long to run, in seconds. If 0 then poll in 'supervised' mode. (Default: 0)
#     -l    Log test pings with timestamps to this file. (Default: '/tmp/test_pybee.log')
#     -i    How often to ping to log file. (Default: 10)

SCRIPT=$(basename $0)
PID=$$

DURATION=0
LOG=/tmp/test_bee.log
INTERVAL=10
EXIT=0


_exit_help() {
    echo "usage: $SCRIPT [-d DURATION] [-i INTERVAL] [-l LOG] [-e EXIT]"
    exit 1
}


_ping_log() {
    local i=$1
    local msg="$(date +'%b %d %T') ${SCRIPT}[${PID}]: Ping ${i}"
    echo "$msg"
    echo "$msg" >> $LOG
}


run() {
    echo "$(date +'%b %d %T') ${SCRIPT}[${PID}] Arguments: DURATION=${DURATION}, INTERVAL=${INTERVAL}, EXIT=${EXIT}, LOG=${LOG}"

    if [ $DURATION -gt 0 ]; then
	echo "$(date +'%b %d %T') ${SCRIPT}[${PID}] Scheduled mode"

	x=1
	for i in $(seq 1 ${INTERVAL} ${DURATION}); do
	    _ping_log $(($x))
	    sleep $INTERVAL
	    ((x++))

	    [ $EXIT -ne 0 ] && [ $x -gt $EXIT ] && break
	done

    else
	echo "$(date +'%b %d %T') ${SCRIPT}[${PID}] Supervised mode"

	x=1
	while true; do
	    _ping_log $x
	    sleep $INTERVAL
	    ((x++))

	    [ $EXIT -ne 0 ] && [ $x -gt $EXIT ] && break
	done
    fi
}


main() {
    while getopts ":hd:l:i:e:" arg; do
	case $arg in
	    d)
		DURATION=$OPTARG
		;;
	    l)
		LOG=$OPTARG
		;;
	    i)
		INTERVAL=$OPTARG
		;;
	    e)
		EXIT=$OPTARG
		;;
	    h)
		_exit_help
		;;
	    *)
		echo "Invalid option: -${OPTARG}"; echo
		_exit_help
		;;
	esac
    done

    # Just run it!
    run

    [ $EXIT -ne 0 ] && echo "$(date +'%b %d %T') ${SCRIPT}[${PID}] Dummy error" 1>&2
    exit $EXIT
}

main "${@}"
