#!/bin/sh
# box installer: picks the binary for this OS and CPU, checks it against the server's SHA256SUMS,
# and puts it at ~/.local/bin/box. Usage: curl -fsSL https://xenoci.com/install.sh | sh
# BOX_VERSION=<version> pins a version (default: latest). BOX_INSTALL_DIR changes the target folder.
# The API address of this server goes to ~/.config/box/api, so the installed box talks to the server it came from.
set -eu

origin="${BOX_ORIGIN:-https://xenoci.com}"
version="${BOX_VERSION:-latest}"
dir="${BOX_INSTALL_DIR:-$HOME/.local/bin}"

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  *) echo "box: this OS is not supported ($(uname -s)); use Linux or macOS" >&2; exit 2 ;;
esac
case "$(uname -m)" in
  x86_64|amd64) arch=x86_64 ;;
  aarch64|arm64) arch=arm64 ;;
  *) echo "box: this CPU is not supported ($(uname -m))" >&2; exit 2 ;;
esac
if [ "$os" = darwin ] && [ "$arch" != arm64 ]; then echo "box: on macOS only Apple silicon (arm64) is supported" >&2; exit 2; fi

name="box-$os-$arch"
if [ "$version" = latest ]; then
  version=$(curl -fsSL "$origin/download/latest") || { echo "box: could not reach $origin" >&2; exit 3; }
fi

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "$origin/download/$version/$name" -o "$tmp/$name" || { echo "box: download failed ($origin/download/$version/$name)" >&2; exit 3; }
curl -fsSL "$origin/download/$version/SHA256SUMS" -o "$tmp/SHA256SUMS" || { echo "box: could not fetch SHA256SUMS" >&2; exit 3; }

want=$(awk -v n="$name" '$2 == n || $2 == "*"n { print $1 }' "$tmp/SHA256SUMS")
if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$tmp/$name" | awk '{print $1}'); else got=$(shasum -a 256 "$tmp/$name" | awk '{print $1}'); fi
if [ -z "$want" ] || [ "$want" != "$got" ]; then echo "box: checksum mismatch for $name, not installed" >&2; exit 3; fi

mkdir -p "$dir"
chmod +x "$tmp/$name"
mv "$tmp/$name" "$dir/box"
conf="${BOX_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/box}"
mkdir -p "$conf"
printf '%s/api\n' "$origin" > "$conf/api"
echo "box $version installed at $dir/box (API $origin/api)"
case ":$PATH:" in *":$dir:"*) ;; *) echo "add it to PATH: export PATH=\"$dir:\$PATH\"" ;; esac
