#!/bin/bash -e

trap 'kill $(jobs -p)' EXIT

installed() {
	which $1 > /dev/null
}

log() {
	echo >&2 $1
}

fatal() {
	log $1
	exit 1
}

if ! installed vegeta; then
	if ! installed go; then
		fatal "Could not find go. Either run the examples manually or install"
	fi

	go get github.com/tsenart/vegeta
	go install github.com/tsenart/vegeta
fi

PORT=5000
URL=http://127.0.0.1:${PORT}/

log "starting example server"
bundle install --quiet
bundle exec unicorn -p ${PORT} -c unicorn.conf &>> /dev/null &

# wait until unicorn is available
sleep 1

log "sending requests for 5 seconds"
printf "GET ${URL}\nPOST ${URL}\nDELETE ${URL}" | vegeta attack -duration 5s &>> /dev/null

log "printing /metrics"
curl -s "${URL}metrics"
