#!/usr/bin/env bash
set -euo pipefail

log() {
  local msg
  local time

  msg=$1
  time=$(date -u +"%Y-%m-%dT%H:%M:%S.%NZ")

  echo "$time: $msg"
}

start="$( date +%s )"
timeout=120

# In Resolute netcat has an AppArmor profile that requires the garden
# directory to be executable even when post-start runs netcat as root.
# consider changing greenskeeper to create this with these permissions,
# or just use curl instead of netcat.
chmod 755 /var/vcap/data/garden/


log "Pinging garden server..."
i=1

<% if p("garden.listen_network") == "tcp" -%>
cmd='curl -s <%= p("garden.listen_address") %>/ping'
<% else -%>
cmd='echo -e "GET /ping HTTP/1.1\r\n\r\n" | nc -U <%= p("garden.listen_address") %>'
<% end -%>

while [ $(( $(date +%s) - timeout )) -lt "$start" ]; do
  log "Attempt $i..."
  if sh -c "${cmd}"; then
    log "Success!"
    exit 0
  fi
  i=$((i + 1))
  sleep 1
done

log "Timed out pinging garden server."
exit 1
