#!/bin/sh
# Simien installer.
#
#   curl -fsSL https://simien.dev/install.sh | sh
#   curl -fsSL https://simien.dev/install.sh | sh -s -- --canary
#
# Installs simien (and its short name, s) into ~/.simien/bin, and
# simien:torch's engine with the libtorch libraries it loads into ~/.simien/lib.
# Options: --stable / --canary, --version X.Y.Z, --install-dir PATH,
# --base-url HTTPS_URL (artifact mirror), --no-modify-path.
# Re-run this installer to update. No sudo is required.
#
# Ported from deka's installer (deka.gg/install.sh): the same channels,
# manifest, checksum check and atomic install, for Simien's releases.

set -eu

# Releases live in R2 (simien-releases), served at this domain. Kept as a
# constant so repointing it is a one-line change.
BASE_URL="https://releases.simien.dev"
INSTALL_DIR="${HOME}/.simien"
SIMIEN_VERSION=""
NO_MODIFY_PATH=0

# --- output -----------------------------------------------------------------
# Colour only when stdout is a terminal; piping to a file or another program
# should not get escape codes.
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  bold=$(printf '\033[1m'); dim=$(printf '\033[2m'); red=$(printf '\033[31m')
  green=$(printf '\033[32m'); reset=$(printf '\033[0m')
else
  bold=''; dim=''; red=''; green=''; reset=''
fi

info() { printf '%s\n' "$*"; }
# Show ~/.simien rather than /home/someone/.simien in user-facing output.
# shellcheck disable=SC2088 # the ~ is printed for people, never expanded
tildify() { case "$1" in "${HOME}"/*) printf '~/%s' "${1#"${HOME}"/}" ;; *) printf '%s' "$1" ;; esac; }
step() { printf '%s==>%s %s\n' "$bold" "$reset" "$*"; }
warn() { printf '%swarning:%s %s\n' "$red" "$reset" "$*" >&2; }

die() {
  printf '%serror:%s %s\n' "$red" "$reset" "$1" >&2
  shift
  for line in "$@"; do printf '  %s\n' "$line" >&2; done
  exit 1
}

need() {
  command -v "$1" >/dev/null 2>&1 || die "'$1' is required but was not found on PATH."
}

need uname
need mkdir

# A small reader for the published release.json, in POSIX tools only (no
# python or jq on a fresh machine). JSON is read flattened onto one line.
# The manifest nests objects (binaries, engines, libtorch.files, each keyed by
# platform), so a key is always looked up inside the object it belongs to:
#   json_flat FILE | json_object binaries | json_object darwin-x64 | json_value sha256
# The manifest's strings hold no braces or escaped quotes.
json_flat() { tr -d '\n' < "$1"; }

json_value() {
  # stdin: flattened JSON; $1 key -> the first "key": "value" string
  grep -o "\"$1\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" | head -n 1 | sed 's/^.*:[[:space:]]*"\(.*\)"$/\1/'
}

json_object() {
  # stdin: flattened JSON; $1 key -> the first {...} that is the value of "key"
  awk -v key="\"$1\"" '{
    s = $0
    while ((i = index(s, key)) > 0) {
      s = substr(s, i + length(key))
      j = index(s, "{")
      if (j > 0 && substr(s, 1, j - 1) ~ /^[ \t]*:[ \t]*$/) {
        s = substr(s, j); d = 0
        for (k = 1; k <= length(s); k++) {
          c = substr(s, k, 1)
          if (c == "{") d++
          else if (c == "}") { d--; if (d == 0) { print substr(s, 1, k); exit } }
        }
        exit
      }
    }
  }'
}

json_pairs() {
  # stdin: one flattened {"a": "x", "b": "y"} -> lines "a x"
  grep -o '"[^"]*"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/^"\([^"]*\)"[[:space:]]*:[[:space:]]*"\([^"]*\)"$/\1 \2/'
}

json_string() {
  # json_string FILE key -> the first "key": "value" in the file (the
  # manifest's top-level name and version come before any nested object)
  json_flat "$1" | json_value "$2"
}

sha256_file() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | cut -d' ' -f1
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | cut -d' ' -f1
  else
    die "Neither sha256sum nor shasum is available; cannot verify the download."
  fi
}

# Everything below runs inside main(), invoked on the very last line. That
# matters for `curl ... | sh`: if the connection drops mid-transfer, sh runs
# whatever bytes arrived. Top-level statements would run half a script,
# possibly having downloaded but not verified. Defining functions and calling
# main() last means a truncated file defines some functions and does nothing.

main() {
  # --- channel ----------------------------------------------------------------
  # A flag, not an environment variable: the channel is decided at the
  # curl|sh call site (`sh -s -- --canary`), not left in a shell profile.
  CHANNEL='stable'
  while [ "$#" -gt 0 ]; do
    case "$1" in
      --canary) CHANNEL='canary' ;;
      --stable) CHANNEL='stable' ;;
      --no-modify-path) NO_MODIFY_PATH=1 ;;
      --version|--install-dir|--base-url)
        option="$1"
        shift
        [ "$#" -gt 0 ] || die "Missing value for ${option}"
        case "$option" in
          --version) SIMIEN_VERSION="$1" ;;
          --install-dir) INSTALL_DIR="$1" ;;
          --base-url) BASE_URL="$1" ;;
        esac
        ;;
      *) die "Usage: install.sh [--stable|--canary] [--version VERSION] [--install-dir PATH] [--base-url HTTPS_URL] [--no-modify-path]" ;;
    esac
    shift
  done
  case "$BASE_URL" in https://*) ;; *) die "The artifact mirror must use HTTPS." ;; esac
  BIN_DIR="${INSTALL_DIR}/bin"

  # --- platform ---------------------------------------------------------------
  # Simien publishes three builds:
  #   macOS  x86_64   -> darwin-x64
  #   macOS  arm64    -> darwin-arm64
  #   Linux  x86_64   -> linux-x64
  # Anything else is a clear error, not a download that 404s. OS and arch are
  # checked as a pair.
  os=$(uname -s)
  arch=$(uname -m)

  case "$os" in
    Linux|Darwin) ;;
    MINGW*|MSYS*|CYGWIN*|Windows_NT)
      die "Windows is not supported." \
          "Run this inside WSL (Windows Subsystem for Linux) instead:" \
          "  wsl --install" \
          "  curl -fsSL https://simien.dev/install.sh | sh"
      ;;
    *)
      die "${os} is not supported." \
          "Simien publishes builds for macOS and Linux." \
          "Track platform support: https://github.com/simienapp/runtime/issues"
      ;;
  esac

  case "${os}/${arch}" in
    Darwin/x86_64|Darwin/amd64)   PLATFORM='darwin-x64' ;;
    Darwin/arm64|Darwin/aarch64)  PLATFORM='darwin-arm64' ;;
    Linux/x86_64|Linux/amd64)     PLATFORM='linux-x64' ;;
    Linux/aarch64|Linux/arm64)
      # Common in Docker on Apple Silicon, where the daemon defaults to
      # linux/arm64; the fix there is a flag, not another machine.
      die "Linux on ARM (${arch}) is not supported yet." \
          "Simien publishes: macOS x86_64, macOS arm64, Linux x86_64." \
          "" \
          "In Docker on an Apple Silicon Mac, ask for an x86_64 image:" \
          "  docker run --platform linux/amd64 ..." \
          "" \
          "Follow Linux ARM support: https://github.com/simienapp/runtime/issues"
      ;;
    *)
      die "Unsupported platform: ${os} ${arch}" \
          "Simien publishes: macOS x86_64 (Intel), macOS arm64 (Apple Silicon), Linux x86_64." \
          "" \
          "Include this when reporting:" \
          "  uname -a: $(uname -a 2>/dev/null || echo unavailable)" \
          "  https://github.com/simienapp/runtime/issues"
      ;;
  esac

  # Under Rosetta 2, `uname -m` says x86_64 on an Apple Silicon Mac, so the
  # Intel build would be picked and run emulated. Ask whether this process is
  # translated and install the native build instead.
  if [ "$PLATFORM" = 'darwin-x64' ] && \
     [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = '1' ]; then
    PLATFORM='darwin-arm64'
    info "  Detected Rosetta 2; installing the native arm64 build."
  fi

  # --- downloader -------------------------------------------------------------
  # curl and wget disagree on flags; normalise to `fetch <url> <dest>`.
  if command -v curl >/dev/null 2>&1; then
    fetch() { curl -fsSL --retry 3 --proto '=https' --tlsv1.2 -o "$2" "$1"; }
  elif command -v wget >/dev/null 2>&1; then
    fetch() { wget -q --https-only --tries=3 -O "$2" "$1"; }
  else
    die "Either curl or wget is required."
  fi

  tmp=$(mktemp -d 2>/dev/null || mktemp -d -t simien-install)
  cleanup() { rm -rf "$tmp"; }
  trap cleanup EXIT INT TERM HUP

  # --- version ----------------------------------------------------------------
  if [ -z "$SIMIEN_VERSION" ]; then
    case "$CHANNEL" in
      canary)
        step "Resolving simien version (canary)"
        fetch "${BASE_URL}/canary.json" "${tmp}/release.json" || die \
          "No canary build has been published yet (${BASE_URL}/canary.json not found)."
        ;;
      *)
        step "Resolving simien version (stable)"
        fetch "${BASE_URL}/latest.json" "${tmp}/release.json" || die \
          "No stable release of simien yet (${BASE_URL}/latest.json not found)." \
          "Install the newest canary build instead:" \
          "  curl -fsSL https://simien.dev/install.sh | sh -s -- --canary"
        ;;
    esac
    SIMIEN_VERSION=$(json_string "${tmp}/release.json" version)
    [ -n "$SIMIEN_VERSION" ] || die "Could not read the version from the ${CHANNEL} manifest."
  fi
  case "$SIMIEN_VERSION" in v*) SIMIEN_VERSION="${SIMIEN_VERSION#v}" ;; esac

  # Release directories are the full version with no "v", in every channel:
  # 0.61.0/release.json and 0.61.0-canary-906f051/release.json (the git tag
  # has the v, the path does not). A pinned --version that is a canary
  # resolves either way.
  if [ ! -f "${tmp}/release.json" ] || [ "$(json_string "${tmp}/release.json" version)" != "$SIMIEN_VERSION" ]; then
    fetch "${BASE_URL}/${SIMIEN_VERSION}/release.json" "${tmp}/release.json" || die \
      "Could not download the simien ${SIMIEN_VERSION} manifest:" \
      "  ${BASE_URL}/${SIMIEN_VERSION}/release.json"
  fi

  [ "$(json_string "${tmp}/release.json" name)" = "simien" ] || die "This manifest is not a simien release."
  [ "$(json_string "${tmp}/release.json" version)" = "$SIMIEN_VERSION" ] || die "Release manifest version mismatch."
  BINARY="simien-${PLATFORM}"
  URL="${BASE_URL}/${SIMIEN_VERSION}/${BINARY}"
  SHA=$(json_flat "${tmp}/release.json" | json_object binaries | json_object "$PLATFORM" | json_value sha256)
  [ -n "$SHA" ] || die "simien ${SIMIEN_VERSION} has no ${PLATFORM} checksum in its release manifest."

  # simien:torch's engine and the libtorch libraries it loads, installed in
  # lib/ beside bin/ (the binary looks for the engine in ../lib). Releases
  # before 0.62 have no engine, and then only the binary is installed.
  ENGINE_NAME=$(json_flat "${tmp}/release.json" | json_object engines | json_object "$PLATFORM" | json_value name)
  ENGINE_SHA=$(json_flat "${tmp}/release.json" | json_object engines | json_object "$PLATFORM" | json_value sha256)
  LIBTORCH_PATH=$(json_flat "${tmp}/release.json" | json_object libtorch | json_value path)
  json_flat "${tmp}/release.json" | json_object libtorch | json_object files | json_object "$PLATFORM" | json_pairs > "${tmp}/libtorch-files"
  LIB_DIR="${INSTALL_DIR}/lib"
  if [ -n "$ENGINE_NAME" ]; then
    [ -n "$ENGINE_SHA" ] && [ -n "$LIBTORCH_PATH" ] && [ -s "${tmp}/libtorch-files" ] || \
      die "simien ${SIMIEN_VERSION}'s manifest names a ${PLATFORM} engine but not all of its files."
    case "$ENGINE_NAME" in *.dylib) ENGINE_FILE='libsimien_torch.dylib' ;; *) ENGINE_FILE='libsimien_torch.so' ;; esac
  fi

  info ""
  info "  ${bold}simien${reset} v${SIMIEN_VERSION}"
  info "  ${dim}${PLATFORM}${reset}"
  info "  ${dim}$(tildify "${BIN_DIR}")${reset}"
  info ""

  # --- download and verify ----------------------------------------------------
  step "Downloading ${BINARY}"
  fetch "$URL" "${tmp}/simien" || die \
    "Download failed: ${URL}" \
    "That version may not publish a build for ${PLATFORM}."

  step "Verifying checksum"
  actual=$(sha256_file "${tmp}/simien")
  if [ "$SHA" != "$actual" ]; then
    die "Checksum mismatch for simien; refusing to install." \
        "expected: ${SHA}" \
        "actual:   ${actual}" \
        "" \
        "This can mean a corrupted download, or a tampered artifact." \
        "Please report it: https://github.com/simienapp/runtime/issues"
  fi

  # A file of the engine or libtorch: reuse an installed copy whose checksum
  # already matches (libtorch is a few hundred MB and rarely changes),
  # otherwise download and verify it. Everything lands in ${tmp}/lib first.
  mkdir -p "${tmp}/lib"
  fetch_verified() {
    # fetch_verified URL INSTALLED_NAME SHA256
    if [ -f "${LIB_DIR}/$2" ] && [ "$(sha256_file "${LIB_DIR}/$2")" = "$3" ]; then
      cp "${LIB_DIR}/$2" "${tmp}/lib/$2"
      return 0
    fi
    fetch "$1" "${tmp}/lib/$2" || die "Download failed: $1"
    got=$(sha256_file "${tmp}/lib/$2")
    [ "$got" = "$3" ] || die "Checksum mismatch for $2; refusing to install." \
      "expected: $3" "actual:   ${got}" "" \
      "This can mean a corrupted download, or a tampered artifact."
  }
  if [ -n "$ENGINE_NAME" ]; then
    step "Downloading simien:torch's engine"
    fetch_verified "${BASE_URL}/${SIMIEN_VERSION}/${ENGINE_NAME}" "$ENGINE_FILE" "$ENGINE_SHA"
    step "Downloading libtorch (PyTorch's C++ library; reused if already installed)"
    while read -r lib_name lib_sha; do
      fetch_verified "${BASE_URL}/${LIBTORCH_PATH}/${PLATFORM}/${lib_name}" "$lib_name" "$lib_sha"
    done < "${tmp}/libtorch-files"
  fi

  chmod 755 "${tmp}/simien"
  banner=$("${tmp}/simien" --version 2>&1) || die "The downloaded simien did not run."
  base_version="${SIMIEN_VERSION%%-canary-*}"
  case "$banner" in
    *"\"version\": \"${base_version}\""*) ;;
    *) die "The downloaded simien reports a different version: ${banner}" ;;
  esac

  # --- install ----------------------------------------------------------------
  step "Installing to $(tildify "${INSTALL_DIR}")"
  mkdir -p "$BIN_DIR"
  # lib/ first, so a binary that needs the engine never lands without it.
  # Each file is renamed into place, like the binary below.
  if [ -n "$ENGINE_NAME" ]; then
    mkdir -p "$LIB_DIR"
    for staged in "${tmp}/lib/"*; do
      lib_name=$(basename "$staged")
      mv -f "$staged" "${LIB_DIR}/.${lib_name}.tmp"
      mv -f "${LIB_DIR}/.${lib_name}.tmp" "${LIB_DIR}/${lib_name}"
    done
  fi
  # Write to a temp name and rename, so an interrupted install cannot leave a
  # half-written binary, and replacing a running simien works (rename swaps
  # the inode rather than rewriting it).
  mv -f "${tmp}/simien" "${BIN_DIR}/.simien.tmp"
  mv -f "${BIN_DIR}/.simien.tmp" "${BIN_DIR}/simien"
  # s is the same program under a shorter name.
  ln -sf simien "${BIN_DIR}/s"

  "${BIN_DIR}/simien" --version >/dev/null 2>&1 || die "simien was installed but does not run from $(tildify "${BIN_DIR}")."

  # --- PATH -------------------------------------------------------------------
  already_on_path=0
  case ":${PATH}:" in *":${BIN_DIR}:"*) already_on_path=1 ;; esac

  # Write $HOME rather than the expanded path when possible, so a profile
  # stays valid if the home directory moves.
  if [ "${BIN_DIR#"${HOME}/"}" != "$BIN_DIR" ]; then
    path_literal="\$HOME/${BIN_DIR#"${HOME}"/}"
  else
    path_literal="$BIN_DIR"
  fi

  # Only touch the profile of the shell the user runs: POSIX `export` in a
  # fish config is a syntax error.
  shell_name=$(basename "${SHELL:-sh}")
  added_to=''

  append_profile() {
    target_file="$1"
    target_line="$2"
    [ -e "$target_file" ] || touch "$target_file" 2>/dev/null || return 0
    [ -w "$target_file" ] || { warn "Cannot write ${target_file}; skipping PATH setup there."; return 0; }
    grep -Fq "$BIN_DIR" "$target_file" 2>/dev/null && return 0
    printf '\n# Simien\n%s\n' "$target_line" >> "$target_file" || return 0
    added_to="${added_to} ${target_file##*/}"
  }

  if [ "$already_on_path" -eq 0 ] && [ "$NO_MODIFY_PATH" -eq 0 ]; then
    case "$shell_name" in
      fish)
        fish_config="${XDG_CONFIG_HOME:-${HOME}/.config}/fish/config.fish"
        mkdir -p "$(dirname "$fish_config")" 2>/dev/null || true
        append_profile "$fish_config" "set -gx PATH ${path_literal} \$PATH"
        ;;
      zsh)
        append_profile "${ZDOTDIR:-$HOME}/.zshrc" "export PATH=\"${path_literal}:\$PATH\""
        ;;
      bash)
        # bash reads .bash_profile on macOS login shells and .bashrc on Linux;
        # writing whichever exists covers both without inventing files.
        for f in "${HOME}/.bashrc" "${HOME}/.bash_profile"; do
          [ -f "$f" ] && append_profile "$f" "export PATH=\"${path_literal}:\$PATH\""
        done
        [ -z "$added_to" ] && append_profile "${HOME}/.bashrc" "export PATH=\"${path_literal}:\$PATH\""
        ;;
      *)
        append_profile "${HOME}/.profile" "export PATH=\"${path_literal}:\$PATH\""
        ;;
    esac
  fi

  # --- done -------------------------------------------------------------------
  info ""
  info "  ${green}Installed${reset} simien v${SIMIEN_VERSION} (also as s)"
  info ""
  if [ "$already_on_path" -eq 1 ]; then
    info "  Start an app: ${bold}simien init my-app${reset}"
  elif [ -n "$added_to" ]; then
    info "  Added to PATH in:${added_to}"
    info "  Restart your shell, or run:"
    info ""
    info "    ${bold}export PATH=\"${BIN_DIR}:\$PATH\"${reset}"
    info ""
    info "  Then start an app: ${bold}simien init my-app${reset}"
  else
    info "  Add this to your shell profile:"
    info ""
    info "    ${bold}export PATH=\"${BIN_DIR}:\$PATH\"${reset}"
  fi
  info ""
  info "  ${dim}Docs: https://simien.dev/docs/first-app/${reset}"
  info ""
}

main "$@"
