#!/bin/sh
# ─────────────────────────────────────────────────────────────────────
#  Softinel CLI installer
#
#  usage:  curl -sSfL https://softinel.com/get/install.sh | sh
#          curl -sSfL https://softinel.com/get           | sh     # same
#
#  env vars:
#    SVP_VERSION      — release to install (default: latest)
#    SVP_INSTALL_DIR  — where to drop the binary (default: /usr/local/bin)
#
#  what it does:
#    1. Detects your OS + arch
#    2. Downloads the matching binary from https://softinel.com/get/dl/
#    3. Installs it (with sudo only if needed)
#    4. Prints the version so you can confirm
#
#  supported: linux/amd64, linux/arm64, darwin/amd64, darwin/arm64
# ─────────────────────────────────────────────────────────────────────
set -eu

SVP_VERSION="${SVP_VERSION:-latest}"
SVP_INSTALL_DIR="${SVP_INSTALL_DIR:-/usr/local/bin}"
BASE_URL="${SVP_BASE_URL:-https://softinel.com/get}"

blue()  { printf '\033[34m%s\033[0m\n' "$*"; }
green() { printf '\033[32m%s\033[0m\n' "$*"; }
red()   { printf '\033[31m%s\033[0m\n' "$*" >&2; }

blue ">>> Softinel CLI installer"

# ── Detect OS + arch ────────────────────────────────────────────────
os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in
  linux|darwin) ;;
  *) red "unsupported OS: $os (want linux or darwin)"; exit 1 ;;
esac

arch=$(uname -m)
case "$arch" in
  x86_64|amd64)  arch=amd64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) red "unsupported architecture: $arch (want amd64 or arm64)"; exit 1 ;;
esac

url="$BASE_URL/dl/$SVP_VERSION/$os-$arch/svp"
blue ">>> target: $os/$arch  version=$SVP_VERSION"
blue ">>> source: $url"

# ── Download ────────────────────────────────────────────────────────
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT INT TERM

if ! curl -fSL --progress-bar -o "$tmp" "$url"; then
  red "download failed."
  red "verify supported versions at $BASE_URL/available"
  exit 1
fi
chmod +x "$tmp"

# ── Install ─────────────────────────────────────────────────────────
dst="$SVP_INSTALL_DIR/svp"
if [ -w "$SVP_INSTALL_DIR" ] || [ "$(id -u)" -eq 0 ]; then
  mv "$tmp" "$dst"
else
  blue ">>> $SVP_INSTALL_DIR not writable — using sudo"
  sudo mv "$tmp" "$dst"
fi
trap - EXIT INT TERM

green ">>> installed: $dst"
green ">>> version:   $("$dst" --version 2>/dev/null || "$dst" version 2>/dev/null || echo '(no --version flag)')"
echo
echo "Next steps:"
echo "  svp login          # authenticate against your Softinel org"
echo "  svp projects list  # confirm you can reach the platform"
echo
echo "Docs: https://softinel.com/docs"
