# -*- mode: sh -*-
# shellcheck shell=bash

# A flag to control whether to use omnix from latest github repo or from nixpkgs
OMNIX_FROM_NIXPKGS="${OMNIX_FROM_NIXPKGS:-true}"

# Define OMNIX_BIN based on the flag
if [[ "${OMNIX_FROM_NIXPKGS}" == "true" ]]; then
  OMNIX_BIN="${OMNIX_BIN:-"nix run github:nixos/nixpkgs/4f3a8e6936bb8d3490057ed114738ccb7af6b73b#omnix --"}"
else
  # Fetch omnix only through binary cache from GitHub
  # Hence `-j0`, as well as `--option builders ''` for when there are remote builders.
  OMNIX_BIN="${OMNIX_BIN:-"nix --accept-flake-config --option builders '' -j0 run github:juspay/omnix --"}"
fi

use_omnix() {
  echo "Invoking omnix using: ${OMNIX_BIN}"

  # Run pre-shell stage, which runs health checks and applies changes as necessary.
  ${OMNIX_BIN} develop --stage=pre-shell $* || exit 1

  # Defer to nix-direnv now.
  use flake ${*:-.} --accept-flake-config

  if [[ ! -z "${NIX_DIRENV_DID_FALLBACK:-}" ]]; then
    # Nix shell failed (direnv fell back to previous instance); move on!
    exit
  else
    # Run post-shell stage (prints 'readme')
    ${OMNIX_BIN} develop --stage=post-shell $*
  fi
}
