#!/bin/bash -eu

<% unless p("cf_networking.disable") %>
source /var/vcap/packages/ctl-utils/ctl_util.sh

PORT=<%= p("cf_networking.silk_daemon.listen_port") %>
URL=127.0.0.1:"${PORT}"
RUN_DIR=/var/vcap/sys/run/silk-daemon
LOG_DIR=/var/vcap/sys/log/silk-daemon
TIMEOUT=20
export PIDFILE="${RUN_DIR}"/silk-daemon.pid

mkdir -p "${RUN_DIR}"
mkdir -p "${LOG_DIR}"

exec 1>> "${LOG_DIR}"/silk-daemon_ctl.out.log
exec 2>> "${LOG_DIR}"/silk-daemon_ctl.err.log

case $1 in

  start)
    trap 'handle_orphaned_server silk-daemon ${pid}' TERM

    stop_process_on_port "${PORT}"

    /var/vcap/packages/silk-daemon/bin/silk-daemon \
         -config=/var/vcap/jobs/silk-daemon/config/client-config.json \
         2> >(tee -a "${LOG_DIR}"/silk-daemon.stderr.log | logger -p user.error -t silk-daemon) \
         1> >(tee -a "${LOG_DIR}"/silk-daemon.stdout.log | logger -t silk-daemon) &

    pid=$!

    healthy=$(wait_for_server_to_become_healthy "${URL}" "${TIMEOUT}")
    write_pid "${healthy}" "${pid}"

    ;;

  stop)

    stop_process

    ;;

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

    ;;

esac
<% end %>
