#!/bin/bash

set -e # exit immediately if a simple command exits with a non-zero status
set -u # report the usage of uninitialized variables

# Setup env vars and folders for the webapp_ctl script
source /var/vcap/jobs/stannis-agent/helpers/ctl_setup.sh 'stannis-agent'

PATH=$PATH:/var/vcap/packages/stannis-agent/bin
export PORT=${PORT:-5000}
export LANG=en_US.UTF-8

case $1 in

  start)
    pid_guard $PIDFILE $JOB_NAME

    # store pid in $PIDFILE
    echo $$ > $PIDFILE

    while true
    do
      echo Uploading stannis information >>$LOG_DIR/$JOB_NAME.stdout.log
      chpst -u vcap:vcap \
        stannis agent --config $JOB_DIR/config/agent.yml

      echo Now sleeping $UPLOAD_INTERVAL >>$LOG_DIR/$JOB_NAME.stdout.log
    	sleep $UPLOAD_INTERVAL
    done

    ;;

  stop)
    kill_and_wait $PIDFILE

    ;;
  *)
    echo "Usage: agent_ctl {start|stop}"

    ;;

esac
exit 0
