#!/bin/bash

set -e # exit immediately if a simple command exits with a non-zero status

# Setup common env vars and folders
source /var/vcap/jobs/remote-syslog/helpers/ctl_setup.sh 'remote-syslog'

# reuse $REMOTE_SYSLOG_DEBUG to toggle print all commands
if [[ "${REMOTE_SYSLOG_DEBUG}X" != "X" ]]; then
  set -x
fi

# Set the hostname
if hostname=$(public_hostname); then
  hostname $hostname
else
  hostname <%= index %>.<%= name %>.<%= spec.networks.methods(false).grep(/[^=]$/).first.to_s %>.<%= spec.deployment %>.<%= spec.dns_domain_name %>
fi

case $1 in

  start)
    pid_guard ${PID_FILE} ${JOB_NAME}

    # Create Remote Syslog user & group
    create_group ${REMOTE_SYSLOG_GROUP}
    create_user ${REMOTE_SYSLOG_USER} ${REMOTE_SYSLOG_GROUP}

    # Start Remote Syslog daemon
    exec chpst -u ${REMOTE_SYSLOG_USER}:${REMOTE_SYSLOG_GROUP} remote_syslog \
        --configfile="${REMOTE_SYSLOG_CONF_DIR}/remote_syslog.yml" \
        --pid-file="${PID_FILE}" \
        --hostname="${REMOTE_SYSLOG_HOSTNAME}" \
        --new-file-check-interval="${REMOTE_SYSLOG_NEW_FILE_CHECK_INTERVAL}" \
        ${REMOTE_SYSLOG_DEBUG} \
        >>${REMOTE_SYSLOG_LOG_DIR}/${OUTPUT_LABEL}.log 2>&1
    ;;

  stop)
    # Stop Remote Syslog daemon
    kill_and_wait ${PID_FILE}
    ;;

  *)
    echo "Usage: $0 {start|stop}"
    exit 1
    ;;

esac
exit 0
