#!/usr/bin/env bash
# gitroots installer
#
#   curl -fsSL https://gitroots.com/cli/install.sh | bash
#   curl -fsSL https://gitroots.com/cli/install.sh | bash -s -- 0.5.0     # a specific version
#
# Installs a standalone binary (no Node needed) to ~/.local/share/gitroots/versions/<version>
# and links it as ~/.local/bin/gitroots. On platforms without a binary it falls back to the
# npm package when Node 18+ is available.
#
# Environment:
#   GITROOTS_DOWNLOAD_BASE   where releases live (default https://gitroots.com/cli)
#   GITROOTS_VERSION         version to install (default: latest)
#   GITROOTS_NO_MODIFY_PATH  set to 1 to leave shell profiles alone
set -euo pipefail

BASE="${GITROOTS_DOWNLOAD_BASE:-https://gitroots.com/cli}"
BASE="${BASE%/}"
VERSION="${1:-${GITROOTS_VERSION:-latest}}"

if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  G=$'\033[38;5;77m'; M=$'\033[38;5;109m'; W=$'\033[38;5;221m'; R=$'\033[38;5;210m'; B=$'\033[1m'; X=$'\033[0m'
else G=""; M=""; W=""; R=""; B=""; X=""; fi
say()  { printf '%s\n' "$*"; }
ok()   { say "  ${G}✓${X} $*"; }
warn() { say "  ${W}◐${X} $*"; }
die()  { say "  ${R}✕${X} $*" >&2; exit 1; }

# ---- downloader --------------------------------------------------------------
if command -v curl >/dev/null 2>&1; then
  fetch()   { curl -fsSL --retry 2 "$1"; }
  fetchto() { curl -fSL --retry 2 --progress-bar -o "$2" "$1"; }
elif command -v wget >/dev/null 2>&1; then
  fetch()   { wget -qO- "$1"; }
  fetchto() { wget -q --show-progress -O "$2" "$1"; }
else
  die "curl or wget is required"
fi

# ---- platform ----------------------------------------------------------------
case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux)  os=linux ;;
  MINGW*|MSYS*|CYGWIN*) die "on Windows run in PowerShell:  irm ${BASE}/install.ps1 | iex" ;;
  *) die "unsupported OS: $(uname -s)" ;;
esac
case "$(uname -m)" in
  x86_64|amd64) arch=x64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) die "unsupported CPU: $(uname -m)" ;;
esac
# An x64 shell under Rosetta on Apple silicon should still get the native arm64 build.
if [ "$os" = darwin ] && [ "$arch" = x64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 1 ]; then arch=arm64; fi
platform="${os}-${arch}"
if [ "$os" = linux ] && { ldd --version 2>&1 | grep -qi musl || ls /lib/ld-musl-* >/dev/null 2>&1; }; then platform="${platform}-musl"; fi

say ""
say "${G}${B}gitroots${X}  ${M}installer · ${platform}${X}"

# ---- version -----------------------------------------------------------------
if [ "$VERSION" = latest ]; then
  VERSION="$(fetch "${BASE}/latest" | tr -d '[:space:]')" || die "can't reach ${BASE}/latest"
fi
case "$VERSION" in [0-9]*.[0-9]*.[0-9]*) ;; *) die "bad version from ${BASE}/latest: ${VERSION}" ;; esac

SUMS="$(fetch "${BASE}/${VERSION}/SHA256SUMS")" || die "gitroots ${VERSION} not found at ${BASE}/${VERSION}"

sha256() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  else shasum -a 256 "$1" | cut -d' ' -f1; fi
}

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

DATA="${XDG_DATA_HOME:-$HOME/.local/share}/gitroots"
BIN="$HOME/.local/bin"
file="gitroots-${VERSION}-${platform}.tar.gz"
want="$(printf '%s\n' "$SUMS" | awk -v f="$file" '$2==f {print $1}')"

if [ -n "$want" ]; then
  # ---- standalone binary -------------------------------------------------------
  say "  ${M}downloading gitroots ${VERSION}…${X}"
  fetchto "${BASE}/${VERSION}/${file}" "$tmp/$file" || die "download failed"
  got="$(sha256 "$tmp/$file")"
  [ "$got" = "$want" ] || die "checksum mismatch for ${file} · expected ${want}, got ${got} · nothing was installed"
  ok "checksum verified"
  dest="$DATA/versions/$VERSION"
  mkdir -p "$dest" "$BIN"
  tar -xzf "$tmp/$file" -C "$dest"
  chmod 755 "$dest/gitroots"
  ln -sfn "$dest/gitroots" "$BIN/gitroots.new" && mv -f "$BIN/gitroots.new" "$BIN/gitroots"
  # keep this and the previous version
  ls -1 "$DATA/versions" 2>/dev/null | sort -t. -k1,1nr -k2,2nr -k3,3nr | tail -n +3 | while read -r old; do
    [ "$old" != "$VERSION" ] && rm -rf "$DATA/versions/$old"
  done
  ok "installed ${B}gitroots ${VERSION}${X} → ${BIN}/gitroots"
  installed="$BIN/gitroots"
else
  # ---- npm fallback ------------------------------------------------------------
  npmfile="gitroots-${VERSION}.tgz"
  npmsum="$(printf '%s\n' "$SUMS" | awk -v f="$npmfile" '$2==f {print $1}')"
  command -v node >/dev/null 2>&1 && command -v npm >/dev/null 2>&1 || die "no standalone build for ${platform}, and Node 18+ with npm is needed for the fallback"
  major="$(node -p 'process.versions.node.split(".")[0]')"
  [ "$major" -ge 18 ] || die "no standalone build for ${platform} and Node is $(node -v); Node 18+ is needed"
  warn "no standalone build for ${platform} · installing the npm package with Node $(node -v)"
  fetchto "${BASE}/${VERSION}/${npmfile}" "$tmp/$npmfile" || die "download failed"
  [ -z "$npmsum" ] || [ "$(sha256 "$tmp/$npmfile")" = "$npmsum" ] || die "checksum mismatch for ${npmfile}"
  npm install -g "$tmp/$npmfile" >/dev/null || die "npm install -g failed (try again with sudo, or set an npm prefix you own)"
  ok "installed ${B}gitroots ${VERSION}${X} with npm"
  installed="$(command -v gitroots || echo gitroots)"
  BIN=""
fi

# ---- PATH --------------------------------------------------------------------
if [ -n "$BIN" ]; then
  case ":$PATH:" in
    *":$BIN:"*) ;;
    *)
      if [ "${GITROOTS_NO_MODIFY_PATH:-}" = 1 ]; then
        warn "${BIN} is not on your PATH · add:  export PATH=\"${BIN}:\$PATH\""
      else
        shell_name="$(basename "${SHELL:-sh}")"
        case "$shell_name" in
          zsh)  rc="${ZDOTDIR:-$HOME}/.zshrc";  line="export PATH=\"\$HOME/.local/bin:\$PATH\"" ;;
          bash) if [ "$os" = darwin ]; then rc="$HOME/.bash_profile"; else rc="$HOME/.bashrc"; fi; line="export PATH=\"\$HOME/.local/bin:\$PATH\"" ;;
          fish) rc="$HOME/.config/fish/config.fish"; line="fish_add_path \$HOME/.local/bin" ;;
          *)    rc="$HOME/.profile"; line="export PATH=\"\$HOME/.local/bin:\$PATH\"" ;;
        esac
        mkdir -p "$(dirname "$rc")"
        if ! grep -qs '.local/bin' "$rc"; then
          printf '\n# added by the gitroots installer\n%s\n' "$line" >> "$rc"
          ok "added ${BIN} to PATH in ${rc}"
        fi
        warn "open a new terminal, or run:  export PATH=\"${BIN}:\$PATH\""
      fi
      ;;
  esac
fi

if ! err="$("$installed" --version 2>&1)"; then
  case "$err" in
    *"shared libraries"*)
      lib="$(printf '%s' "$err" | sed -n 's/.*libraries: \([^:]*\):.*/\1/p')"
      die "installed, but this system is missing ${lib:-a shared library} · e.g. sudo apt-get install -y libstdc++6 (Debian/Ubuntu) or sudo dnf install -y libstdc++ (Fedora)" ;;
    *) die "installed, but ${installed} --version failed: ${err}" ;;
  esac
fi
say ""
say "  ${G}→ gitroots${X}          ${M}welcome and quick start${X}"
say "  ${G}→ gitroots login${X}    ${M}connect your gitroots server${X}"
say "  ${G}→ gitroots doctor${X}   ${M}check the install${X}"
say ""
