#!/usr/bin/env sh
# Installer for lmctfy on macOS / Linux / WSL. Drops a single static
# binary into ~/.local/bin (no sudo, no system writes). Override the
# destination with LMCTFY_BIN=<path>.
#
#   curl -fsSL https://install.lmctf.you | bash                        # latest
#   LMCTFY_VERSION=v0.0.3 curl -fsSL https://install.lmctf.you | bash  # pin
#   LMCTFY_BIN=$HOME/bin/lmctfy curl -fsSL https://install.lmctf.you | bash
#
# Windows users: use install.ps1 (PowerShell) or install.cmd (CMD).
#
# Verifies the SHA-256 against the published checksums.txt before
# installing. If host, version, or checksum is wrong, fails closed.

set -eu

HOST=${LMCTFY_HOST:-https://install.lmctf.you}
DEST=${LMCTFY_BIN:-$HOME/.local/bin/lmctfy}

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$ARCH" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "unsupported architecture: $ARCH" >&2; exit 1 ;;
esac
case "$OS" in
  linux|darwin) ;;
  *) echo "unsupported OS: $OS" >&2; exit 1 ;;
esac

if [ -z "${LMCTFY_VERSION:-}" ]; then
  VER=$(curl -fsSL "$HOST/latest.txt" | tr -d '[:space:]')
else
  VER=$LMCTFY_VERSION
fi
case "$VER" in
  v*) ;;
  *) echo "version must start with 'v' (got: $VER)" >&2; exit 1 ;;
esac

ARCHIVE="lmctfy_${OS}_${ARCH}.tar.gz"
URL="$HOST/$VER/$ARCHIVE"
SUMS_URL="$HOST/$VER/checksums.txt"

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

echo "Fetching $URL" >&2
curl -fsSL "$URL" -o "$TMP/$ARCHIVE"
curl -fsSL "$SUMS_URL" -o "$TMP/checksums.txt"

# Verify checksum. Prefer sha256sum (Linux); fall back to shasum (macOS).
EXPECTED=$(grep -E "  $ARCHIVE\$" "$TMP/checksums.txt" | awk '{print $1}')
if [ -z "$EXPECTED" ]; then
  echo "no checksum entry for $ARCHIVE in checksums.txt" >&2
  exit 1
fi
if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL=$(sha256sum "$TMP/$ARCHIVE" | awk '{print $1}')
else
  ACTUAL=$(shasum -a 256 "$TMP/$ARCHIVE" | awk '{print $1}')
fi
if [ "$EXPECTED" != "$ACTUAL" ]; then
  echo "checksum mismatch:"          >&2
  echo "  expected $EXPECTED"        >&2
  echo "  actual   $ACTUAL"          >&2
  exit 1
fi

tar -xzf "$TMP/$ARCHIVE" -C "$TMP"

DEST_DIR=$(dirname "$DEST")
mkdir -p "$DEST_DIR"
install -m 0755 "$TMP/lmctfy" "$DEST"

echo "Installed lmctfy $VER → $DEST" >&2

# Friendly PATH hint. We don't try to edit shell rc files — that's
# the user's territory. Just tell them what to add if it's missing.
case ":$PATH:" in
  *":$DEST_DIR:"*) ;;
  *)
    cat >&2 <<EOF

NOTE: $DEST_DIR is not on your PATH. Add this to your shell rc to fix it:
  export PATH="$DEST_DIR:\$PATH"
Or invoke the binary by absolute path: $DEST -dir=\$PWD
EOF
    ;;
esac
