#!/bin/sh
# Install the `cordane` binary — no hub needed.
#
#   curl -fsSL https://cordane.ai/install.sh | sh
#   cordane up          # a local hub + this machine as its worker, in your browser
#
# or both in one go (anything after `up` is passed to it):
#
#   curl -fsSL https://cordane.ai/install.sh | sh -s up
#
# Downloads the latest release from github.com/cordane/cordane (the same build
# the :stable images ship), checks it against the release's SHA256SUMS, and puts
# it in /usr/local/bin when that is writable, else ~/.local/bin — never sudo.
#
# Overrides: CORDANE_BIN=/path/to/cordane (install location),
#            CORDANE_VERSION=<release tag> (default: latest),
#            CORDANE_DOWNLOAD_BASE=<url> (a mirror with the release assets).
set -eu

REPO="cordane/cordane"
VERSION="${CORDANE_VERSION:-latest}"

say() { printf '%s\n' "$*"; }
die() { printf 'cordane install: %s\n' "$*" >&2; exit 1; }

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  *) die "unsupported OS $(uname -s) — Cordane runs on Linux and macOS" ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *) die "unsupported CPU $(uname -m) — builds exist for amd64 and arm64" ;;
esac
asset="cordane-${os}-${arch}"

if [ -n "${CORDANE_DOWNLOAD_BASE:-}" ]; then
  base="$CORDANE_DOWNLOAD_BASE" # a mirror holding the release assets
elif [ "$VERSION" = latest ]; then
  base="https://github.com/${REPO}/releases/latest/download"
else
  base="https://github.com/${REPO}/releases/download/${VERSION}"
fi

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

say "Downloading ${asset} (${VERSION}) …"
curl -fsSL -o "$tmp/$asset" "$base/$asset" || die "download failed: $base/$asset"
curl -fsSL -o "$tmp/SHA256SUMS" "$base/SHA256SUMS" || die "download failed: $base/SHA256SUMS"

want="$(awk -v a="$asset" '$2 == a || $2 == "*" a { print $1 }' "$tmp/SHA256SUMS")"
[ -n "$want" ] || die "no checksum for $asset in SHA256SUMS"
if command -v sha256sum >/dev/null 2>&1; then
  got="$(sha256sum "$tmp/$asset" | awk '{ print $1 }')"
else
  got="$(shasum -a 256 "$tmp/$asset" | awk '{ print $1 }')"
fi
[ "$got" = "$want" ] || die "checksum mismatch for $asset (want $want, got $got)"
chmod +x "$tmp/$asset"

if [ -n "${CORDANE_BIN:-}" ]; then
  dest="$CORDANE_BIN"
elif [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
  dest=/usr/local/bin/cordane
else
  dest="$HOME/.local/bin/cordane"
fi
mkdir -p "$(dirname "$dest")"
mv "$tmp/$asset" "$dest"

ver="$("$dest" version 2>/dev/null || echo "?")"
say "Installed cordane ${ver} to ${dest}"
case ":$PATH:" in
  *":$(dirname "$dest"):"*) run=cordane ;;
  *)
    run="$dest"
    say ""
    say "$(dirname "$dest") is not on your PATH. Add it, e.g.:"
    say "  echo 'export PATH=\"$(dirname "$dest"):\$PATH\"' >> ~/.profile"
    ;;
esac
if [ "${1:-}" = up ]; then
  shift
  say ""
  exec "$dest" up "$@"
fi
say ""
say "Next — start Cordane on this machine:"
say "  $run up"
