#!/bin/sh
# SBOMBox installer: the `sbombox` CLI plus an SBOM generator, in one step.
#
#   curl -fsSL https://sbombox.com/install.sh | sh
#
# By default this installs:
#   * the sbombox CLI, as an isolated tool managed by uv (uv is installed first
#     if missing, and fetches Python 3.12+ itself, so no system Python is needed);
#   * SBOM generators, all pinned to tested versions:
#       - syft: one binary that reads every supported ecosystem, verified
#         against its published SHA-256 checksum;
#       - cyclonedx-py: the native Python generator (installed through uv);
#       - cyclonedx-npm: the native npm generator, only if Node.js 20+ is
#         present and its npm is older than 9.5. npm 9.5+, pnpm 11.1+ and
#         uv 0.9.11+ make SBOMs themselves, so nothing is installed for them.
#     Tools already installed are left alone. sbombox picks the most accurate
#     one for each project: the package manager's own `sbom` command when the
#     lockfile is present, then the native tool for a single-language project,
#     and a universal tool (cdxgen if installed, else syft) for multi-language
#     ones. To force a choice at run time: SBOMBOX_GENERATOR=npm-sbom,syft
#
# Nothing needs root. Running it again upgrades in place.
#
# Advanced: set any of these in front of `sh`, e.g.
#   curl -fsSL https://sbombox.com/install.sh | SBOMBOX_GENERATORS=all sh
#
#   SBOMBOX_VERSION=0.2.0          Pin a CLI version (e.g. for reproducible CI).
#                                  Default: the current version published by
#                                  SBOMBox. Versions below the server's minimum
#                                  are refused (the API would reject them).
#   SBOMBOX_GENERATORS=auto        Generators to install, comma-separated:
#                                  syft, cyclonedx-py, cyclonedx-npm, cdxgen,
#                                  auto, all or none. Default: auto (see above).
#                                  cdxgen (Node.js 24+) is the most thorough
#                                  for Java/Gradle projects but much slower.
#   SBOMBOX_SYFT_VERSION=v1.57.1   syft version to install.
#   SBOMBOX_BIN_DIR=DIR            Where to put syft. Default: uv's tool bin
#                                  directory (usually ~/.local/bin).
#   SBOMBOX_SKIP_CLI=1             Only install generators (CLI already present).
#   SBOMBOX_NO_MODIFY_PATH=1       Do not edit shell profiles to update PATH.
#   SBOMBOX_API_URL=URL            Self-hosted SBOMBox: where to read the CLI
#                                  version policy. Default: https://api.sbombox.com
set -eu

PACKAGE="sbombox"
MIN_PYTHON="3.12"
DEFAULT_SYFT_VERSION="v1.57.1"
CYCLONEDX_PY_VERSION="8.0.1"      # PyPI: cyclonedx-bom
CYCLONEDX_NPM_VERSION="7.0.1"     # npm: @cyclonedx/cyclonedx-npm (Node.js 20+)
CDXGEN_VERSION="13.8.0"           # npm: @cdxgen/cdxgen (Node.js 24+; was @cyclonedx/cdxgen before v13)

say() { printf '%s\n' "sbombox-install: $*"; }
warn() { printf '%s\n' "sbombox-install: warning: $*" >&2; }
err() { printf '%s\n' "sbombox-install: error: $*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1; }

fetch() { # fetch URL FILE
  if need curl; then
    curl -fsSL --retry 3 -o "$2" "$1"
  elif need wget; then
    wget -q -O "$2" "$1"
  else
    err "curl or wget is required"
  fi
}

json_field() { # json_field FILE KEY -> string value, or empty for null/missing
  sed -n "s/.*\"$2\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$1" | head -n 1
}

version_lt() { # version_lt A B: true if A < B (numeric x.y.z)
  awk -v a="${1#v}" -v b="${2#v}" 'BEGIN {
    split(a, x, "."); split(b, y, ".")
    for (i = 1; i <= 3; i++) { if ((x[i] + 0) < (y[i] + 0)) exit 0; if ((x[i] + 0) > (y[i] + 0)) exit 1 }
    exit 1 }'
}

sha256_of() {
  if need sha256sum; then
    sha256sum "$1" | cut -d' ' -f1
  elif need shasum; then
    shasum -a 256 "$1" | cut -d' ' -f1
  else
    err "sha256sum or shasum is required to verify downloads"
  fi
}

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  MINGW* | MSYS* | CYGWIN*)
    err "Windows shells are not supported by this script. In PowerShell run:
  powershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"
  uv tool install $PACKAGE
and install syft from https://github.com/anchore/syft/releases" ;;
  *) err "unsupported operating system: $(uname -s)" ;;
esac

case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *) arch="" ;;
esac

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

# 1. uv ----------------------------------------------------------------------
if ! need uv; then
  # uv may already be installed in its default location but not on PATH yet.
  for d in "$HOME/.local/bin" "$HOME/.cargo/bin"; do
    if [ -x "$d/uv" ]; then PATH="$d:$PATH"; export PATH; break; fi
  done
fi
if ! need uv; then
  say "installing uv (Python tool manager from Astral)"
  fetch https://astral.sh/uv/install.sh "$tmp/uv-install.sh"
  env ${SBOMBOX_NO_MODIFY_PATH:+UV_NO_MODIFY_PATH=1} sh "$tmp/uv-install.sh" >/dev/null
  PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
  export PATH
  need uv || err "uv was installed but is not on PATH; open a new shell and run this again"
fi
bin_dir="${SBOMBOX_BIN_DIR:-$(uv tool dir --bin 2>/dev/null || printf '%s' "$HOME/.local/bin")}"
mkdir -p "$bin_dir"
case ":$PATH:" in *":$bin_dir:"*) ;; *) PATH="$bin_dir:$PATH"; export PATH ;; esac

# 2. The CLI -----------------------------------------------------------------
if [ -z "${SBOMBOX_SKIP_CLI:-}" ]; then
  # The server decides which version is current and which are still allowed.
  api_url="${SBOMBOX_API_URL:-https://api.sbombox.com}"
  latest=""; minimum=""
  if fetch "${api_url%/}/v1/meta/cli" "$tmp/policy.json" 2>/dev/null; then
    latest="$(json_field "$tmp/policy.json" latest_version)"
    minimum="$(json_field "$tmp/policy.json" min_supported_version)"
  else
    warn "could not reach $api_url for the current version; installing the newest release"
  fi
  version="${SBOMBOX_VERSION:-$latest}"
  version="${version#v}"
  if [ -n "$version" ] && [ -n "$minimum" ] && version_lt "$version" "$minimum"; then
    err "sbombox $version is below the minimum supported version $minimum and would be refused by the API; use $minimum or newer"
  fi
  spec="$PACKAGE"
  [ -n "$version" ] && spec="$PACKAGE==$version"
  say "installing $spec"
  uv tool install --quiet --force --python ">=$MIN_PYTHON" "$spec" || err "uv could not install $spec"
  if [ -z "${SBOMBOX_NO_MODIFY_PATH:-}" ]; then
    uv tool update-shell >/dev/null 2>&1 || true
  fi
  need sbombox || err "install finished but sbombox was not found in $bin_dir"
fi

# 3. SBOM generators ---------------------------------------------------------
install_syft() {
  version="${SBOMBOX_SYFT_VERSION:-$DEFAULT_SYFT_VERSION}"
  version="v${version#v}"
  [ -n "$arch" ] || { warn "no syft build for $(uname -m); install a generator yourself"; return 0; }
  if need syft; then
    if [ -z "${SBOMBOX_SYFT_VERSION:-}" ]; then
      say "syft already installed"; return 0
    fi
    if syft version 2>/dev/null | grep -q "${version#v}"; then
      say "syft $version already installed"; return 0
    fi
  fi
  archive="syft_${version#v}_${os}_${arch}.tar.gz"
  base="https://github.com/anchore/syft/releases/download/$version"
  say "installing syft $version"
  fetch "$base/$archive" "$tmp/$archive" || err "could not download $archive"
  fetch "$base/syft_${version#v}_checksums.txt" "$tmp/checksums.txt" || err "could not download syft checksums"
  expected="$(grep " $archive\$" "$tmp/checksums.txt" | cut -d' ' -f1)"
  [ -n "$expected" ] || err "no published checksum for $archive"
  [ "$(sha256_of "$tmp/$archive")" = "$expected" ] || err "checksum mismatch for $archive; not installing"
  tar -xzf "$tmp/$archive" -C "$tmp" syft
  mv "$tmp/syft" "$bin_dir/syft"
  chmod 755 "$bin_dir/syft"
}

node_ok() { # node_ok MIN_MAJOR: Node.js of at least that major version, with npm
  need npm && need node || return 1
  major="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
  [ "$major" -ge "$1" ] 2>/dev/null
}

install_npm_tool() { # install_npm_tool COMMAND PACKAGE@VERSION REQUIRED(0|1) MIN_NODE_MAJOR
  if need "$1"; then say "$1 already installed"; return 0; fi
  if ! node_ok "$4"; then
    [ "$3" = 1 ] && warn "skipping $1: needs Node.js $4 or newer with npm"
    return 0
  fi
  say "installing $1"
  npm install -g --silent "$2" >/dev/null 2>&1 || warn "npm could not install $2 (try with a user-writable npm prefix)"
}

npm_has_sbom() { # npm 9.5+ ships `npm sbom`, which sbombox prefers anyway
  need npm || return 1
  v="$(npm --version 2>/dev/null || echo 0.0.0)"
  major="${v%%.*}"; rest="${v#*.}"; minor="${rest%%.*}"
  [ "$major" -gt 9 ] 2>/dev/null || { [ "$major" -eq 9 ] && [ "$minor" -ge 5 ]; } 2>/dev/null
}

install_cyclonedx_py() {
  if need cyclonedx-py; then say "cyclonedx-py already installed"; return 0; fi
  say "installing cyclonedx-py"
  uv tool install --quiet "cyclonedx-bom==$CYCLONEDX_PY_VERSION" || warn "could not install cyclonedx-py"
}

generators="${SBOMBOX_GENERATORS:-auto}"
case "$generators" in
  all) generators="syft,cyclonedx-py,cyclonedx-npm,cdxgen" ;;
  auto) generators="syft,cyclonedx-py,cyclonedx-npm-if-node" ;;
esac

for g in $(printf '%s' "$generators" | tr ',' ' '); do
  case "$g" in
    none) ;;
    syft) install_syft ;;
    cyclonedx-py) install_cyclonedx_py ;;
    cyclonedx-npm) install_npm_tool cyclonedx-npm "@cyclonedx/cyclonedx-npm@$CYCLONEDX_NPM_VERSION" 1 20 ;;
    cyclonedx-npm-if-node)
      if npm_has_sbom; then say "npm $(npm --version) has npm sbom; cyclonedx-npm not needed"
      else install_npm_tool cyclonedx-npm "@cyclonedx/cyclonedx-npm@$CYCLONEDX_NPM_VERSION" 0 20; fi ;;
    cdxgen) install_npm_tool cdxgen "@cdxgen/cdxgen@$CDXGEN_VERSION" 1 24 ;;
    *) warn "unknown generator '$g' (use syft, cyclonedx-py, cyclonedx-npm, cdxgen, auto, all or none)" ;;
  esac
done

# 4. Summary -----------------------------------------------------------------
say "done"
if need sbombox; then printf '  %-14s %s\n' "sbombox" "$(sbombox --version 2>/dev/null | sed 's/^sbombox //')"; fi
for t in syft cyclonedx-py cdxgen cyclonedx-npm; do
  need "$t" && printf '  %-14s %s\n' "$t" "$(command -v "$t")"
done

if [ -z "${SBOMBOX_SKIP_CLI:-}" ]; then
  cat <<EOF

Next steps, from the root of a repository:
  sbombox login     # sign in through your browser
  sbombox init      # choose a project, allow CI, write the workflow

If 'sbombox' is not found, open a new shell or add $bin_dir to your PATH.
Docs: https://sbombox.com/docs/install
EOF
fi
