if [ "$LIVEBOOK_CLUSTER" = "auto" ] && [ ! -z "$FLY_APP_NAME" ]; then
  export LIVEBOOK_CLUSTER="dns:${FLY_APP_NAME}.internal"

  case "$ERL_AFLAGS $ERL_ZFLAGS" in
    *"-proto_dist"*) ;;
    *)
      export ERL_AFLAGS="$ERL_AFLAGS -proto_dist inet6_tcp"
      ;;
  esac

  if [ -z "${LIVEBOOK_NODE}" ]; then
    deployment="$(echo "$FLY_IMAGE_REF" | shasum | cut -c 1-10)"
    export LIVEBOOK_NODE="${FLY_APP_NAME}-${deployment}@${FLY_PRIVATE_IP}"
  fi
fi

if [ -f "${RELEASE_ROOT}/user/env.sh" ]; then
  . "${RELEASE_ROOT}/user/env.sh"
fi

export RELEASE_MODE="interactive"
export RELEASE_DISTRIBUTION="none"

# Mirror these values, so that it is easier to use "bin/release rpc",
# though it still requires setting RELEASE_DISTRIBUTION=name
if [ ! -z "${LIVEBOOK_NODE}" ]; then export RELEASE_NODE=${LIVEBOOK_NODE}; fi
if [ ! -z "${LIVEBOOK_COOKIE}" ]; then export RELEASE_COOKIE=${LIVEBOOK_COOKIE}; fi

# We remove the COOKIE file when assembling the release, because we
# don't want to share the same cookie across users. The Elixir release
# script attempts to read from that file, which would fail, therefore
# we need to set it here. Also there is a very tiny time gap between we
# start distribution and set the cookie during application boot, so we
# specifically want the temporary node cookie to be random, rather than
# a fixed value. Note that this value is overriden on boot, so other
# than being the initial node cookie, we don't really use it.
export RELEASE_COOKIE="${RELEASE_COOKIE:-$(cat /dev/urandom | env LC_ALL=C tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)}"

cd $HOME
