#!/bin/sh
# Installs the omarchy-pets command line: one file under ~/.local/bin, checked against its published SHA-256.
# Everything runs from main, called on the last line, so a download cut short runs nothing.
set -eu

fail() { echo "omarchy-pets: $1" >&2; exit 1; }

main() {
  base="${OMARCHY_PETS_BASE:-https://omarchy-pets.com}"
  bin="$HOME/.local/bin"
  tmp=$(mktemp)
  trap 'rm -f "$tmp"' EXIT

  if command -v sha256sum >/dev/null 2>&1; then digest() { sha256sum "$1" | cut -d' ' -f1; }
  elif command -v shasum >/dev/null 2>&1; then digest() { shasum -a 256 "$1" | cut -d' ' -f1; }
  else fail "neither sha256sum nor shasum is installed"; fi

  curl -fsSL "$base/cli/omarchy-pets" -o "$tmp" || fail "could not download $base/cli/omarchy-pets"
  expected=$(curl -fsSL "$base/cli/omarchy-pets.sha256" | cut -d' ' -f1) || fail "could not download $base/cli/omarchy-pets.sha256"
  [ "$(digest "$tmp")" = "$expected" ] || fail "the download does not match $base/cli/omarchy-pets.sha256"

  mkdir -p "$bin"
  install -m 755 "$tmp" "$bin/omarchy-pets"
  echo "Installed $bin/omarchy-pets ($("$bin/omarchy-pets" --version))" >&2

  case ":$PATH:" in
    *":$bin:"*) ;;
    *)
      # fish: a universal variable, so every running fish shell sees it now. bash and zsh: a marked line in the startup file of each shell that is installed, read by the next shell.
      if command -v fish >/dev/null 2>&1; then fish -c 'contains -- $argv[1] $fish_user_paths || fish_add_path -U $argv[1]' "$bin"; fi
      for shell in bash zsh; do
        command -v "$shell" >/dev/null 2>&1 || continue
        rc="$HOME/.${shell}rc"
        [ -f "$rc" ] && grep -q '# omarchy-pets' "$rc" && continue
        printf '\nexport PATH="$HOME/.local/bin:$PATH" # omarchy-pets\n' >>"$rc"
      done
      echo "Added $bin to PATH: fish has it now, bash and zsh in their next terminal." >&2
      ;;
  esac

  # The first run makes ~/.omarchy-pets/pets and offers to copy the Codex pets; it needs the terminal, not the pipe.
  if ( : </dev/tty ) 2>/dev/null; then "$bin/omarchy-pets" list </dev/tty; fi
}

main "$@"
