#!/bin/bash -eu

<% unless p("cf_networking.disable") %>
set -o pipefail

LOG_DIR=/var/vcap/sys/log/silk-daemon
LOGFILE="${LOG_DIR}"/drain.log
REP_ADDRESS=<%= p("cf_networking.rep_listen_addr_admin") %>
SILK_DAEMON_HEALTH_CHECK_ADDRESS=localhost:<%= p("cf_networking.silk_daemon.listen_port") %>
export RUN_DIR=/var/vcap/sys/run/silk-daemon
export PIDFILE="${RUN_DIR}"/silk-daemon.pid

mkdir -p "${LOG_DIR}"

exec 3>&1

exec 1>> "${LOGFILE}"
exec 2>> "${LOGFILE}"

run_teardown() {
  /var/vcap/packages/silk-daemon/bin/silk-teardown \
    -config=/var/vcap/jobs/silk-daemon/config/client-config.json
}

shutdown_silk_daemon() {
  /var/vcap/packages/silk-daemon/bin/silk-daemon-shutdown \
    --repUrl "http://${REP_ADDRESS}/ping" \
    --silkDaemonUrl "http://${SILK_DAEMON_HEALTH_CHECK_ADDRESS}/ping" \
    --silkDaemonPidPath "${PIDFILE}"
}

output_for_bosh() {
  local exit_code=$?

  if [ "${exit_code}" -eq 0 ]; then
    echo "$(date): drain success"
  else
    echo "$(date): drain failed"
  fi

  echo "${exit_code}" >&3
}

trap output_for_bosh EXIT

shutdown_silk_daemon
run_teardown
<% else %>
  echo "0"
<% end %>
