#!/bin/bash

set -e # exit immediately if a simple command exits with a non-zero status
set -u # report the usage of uninitialized variables

# Setup env vars and folders for the ctl script
source /var/vcap/jobs/registry/helpers/ctl_setup.sh 'registry'

export LANG=en_US.UTF-8

case $1 in
  start)
    pid_guard $PIDFILE $JOB_NAME
    <%- if_p('docker.registry.http_proxy') do |v| %>
      export http_proxy="<%= v %>"
    <%- end %>
    <%- if_p('docker.registry.https_proxy') do |v| %>
      export https_proxy="<%= v %>"
    <%- end %>
    <%- if_p('docker.registry.no_proxy') do |v| %>
      export no_proxy="<%= v %>"
    <%- end %>
    (
        {
            # Set limitations on system resources
            ulimit -n $JOB_ULIMIT_FILES
            exec chpst -u vcap:vcap registry serve \
                ${JOB_DIR}/config/registry.conf
        } \
        >>$LOG_DIR/$JOB_NAME.log 2>&1
    ) &
    echo $! > $PIDFILE
    ;;
  stop)
<% if p('docker.registry.debug_endpoint_enabled') == true ||
      p('docker.registry.debug_endpoint_enabled') =~ (/(true|t|yes|y|1)$/i)
  debug = p('docker.registry.debug_endpoint')
  port = debug.split(':')[1].to_s
  host = (debug.split(':')[0].to_s.empty?) ? '127.0.0.1' : debug.split(':')[0].to_s
  %>
    (
        echo "$(date +%y:%m:%d-%H:%M:%S) GET http://<%= host %>/<%= port %>/debug/health" >> $LOG_DIR/$JOB_NAME.health.log
        exec 9<> /dev/tcp/<%= host %>/<%= port %>
        echo -e "GET /debug/health HTTP/1.0\r\n\r\n" >&9
        cat <&9 | tee -a $LOG_DIR/$JOB_NAME.health.log
        echo >> $LOG_DIR/$JOB_NAME.health.log
        echo "$(date +%y:%m:%d-%H:%M:%S) DONE" >> $LOG_DIR/$JOB_NAME.health.log
        exec 9>&-
    )
<% end %>
    kill_and_wait $PIDFILE
    ;;
  *)
    echo "Usage: ctl {start|stop}"
    ;;
esac
exit 0
