#!/usr/bin/env bash

# Source this file from bash or zsh to activate the checkout-managed DAY-EC
# conda environment.

if [ -f "$HOME/.config/daylily/headnode-configure.in-progress" ] && [ "${DAYLILY_EC_CONFIGURE_ACTIVE:-0}" != "1" ]; then
  echo "Error: headnode configure maintenance is active; environment activation is disabled." >&2
  return 1 2>/dev/null || exit 1
fi

__daylily_activate_is_sourced() {
  if [ -n "${ZSH_VERSION:-}" ]; then
    case "${ZSH_EVAL_CONTEXT:-}" in
      *:file|*:file:*) return 0 ;;
    esac
    return 1
  fi

  if [ -n "${BASH_VERSION:-}" ]; then
    [ "${BASH_SOURCE[0]}" != "$0" ]
    return
  fi

  return 1
}

if ! __daylily_activate_is_sourced; then
  echo "Error: this script must be sourced." >&2
  echo "Usage: source ./activate" >&2
  exit 1
fi

__daylily_activate_script_path() {
  if [ -n "${BASH_VERSION:-}" ]; then
    printf '%s\n' "${BASH_SOURCE[0]}"
    return 0
  fi

  if [ -n "${ZSH_VERSION:-}" ]; then
    eval 'printf "%s\n" "${(%):-%N}"'
    return 0
  fi

  return 1
}

__daylily_activate_conda_is_function() {
  case "$(type conda 2>/dev/null)" in
    *"shell function"*|*"function"*) return 0 ;;
  esac
  return 1
}

__daylily_activate_conda_exe() {
  if [ -n "${CONDA_EXE:-}" ] && [ -x "${CONDA_EXE}" ]; then
    printf '%s\n' "${CONDA_EXE}"
    return 0
  fi

  if [ -n "${BASH_VERSION:-}" ]; then
    type -p conda
    return
  fi

  if [ -n "${ZSH_VERSION:-}" ]; then
    whence -p conda
    return
  fi

  command -v conda
}

__daylily_activate_load_conda() {
  if ! command -v conda >/dev/null 2>&1; then
    return 1
  fi

  if __daylily_activate_conda_is_function; then
    return 0
  fi

  local conda_exe conda_shell conda_hook conda_base
  conda_exe="$(__daylily_activate_conda_exe 2>/dev/null || true)"
  if [ -z "${conda_exe}" ]; then
    return 1
  fi

  if [ -n "${BASH_VERSION:-}" ]; then
    conda_shell="bash"
  elif [ -n "${ZSH_VERSION:-}" ]; then
    conda_shell="zsh"
  else
    conda_shell="posix"
  fi

  conda_hook="$("${conda_exe}" "shell.${conda_shell}" hook 2>/dev/null || "${conda_exe}" shell.posix hook 2>/dev/null || true)"
  if [ -n "${conda_hook}" ]; then
    eval "${conda_hook}"
    return 0
  fi

  conda_base="$("${conda_exe}" info --base 2>/dev/null || true)"
  if [ -n "${conda_base}" ] && [ -f "${conda_base}/etc/profile.d/conda.sh" ]; then
    . "${conda_base}/etc/profile.d/conda.sh"
    return 0
  fi

  return 1
}

__daylily_activate_refresh_command_cache() {
  hash -r 2>/dev/null || true
  rehash 2>/dev/null || true
}

__daylily_activate_configure_conda_noninteractive() {
  # These settings are bootstrap state, not activation state.  Keep the
  # marker in the user config directory so every later dy-a/source ./activate
  # is read-only.  The lock still serializes first-time initialization when
  # several controllers start together.
  local marker_dir="${HOME}/.config/daylily"
  local marker_file="${marker_dir}/conda-noninteractive-configured"
  local lock_dir="${HOME}/.daylily-conda-config.lock"
  local lock_pid_file="${lock_dir}/pid"
  local waited=0
  local owner_pid
  local rc=0

  if [ -f "${marker_file}" ]; then
    return 0
  fi

  if ! mkdir -p "${marker_dir}"; then
    echo "Error: failed to create the Conda configuration marker directory: ${marker_dir}" >&2
    return 1
  fi

  while ! mkdir "${lock_dir}" 2>/dev/null; do
    if [ -f "${marker_file}" ]; then
      return 0
    fi
    owner_pid="$(cat "${lock_pid_file}" 2>/dev/null || true)"
    case "${owner_pid}" in
      ''|*[!0-9]*) ;;
      *)
        if ! kill -0 "${owner_pid}" 2>/dev/null; then
          rm -f "${lock_pid_file}"
          rmdir "${lock_dir}" 2>/dev/null || true
          continue
        fi
        ;;
    esac
    if [ "${waited}" -ge 120 ]; then
      echo "Error: timed out waiting for the Conda configuration lock: ${lock_dir}" >&2
      return 1
    fi
    sleep 1
    waited=$((waited + 1))
  done

  if [ -f "${marker_file}" ]; then
    rmdir "${lock_dir}" 2>/dev/null || true
    return 0
  fi

  if ! printf '%s\n' "$$" >"${lock_pid_file}"; then
    rmdir "${lock_dir}" 2>/dev/null || true
    echo "Error: failed to record the Conda configuration lock owner." >&2
    return 1
  fi

  if ! conda config --set plugins.auto_accept_tos true; then
    echo "Error: failed to configure Conda automatic Terms of Service acceptance." >&2
    rc=1
  elif ! conda config --set always_yes true; then
    echo "Error: failed to configure Conda automatic confirmation acceptance." >&2
    rc=1
  fi

  if [ "${rc}" -eq 0 ]; then
    if ! : >"${marker_file}" || ! chmod 600 "${marker_file}"; then
      echo "Error: failed to write the Conda configuration marker: ${marker_file}" >&2
      rc=1
    fi
  fi
  owner_pid="$(cat "${lock_pid_file}" 2>/dev/null || true)"
  if [ "${owner_pid}" = "$$" ]; then
    rm -f "${lock_pid_file}"
    rmdir "${lock_dir}" 2>/dev/null || true
  fi
  return "${rc}"
}

__daylily_activate_enable_shell_completion() {
  case "$-" in
    *i*) ;;
    *) return 0 ;;
  esac

  if ! command -v dyec >/dev/null 2>&1; then
    echo "Error: DYEC is unavailable for shell-completion setup." >&2
    return 1
  fi

  local completion_script
  if [ -n "${BASH_VERSION:-}" ]; then
    completion_script="$(_DYEC_COMPLETE=source_bash dyec)" || {
      echo "Error: DYEC Bash completion generation failed." >&2
      return 1
    }
  elif [ -n "${ZSH_VERSION:-}" ]; then
    if ! command -v compdef >/dev/null 2>&1; then
      autoload -Uz compinit || {
        echo "Error: unable to load Zsh completion support." >&2
        return 1
      }
      compinit || {
        echo "Error: unable to initialize Zsh completion support." >&2
        return 1
      }
    fi
    completion_script="$(_DYEC_COMPLETE=source_zsh dyec)" || {
      echo "Error: DYEC Zsh completion generation failed." >&2
      return 1
    }
  else
    return 0
  fi

  if [ -z "${completion_script}" ]; then
    echo "Error: DYEC generated an empty shell-completion script." >&2
    return 1
  fi
  eval "${completion_script}"
}

__daylily_activate_ensure_env_bin_first() {
  if [ -z "${CONDA_PREFIX:-}" ] || [ ! -d "${CONDA_PREFIX}/bin" ]; then
    echo "Error: conda did not expose a usable DAY-EC bin directory." >&2
    return 1
  fi

  case ":${PATH}:" in
    :"${CONDA_PREFIX}/bin":*) ;;
    *) PATH="${CONDA_PREFIX}/bin:${PATH}" ;;
  esac
  export PATH
}

__daylily_activate_ensure_repo_pythonpath_first() {
  case ":${PYTHONPATH:-}:" in
    :"${DAYLILY_EC_REPO_ROOT}":*) ;;
    *) PYTHONPATH="${DAYLILY_EC_REPO_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" ;;
  esac
  export PYTHONPATH
}

__daylily_activate_dayec_exists() {
  conda env list 2>/dev/null | awk '{print $1}' | grep -qx 'DAY-EC'
}

__daylily_activate_repo_root="$(
  cd "$(dirname "$(__daylily_activate_script_path)")" && pwd
)"
export DAYLILY_EC_REPO_ROOT="${__daylily_activate_repo_root}"
export DAYLILY_EC_RESOURCES_DIR="${DAYLILY_EC_REPO_ROOT}/daylily_ec/resources/payload"
export DAYLILY_EC_ACTIVE="1"

__daylily_activate_load_conda || {
  echo "Error: conda is not available in this shell." >&2
  return 1
}
__daylily_activate_configure_conda_noninteractive || return 1

__daylily_activate_created_dayec=0
if ! __daylily_activate_dayec_exists; then
  __daylily_activate_env_yaml="${DAYLILY_EC_REPO_ROOT}/environment.yaml"
  if [ ! -f "${__daylily_activate_env_yaml}" ]; then
    echo "Error: DAY-EC bootstrap spec not found at ${__daylily_activate_env_yaml}." >&2
    return 1
  fi

  echo "Creating DAY-EC from ${__daylily_activate_env_yaml} ..." >&2
  conda env create -n DAY-EC -f "${__daylily_activate_env_yaml}" || return 1
  __daylily_activate_created_dayec=1
fi

conda activate DAY-EC || {
  echo "Error: failed to activate the DAY-EC conda environment." >&2
  return 1
}
__daylily_activate_ensure_env_bin_first || return 1
__daylily_activate_ensure_repo_pythonpath_first || return 1
__daylily_activate_refresh_command_cache

if [ "${__daylily_activate_created_dayec}" = "1" ]; then
  echo "Installing daylily-ephemeral-cluster into DAY-EC from ${DAYLILY_EC_REPO_ROOT} ..." >&2
  python -m pip install --editable "${DAYLILY_EC_REPO_ROOT}" || {
    echo "Error: failed to install daylily-ephemeral-cluster into DAY-EC." >&2
    return 1
  }
  __daylily_activate_refresh_command_cache
  echo "Installed daylily-ephemeral-cluster into DAY-EC from ${DAYLILY_EC_REPO_ROOT}." >&2
fi

__daylily_activate_enable_shell_completion || return 1

unset __daylily_activate_created_dayec
unset __daylily_activate_env_yaml
unset __daylily_activate_repo_root
unset -f __daylily_activate_is_sourced
unset -f __daylily_activate_script_path
unset -f __daylily_activate_conda_is_function
unset -f __daylily_activate_conda_exe
unset -f __daylily_activate_load_conda
unset -f __daylily_activate_refresh_command_cache
unset -f __daylily_activate_configure_conda_noninteractive
unset -f __daylily_activate_enable_shell_completion
unset -f __daylily_activate_ensure_env_bin_first
unset -f __daylily_activate_ensure_repo_pythonpath_first
unset -f __daylily_activate_dayec_exists

echo "DAY-EC activated."
