#!/bin/sh
# Build the pinned Raxol payments package and run the local fixture.
# Run from a fresh project directory containing the downloaded starter files.
# Usage: sh setup.sh [all|source|toolchain|build|fixture]   (default: all)
set -eu

revision=74c5796f33b449310e841d6325c647f6d7a83952
project=$(pwd -P)
repo="$project/raxol-agent"
package="$repo/packages/raxol_payments"
state="$project/.start"
toolchain_file="$state/toolchain"

# One line saying what failed, one line saying what to run next.
die() {
  printf 'setup: %s\n' "$1" >&2
  if [ -n "${2:-}" ]; then
    printf 'fix:   %s\n' "$2" >&2
  fi
  exit 1
}

fetch_source() {
  if [ ! -d "$repo/.git" ]; then
    git clone https://github.com/DROOdotFOO/raxol-agent.git "$repo" ||
      die "git clone of raxol-agent failed" "check the network, then rerun in an empty folder"
    git -C "$repo" checkout --detach "$revision" ||
      die "could not check out the pinned revision $revision" "start again in an empty folder"
  fi
  [ "$(git -C "$repo" rev-parse HEAD)" = "$revision" ] ||
    die "raxol-agent is not at the pinned revision $revision" "start again in an empty folder; never move the pin"
  [ -z "$(git -C "$repo" status --porcelain --untracked-files=no)" ] ||
    die "raxol-agent has local changes" "start again in an empty folder"
}

# The fix line depends on how the machine provides Elixir.
toolchain_fix() {
  if command -v mise >/dev/null 2>&1; then
    printf '%s' "(cd raxol-agent && mise trust && mise install)"
  else
    printf '%s' "install Elixir 1.20.2 on Erlang/OTP 29 (pinned in raxol-agent/mise.toml), then rerun"
  fi
}

# Ask the VM that the repo actually resolves to where it lives, and which Mix
# home it was handed. This works the same for mise, asdf, Homebrew or a plain
# install, and lets every later step call that exact toolchain instead of
# whatever a shim or PATH picks. (mise's shell activation exports MIX_HOME for
# the folder you are in, so the Mix home has to come from inside the repo too.)
probe_toolchain() {
  # shellcheck disable=SC2016
  probe='IO.puts("elixir=#{System.version()}\notp=#{:erlang.system_info(:otp_release)}\nerlang_bin=#{Path.join(:code.root_dir(), "bin")}\nelixir_bin=#{Path.expand("../../bin", :code.lib_dir(:elixir))}\nmix_home=#{System.get_env("MIX_HOME")}\nmix_archives=#{System.get_env("MIX_ARCHIVES")}")'
  (cd "$package" && elixir --eval "$probe") 2>"$state/toolchain.err"
}

# One recorded value from the toolchain file.
recorded() {
  sed -n "s/^$1=//p" "$toolchain_file"
}

# Put the recorded toolchain first on PATH and hand mix the same Mix home.
use_toolchain() {
  PATH="$(recorded path):$PATH"
  export PATH
  for name in MIX_HOME MIX_ARCHIVES; do
    value=$(recorded "$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')")
    if [ -n "$value" ]; then
      export "$name=$value"
    else
      unset "$name"
    fi
  done
}

check_toolchain() {
  for tool in git make cc; do
    command -v "$tool" >/dev/null 2>&1 || die "missing required tool: $tool" "install $tool, then rerun"
  done
  command -v elixir >/dev/null 2>&1 || die "no elixir on PATH" "$(toolchain_fix)"
  mkdir -p "$state"
  if ! probe_toolchain >"$toolchain_file.new"; then
    case "$(cat "$state/toolchain.err")" in
      *"not trusted"*) die "mise will not use raxol-agent/mise.toml until you trust it" "$(toolchain_fix)" ;;
      *"not installed"* | *"No version is set"*) die "the pinned toolchain is not installed" "$(toolchain_fix)" ;;
      *) die "elixir failed inside raxol-agent: $(head -n 1 "$state/toolchain.err")" "$(toolchain_fix)" ;;
    esac
  fi
  version=$(sed -n 's/^elixir=//p' "$toolchain_file.new")
  otp=$(sed -n 's/^otp=//p' "$toolchain_file.new")
  elixir_bin=$(sed -n 's/^elixir_bin=//p' "$toolchain_file.new")
  erlang_bin=$(sed -n 's/^erlang_bin=//p' "$toolchain_file.new")
  case "$version:$otp" in
    1.20.*:29) ;;
    *) die "need Elixir 1.20.x on Erlang/OTP 29 inside raxol-agent; found Elixir $version on OTP $otp" "$(toolchain_fix)" ;;
  esac
  [ -x "$elixir_bin/mix" ] && [ -x "$erlang_bin/erl" ] ||
    die "could not locate mix and erl for Elixir $version" "$(toolchain_fix)"
  {
    cat "$toolchain_file.new"
    printf 'path=%s:%s\n' "$elixir_bin" "$erlang_bin"
  } >"$toolchain_file"
  rm -f "$toolchain_file.new"
  # From here on, mix is the resolved binary, never a shim.
  use_toolchain
}

install_mix_tools() {
  (cd "$package" && mix local.hex --force --if-missing && mix local.rebar --force --if-missing) ||
    die "could not install Hex and Rebar" "check the network, then rerun"
}

build() {
  cd "$package"
  MIX_ENV=dev
  export MIX_ENV
  mix deps.get || die "mix deps.get failed" "check the network, then rerun"
  git diff --exit-code -- mix.lock >/dev/null ||
    die "mix deps.get changed mix.lock" "start again in an empty folder; never update the lockfile"
  mix compile || die "mix compile failed" "start again in an empty folder; never change a pin to get past it"
}

require_build() {
  [ -d "$package/_build/dev" ] || die "no build found in raxol-agent" "sh setup.sh"
}

# contributor.exs keeps Raxol's local data inside this project itself; exporting
# XDG here would send a mise shim looking for its installs in the wrong folder.
run_fixture() {
  cd "$package"
  MIX_ENV=dev mix run --no-start --no-compile "$project/contributor.exs"
}

main() {
  # Everything this creates (the clone, .start/) belongs next to the starter files.
  [ -f "$project/setup.sh" ] && [ -f "$project/contributor.exs" ] ||
    die "run setup.sh from the starter folder, not $project" "cd into the folder that holds setup.sh, then rerun"
  case "${1:-all}" in
    all)
      fetch_source
      check_toolchain
      install_mix_tools
      build
      run_fixture
      ;;
    source) fetch_source ;;
    toolchain)
      fetch_source
      check_toolchain
      install_mix_tools
      printf 'Elixir %s on Erlang/OTP %s\n' "$version" "$otp"
      ;;
    build)
      fetch_source
      check_toolchain
      build
      ;;
    fixture)
      require_build
      check_toolchain
      run_fixture
      ;;
    *)
      printf 'usage: sh setup.sh [all|source|toolchain|build|fixture]\n' >&2
      exit 2
      ;;
  esac
}

main "$@"
