#!/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/sample-python-flask-app/helpers/ctl_setup.sh 'sample-python-flask-app'

export PORT=<%= p("port") %>
export LANG=en_US.UTF-8

case $1 in

  start)
    pid_guard $PIDFILE $JOB_NAME

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

    cd /var/vcap/packages/simpleflaskapp

    export PS1="> " # venv/bin/activate complains if missing
    . venv/bin/activate

    exec chpst -u vcap:vcap gunicorn simpleflaskapp:app --config $JOB_DIR/config/gunicorn.conf.py \
         >>$LOG_DIR/$JOB_NAME.log 2>&1

    ;;

  stop)
    kill_and_wait $PIDFILE

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

    ;;

esac
exit 0
