#!/bin/sh
# Install the yugos command: yugos claude, yugos codex, yugos pi, yugos opencode.
#
#   curl -fsSL https://www.yugos.ai/install.sh | sh
#
# Downloads one script (setup/yugos-clients.py) to ~/.local/bin/yugos and
# verifies it against its published SHA-256. If that folder is not on your PATH,
# writes ~/.local/share/yugos/env and sources it from your shell profile
# (~/.zshrc, ~/.bashrc or ~/.profile), and for fish writes
# ~/.config/fish/conf.d/yugos.fish; set YUGOS_NO_MODIFY_PATH=1 to skip that. It
# changes no client configuration and stores no key: yugos reads YUGOS_API_KEY
# from your environment or a project .env when it starts. Set YUGOS_INSTALL_DIR
# to install elsewhere. It runs yugos with the newest Python 3.11+ it finds on
# PATH or through uv (or YUGOS_PYTHON). Rerun to update.
set -eu

# The profile a POSIX shell reads; empty for fish and shells without a safe default.
shell_profile() {
  case "$(basename "${SHELL:-}")" in
    zsh) printf '%s/.zshrc' "${ZDOTDIR:-$HOME}" ;;
    bash)
      if [ -f "$HOME/.bashrc" ]; then
        printf '%s/.bashrc' "$HOME"
      else
        printf '%s/.profile' "$HOME"
      fi
      ;;
    sh | dash | ksh) printf '%s/.profile' "$HOME" ;;
    *) ;;
  esac
}

fail() {
  printf 'yugos install: %s\n' "$1" >&2
  exit 1
}

sha256() {
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | cut -d' ' -f1
  elif command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | cut -d' ' -f1
  else
    fail "shasum or sha256sum is required to verify the download"
  fi
}

# Print the interpreter behind $1 if it is Python 3.11+, resolved out of any
# virtualenv, so yugos keeps working when that environment changes.
python_ok() {
  "$1" -c 'import sys
if sys.version_info < (3, 11): sys.exit(1)
print(getattr(sys, "_base_executable", "") or sys.executable)' 2>/dev/null
}

# Absolute path of a Python 3.11+: YUGOS_PYTHON, else the newest on PATH, else
# one that uv manages.
find_python() {
  for candidate in ${YUGOS_PYTHON:-python3.14 python3.13 python3.12 python3.11 python3}; do
    found="$(command -v "$candidate" 2>/dev/null)" || continue
    python_ok "$found" && return 0
  done
  if [ -z "${YUGOS_PYTHON:-}" ] && command -v uv >/dev/null 2>&1; then
    found="$(uv python find '>=3.11' 2>/dev/null)" && python_ok "$found" && return 0
  fi
  return 1
}

# $1 written as $HOME/... when it is under the home directory.
home_relative() {
  case "$1" in
    "$HOME"/*) printf '$HOME/%s' "${1#"$HOME"/}" ;;
    *) printf '%s' "$1" ;;
  esac
}

# Put $1 on PATH for new terminals: an env file sourced once from the POSIX
# shell profile, and a conf.d file for fish when fish is in use.
add_to_path() {
  dir_ref="$(home_relative "$1")"
  manual="export PATH=\"$dir_ref:\$PATH\""
  if [ "${YUGOS_NO_MODIFY_PATH:-}" = "1" ]; then
    printf '\nAdd %s to your PATH, for example in your shell profile:\n  %s\n' "$1" "$manual"
    return
  fi
  ready=""

  profile="$(shell_profile)"
  if [ -n "$profile" ]; then
    data="${XDG_DATA_HOME:-$HOME/.local/share}/yugos"
    mkdir -p "$data"
    {
      printf '# Written by the yugos installer: adds %s to PATH once.\n' "$dir_ref"
      printf 'case ":${PATH}:" in\n'
      printf '  *:"%s":*) ;;\n' "$dir_ref"
      printf '  *) export PATH="%s:$PATH" ;;\n' "$dir_ref"
      printf 'esac\n'
    } >"$data/env"
    source_line=". \"$(home_relative "$data/env")\""
    if [ -f "$profile" ] && grep -qF "$source_line" "$profile"; then
      printf '\n%s already loads yugos onto your PATH.\n' "$profile"
    else
      printf '\n# yugos\n%s\n' "$source_line" >>"$profile"
      printf '\nAdded %s to your PATH in %s.\n' "$1" "$profile"
    fi
    ready="$source_line"
  fi

  fish_conf="${XDG_CONFIG_HOME:-$HOME/.config}/fish"
  if [ "$(basename "${SHELL:-}")" = "fish" ] || [ -d "$fish_conf" ]; then
    mkdir -p "$fish_conf/conf.d"
    {
      printf '# Written by the yugos installer: adds %s to PATH once.\n' "$dir_ref"
      printf 'if not contains -- "%s" $PATH\n' "$dir_ref"
      printf '    set -gx PATH "%s" $PATH\n' "$dir_ref"
      printf 'end\n'
    } >"$fish_conf/conf.d/yugos.fish"
    printf '\nAdded %s to your PATH for fish in %s.\n' "$1" "$fish_conf/conf.d/yugos.fish"
    [ -n "$ready" ] || ready="source $fish_conf/conf.d/yugos.fish"
  fi

  if [ -n "$ready" ]; then
    printf 'Open a new terminal, or run now: %s\n' "$ready"
  else
    printf '\nAdd %s to your PATH, for example in your shell profile:\n  %s\n' "$1" "$manual"
  fi
}

# Everything runs from main, called on the last line, so a truncated download
# runs nothing.
main() {
  site="${YUGOS_SITE_ORIGIN:-https://www.yugos.ai}"
  bin="${YUGOS_INSTALL_DIR:-$HOME/.local/bin}"

  command -v curl >/dev/null 2>&1 || fail "curl is required"
  command -v shasum >/dev/null 2>&1 || command -v sha256sum >/dev/null 2>&1 ||
    fail "shasum or sha256sum is required to verify the download"
  if ! python="$(find_python)"; then
    if command -v uv >/dev/null 2>&1; then
      fail "Python 3.11 or newer is required. Run: uv python install 3.13, then rerun"
    fi
    fail "Python 3.11 or newer is required. Install one (for example: brew install python@3.13, or apt install python3.11), or set YUGOS_PYTHON to its path, then rerun"
  fi

  mkdir -p "$bin"
  download="$(mktemp "${TMPDIR:-/tmp}/yugos-clients.XXXXXX")"
  digest="$(mktemp "${TMPDIR:-/tmp}/yugos-clients-sha256.XXXXXX")"
  trap 'rm -f "$download" "$digest"' EXIT
  curl --fail --silent --show-error --location "$site/setup/yugos-clients.py" -o "$download" ||
    fail "could not download $site/setup/yugos-clients.py"
  curl --fail --silent --show-error --location "$site/setup/yugos-clients.py.sha256" -o "$digest" ||
    fail "could not download $site/setup/yugos-clients.py.sha256"
  expected="$(cut -d' ' -f1 "$digest")"
  printf '%s\n' "$expected" | grep -Eq '^[0-9a-f]{64}$' ||
    fail "the published checksum is not a SHA-256 digest"
  [ "$(sha256 "$download")" = "$expected" ] ||
    fail "checksum verification failed; nothing was installed"

  # Run with the interpreter checked above, not whichever python3 is first on
  # PATH later (an older system Python, a virtualenv).
  installed="$(mktemp "$bin/.yugos.XXXXXX")"
  trap 'rm -f "$download" "$digest" "$installed"' EXIT
  { printf '#!%s\n' "$python"; tail -n +2 "$download"; } >"$installed"
  chmod 755 "$installed"
  mv "$installed" "$bin/yugos"
  rm -f "$download" "$digest"
  trap - EXIT

  printf 'Installed yugos in %s (checksum verified, using %s)\n' "$bin" "$python"
  for client in claude codex pi opencode; do
    if command -v "$client" >/dev/null 2>&1; then
      printf '  yugos %s: ready\n' "$client"
    else
      printf '  yugos %s: install %s first\n' "$client" "$client"
    fi
  done

  case ":$PATH:" in
    *":$bin:"*) ;;
    *) add_to_path "$bin" ;;
  esac

  if [ -n "${YUGOS_API_KEY:-}${YUGO_API_KEY:-}" ]; then
    printf '\nChecking your key:\n'
    "$bin/yugos" check || true
  else
    printf '\nNext: set YUGOS_API_KEY (a project key from the Yugos console) by exporting it,\n'
    printf 'or in a .env in your project folder (or any folder above it), then run: yugos check\n'
  fi
}

main "$@"
