#!/bin/bash
# vim: set ft=sh

set -e -x

pidfile=/var/vcap/sys/run/bpm/gorouter/gorouter.pid
healthchecker_pidfile=/var/vcap/sys/run/bpm/gorouter/gorouter-healthchecker.pid
log_file=/var/vcap/sys/log/gorouter/drain.log
log_format=<%= p("router.logging.format.timestamp") %>
mkdir -p "$(dirname ${log_file})"

log() {
  log_string=$1

  if [ "$log_format" == "deprecated" ]; then
    echo "$(date): ${log_string}" >> ${log_file}
  else
    echo "$(date +%Y-%m-%dT%H:%M:%S.%NZ): ${log_string}" >> ${log_file}
  fi
}

if [[ ! -f ${healthchecker_pidfile} ]]; then
  log "healthchecker pidfile does not exist"
else
  healthchecker_pid="$(cat ${healthchecker_pidfile})"
  if kill -USR1 "${healthchecker_pid}"; then
    log "healthchecker triggering drain"
  else
    log "healthchecker exited"
    rm ${healthchecker_pidfile}
  fi
fi

if [[ ! -f ${pidfile} ]]; then
  log "pidfile does not exist"
  echo 0
  exit 0
fi

pid="$(cat ${pidfile})"

if kill -USR1 "${pid}"; then
  log "triggering drain"
  echo -5
else
  log "gorouter exited"
  rm ${pidfile}
  echo 0
fi
