#!/bin/bash -eu

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

PORT=<%= p("cf_networking.vxlan_policy_agent.debug_server_port")%>
URL=127.0.0.1:"${PORT}"/log-level
RUN_DIR=/var/vcap/sys/run/vxlan-policy-agent
LOG_DIR=/var/vcap/sys/log/vxlan-policy-agent
TIMEOUT=20
export PIDFILE="${RUN_DIR}"/vxlan-policy-agent.pid

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

exec 1>> "${LOG_DIR}"/vxlan-policy-agent_ctl.out.log
exec 2>> "${LOG_DIR}"/vxlan-policy-agent_ctl.err.log

case $1 in

  start)
    trap 'handle_orphaned_server vxlan-policy-agent ${pid}' TERM

    stop_process_on_port "${PORT}"

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

    pid=$!

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

    ;;

  stop)

    stop_process

    ;;

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

    ;;

esac
<% end %>
