#!/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/nxlog/helpers/ctl_setup.sh 'nxlog'

export PORT=${PORT:-5000}
export LANG=en_US.UTF-8

case $1 in

  start)
    pid_guard $PIDFILE $JOB_NAME

    # Setup logrotate to run hourly instead!
    if [ -f "/etc/cron.daily/logrotate" ]; then
      mv -f /etc/cron.daily/logrotate /etc/cron.hourly/
    fi

    exec chpst -u <%= p('nxlog.runas') %> /var/vcap/packages/nxlog/bin/nxlog \
      -c $JOB_DIR/config/nxlog.conf \
      1>>$LOG_DIR/$JOB_NAME.stdout.log \
      2>>$LOG_DIR/$JOB_NAME.stderr.log

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

    ;;

  stop)
    kill_and_wait $PIDFILE

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

    ;;

esac
exit 0
