#!/bin/bash

ESY__PACKAGE_NAME="REASONhCLIh3d1d0"
ESY__BIN_NAME="UTOP"

IS_RELEASE_BIN_ENV_SOURCED="ENV__${ESY__PACKAGE_NAME}__${ESY__BIN_NAME}"
IS_RELEASE_ENV_SOURCED="ENV__${ESY__PACKAGE_NAME}"

printError() {
  echo >&2 "ERROR:";
  echo >&2 "$0 command is not installed correctly. ";
  TROUBLESHOOTING="When installing <package_name>, did you see any errors in the log? "
  TROUBLESHOOTING="$TROUBLESHOOTING - What does (which <binary_name>) return? "
  TROUBLESHOOTING="$TROUBLESHOOTING - Please file a github issue on <package_name>'s repo."
  echo >&2 "$TROUBLESHOOTING";
}

if [ -z ${!IS_RELEASE_BIN_ENV_SOURCED+x} ]; then
  if [ -z ${!IS_RELEASE_ENV_SOURCED+x} ]; then

    #
    # Define $SCRIPTDIR
    #

    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
      SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
      SOURCE="$(readlink "$SOURCE")"
      # if $SOURCE was a relative symlink, we need to resolve it relative to the
      # path where the symlink file was located
      [[ $SOURCE != /* ]] && SOURCE="$SCRIPTDIR/$SOURCE"
    done
    SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

    #
    # Esy utility functions
    #

    esyStrLength() {
      # run in a subprocess to override $LANG variable
      LANG=C /bin/bash -c 'echo "${#0}"' "$1"
    }

    esyRepeatCharacter() {
      local chToRepeat="$1"
      local times="$2"
      printf "%0.s$chToRepeat" $(seq 1 "$times")
    }

    esyGetStorePathFromPrefix() {
      local prefix="$1"
      # Remove trailing slash if any.
      prefix="${prefix%/}"

      prefixLength=$(esyStrLength "$prefix")
      paddingLength=$((ESY__STORE_PADDING_LENGTH - prefixLength))

      # Discover how much of the reserved relocation padding must be consumed.
      if [ "$paddingLength" -lt "0" ]; then
        echo "$prefix is too deep inside filesystem, Esy won't be able to relocate binaries"
        exit 1;
      fi

      padding=$(esyRepeatCharacter '_' "$paddingLength")
      echo "$prefix/$ESY__STORE_VERSION$padding"
    }

    #
    # Esy Release Env
    #

    ESY__STORE_VERSION="3"
    ESY__STORE_PADDING_LENGTH="84"
    ESY__RELEASE=$(dirname "$SCRIPTDIR")

    ESY__STORE=$(esyGetStorePathFromPrefix "$ESY__RELEASE")
    if [ $? -ne 0 ]; then
      echo >&2 "error: $ESY__STORE"
      exit 1
    fi

    export ESY__RELEASE
    export ESY__STORE

    source "$ESY__RELEASE/releaseEnv"

    export "$IS_RELEASE_ENV_SOURCED"="sourced"
    export "$IS_RELEASE_BIN_ENV_SOURCED"="sourced"
  fi

  
    BINNAME="utop"

    command -v ${BINNAME} >/dev/null 2>&1 || {
      printError;
      exit 1;
    }

    if [ "$1" == "----where" ]; then
      which "${BINNAME}"
    else
      exec "${BINNAME}" "$@"
    fi
  

else
  printError;
  exit 1;
fi
