if [[ "$RELEASE_COMMAND" == "rpc" || "$RELEASE_COMMAND" == "remote" ]]; then
  export 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
else
  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
  elif [ "$LIVEBOOK_CLUSTER" = "auto" ] && [ ! -z "$ECS_CONTAINER_METADATA_URI" ]; then
    metadata="$(curl --silent $ECS_CONTAINER_METADATA_URI)"
    machine_ip="$(echo $metadata | $RELEASE_ROOT/bin/livebook eval 'IO.read(:stdio, :eof) |> JSON.decode!() |> Map.fetch!("Networks") |> hd() |> Map.fetch!("IPv4Addresses") |> hd() |> IO.write()')"
    image_id="$(echo $metadata | $RELEASE_ROOT/bin/livebook eval 'IO.read(:stdio, :eof) |> JSON.decode!() |> Map.fetch!("ImageID") |> IO.write()')"

    if [ -z "${LIVEBOOK_NODE}" ]; then
      deployment="$(echo $image_id | shasum | cut -c 1-10)"
      export LIVEBOOK_NODE="livebook-${deployment}@${machine_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"

  # 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
fi
