#!/bin/sh

# Sets and enables heart (recommended only in daemon mode)
case $RELEASE_COMMAND in
  daemon*)
    HEART_COMMAND="$RELEASE_ROOT/bin/$RELEASE_NAME $RELEASE_COMMAND"
    export HEART_COMMAND
    export ELIXIR_ERL_OPTIONS="-heart -kernel inet_dist_listen_min ${ERLANG_DISTRIBUTION_PORT} inet_dist_listen_max ${ERLANG_DISTRIBUTION_PORT}"
    ;;

  start*)
    export ELIXIR_ERL_OPTIONS="-kernel inet_dist_listen_min ${ERLANG_DISTRIBUTION_PORT} inet_dist_listen_max ${ERLANG_DISTRIBUTION_PORT}"
    ;;

  *)
    ;;
esac

# Set the release to work across nodes. If using the long name format like
# the one below (my_app@127.0.0.1), you need to also uncomment the
# RELEASE_DISTRIBUTION variable below. Must be "sname", "name" or "none".
export RELEASE_DISTRIBUTION=name

# Read current hostname from metadata server if available,
# this is to ensure that the hostname is correct in Google Cloud Compute.
#
# Having a valid DNS record is important to remotely connect to a running Erlang node.
if [[ "${RELEASE_HOST_DISCOVERY_METHOD}" == "gce_metadata" ]]; then
  GCP_PROJECT_ID=$(curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google" -s)
  GCP_INSTANCE_NAME=$(curl "http://metadata.google.internal/computeMetadata/v1/instance/name" -H "Metadata-Flavor: Google" -s)
  GCP_INSTANCE_ZONE=$(curl "http://metadata.google.internal/computeMetadata/v1/instance/zone" -H "Metadata-Flavor: Google" -s | sed 's:.*/::')
  RELEASE_HOSTNAME="$GCP_INSTANCE_NAME.$GCP_INSTANCE_ZONE.c.${GCP_PROJECT_ID}.internal"
else
  RELEASE_HOSTNAME=${RELEASE_HOSTNAME:-127.0.0.1}
fi

# RELEASE_NAME is guaranteed to be set by the start script and defaults to 'firezone'
# set RELEASE_NAME in the environment to a unique value when running multiple instances
# in the same network namespace (i.e. with host networking in Podman)
export RELEASE_NODE=${RELEASE_NAME}@${RELEASE_HOSTNAME}

# Choices here are 'interactive' and 'embedded'. 'interactive' boots faster which
# prevents some runit process management edge cases at the expense of the application
# not technically being ready to serve requests "right away". This is a useful tradeoff.
export RELEASE_MODE=interactive
