#!/bin/sh
# murus installer.
#
#   curl -fsSL https://raw.githubusercontent.com/dcodeu/murus/main/install.sh | sh
#
# Downloads the release binary for this platform, checks it against the
# published SHA256SUMS, and installs it. Refuses to install on a checksum
# mismatch. Override the install directory with MURUS_INSTALL_DIR, or pin a
# version with MURUS_VERSION=v0.1.0.
#
# Read it before you pipe it to a shell. That goes for every installer.

set -eu

REPO="dcodeu/murus"
INSTALL_DIR="${MURUS_INSTALL_DIR:-/usr/local/bin}"
VERSION="${MURUS_VERSION:-latest}"

die() { printf '\033[31merror\033[0m %s\n' "$1" >&2; exit 1; }
info() { printf '\033[2m%s\033[0m\n' "$1" >&2; }

need() { command -v "$1" >/dev/null 2>&1 || die "$1 is required but not installed."; }
need curl
need uname

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux)  os=linux ;;
  *) die "unsupported OS $(uname -s). Prebuilt binaries cover macOS and Linux; on Windows download murus-windows-x64.exe from the releases page." ;;
esac

case "$(uname -m)" in
  arm64|aarch64) arch=arm64 ;;
  x86_64|amd64)  arch=x64 ;;
  *) die "unsupported architecture $(uname -m). Prebuilt binaries cover arm64 and x64." ;;
esac

asset="murus-${os}-${arch}"

if [ "$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

info "downloading ${asset} (${VERSION})"
curl -fsSL --proto '=https' --tlsv1.2 -o "${tmp}/${asset}" "${base}/${asset}" \
  || die "download failed. If the repository is private or ${VERSION} has no release, ${base}/${asset} will 404."
curl -fsSL --proto '=https' --tlsv1.2 -o "${tmp}/SHA256SUMS" "${base}/SHA256SUMS" \
  || die "could not fetch SHA256SUMS. Refusing to install an unverified binary."

# SHA256SUMS names the release artefacts, so verify before renaming anything.
info "verifying checksum"
if command -v shasum >/dev/null 2>&1; then
  ( cd "$tmp" && shasum -a 256 -c SHA256SUMS --ignore-missing >/dev/null 2>&1 ) \
    || die "checksum mismatch for ${asset}. Not installing."
elif command -v sha256sum >/dev/null 2>&1; then
  ( cd "$tmp" && sha256sum -c SHA256SUMS --ignore-missing >/dev/null 2>&1 ) \
    || die "checksum mismatch for ${asset}. Not installing."
else
  die "neither shasum nor sha256sum found. Refusing to install an unverified binary."
fi

chmod +x "${tmp}/${asset}"

if [ -w "$INSTALL_DIR" ]; then
  mv "${tmp}/${asset}" "${INSTALL_DIR}/murus"
elif command -v sudo >/dev/null 2>&1; then
  info "${INSTALL_DIR} is not writable, using sudo"
  sudo mv "${tmp}/${asset}" "${INSTALL_DIR}/murus"
else
  die "${INSTALL_DIR} is not writable and sudo is unavailable. Set MURUS_INSTALL_DIR to a directory you own."
fi

printf '\033[32minstalled\033[0m %s/murus\n' "$INSTALL_DIR" >&2
"${INSTALL_DIR}/murus" --version >&2 2>/dev/null || info "run 'murus --version' to confirm it is on your PATH"
