#!/usr/bin/env sh
# sloppoke universal installer
#   curl -fsSL https://sloppoke.me/install.sh | sh
#
# Detects platform + arch, pulls the matching release binary from
# github.com/peeramid-labs/sloppoke, verifies SHA-256, drops it into
# the user's PATH. No build toolchain required.
#
# Honoured env vars:
#   SLOP_VERSION    pin to a specific release tag (default: latest)
#   SLOP_PREFIX     install prefix (default: /usr/local or ~/.local based on writability)
#   SLOP_FORCE      reinstall even when `slop` already exists
#
# Source: https://github.com/peeramid-labs/sloppoke

set -eu

GH_REPO="peeramid-labs/sloppoke"
BIN_NAME="slop"

note()  { printf '\033[1;36m›\033[0m %s\n' "$1"; }
warn()  { printf '\033[1;33m!\033[0m %s\n' "$1" >&2; }
fatal() { printf '\033[1;31m✗\033[0m %s\n' "$1" >&2; exit 1; }

# ── platform detection ───────────────────────────────────────────
os=$(uname -s | tr '[:upper:]' '[:lower:]')
arch=$(uname -m)

case "$os" in
  linux)  os_tag="unknown-linux-gnu" ;;
  darwin) os_tag="apple-darwin" ;;
  *) fatal "unsupported OS: $os (only linux + macOS shipped today; PRs welcome)" ;;
esac

case "$arch" in
  x86_64|amd64) arch_tag="x86_64" ;;
  arm64|aarch64) arch_tag="aarch64" ;;
  *) fatal "unsupported arch: $arch" ;;
esac

target="${arch_tag}-${os_tag}"
note "platform: ${os}/${arch} → ${target}"

# ── prefix selection ─────────────────────────────────────────────
prefix="${SLOP_PREFIX:-}"
if [ -z "$prefix" ]; then
  if [ -w /usr/local/bin ] || [ "$(id -u)" -eq 0 ]; then
    prefix="/usr/local"
  else
    prefix="${HOME}/.local"
    mkdir -p "${prefix}/bin"
  fi
fi
bindir="${prefix}/bin"
mkdir -p "$bindir"

if [ -e "${bindir}/${BIN_NAME}" ] && [ -z "${SLOP_FORCE:-}" ]; then
  current=$("${bindir}/${BIN_NAME}" --version 2>/dev/null || echo "unknown")
  warn "${BIN_NAME} already installed at ${bindir}/${BIN_NAME} (${current}); SLOP_FORCE=1 to overwrite"
  exit 0
fi

# ── resolve version ──────────────────────────────────────────────
version="${SLOP_VERSION:-}"
if [ -z "$version" ]; then
  note "resolving latest release tag…"
  version=$(curl -fsSL "https://api.github.com/repos/${GH_REPO}/releases/latest" \
    | grep -m1 '"tag_name"' \
    | sed -E 's/.*"tag_name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
  [ -n "$version" ] || fatal "could not resolve latest release tag; pin via SLOP_VERSION"
fi
note "version: ${version}"

# ── download + verify ────────────────────────────────────────────
tarball="${BIN_NAME}-${version}-${target}.tar.gz"
url="https://github.com/${GH_REPO}/releases/download/${version}/${tarball}"
sha_url="${url}.sha256"

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

note "fetching ${url}"
curl -fL --progress-bar -o "${tmpdir}/${tarball}" "$url" \
  || fatal "download failed; check https://github.com/${GH_REPO}/releases/${version}"

if curl -fsSL -o "${tmpdir}/${tarball}.sha256" "$sha_url" 2>/dev/null; then
  note "verifying sha256"
  ( cd "$tmpdir" && \
    if command -v sha256sum >/dev/null 2>&1; then
      sha256sum -c "${tarball}.sha256"
    elif command -v shasum >/dev/null 2>&1; then
      shasum -a 256 -c "${tarball}.sha256"
    else
      warn "no sha256sum / shasum on PATH; skipping verify"
    fi
  ) || fatal "sha256 mismatch; aborting"
else
  warn "no published sha256 for ${tarball}; skipping verify"
fi

# ── unpack + install ─────────────────────────────────────────────
tar -xzf "${tmpdir}/${tarball}" -C "$tmpdir"
if [ ! -f "${tmpdir}/${BIN_NAME}" ]; then
  # Some releases ship the binary nested; find it.
  found=$(find "$tmpdir" -name "$BIN_NAME" -type f | head -1 || true)
  [ -n "$found" ] || fatal "binary '${BIN_NAME}' not found inside tarball"
  cp "$found" "${bindir}/${BIN_NAME}"
else
  cp "${tmpdir}/${BIN_NAME}" "${bindir}/${BIN_NAME}"
fi
chmod +x "${bindir}/${BIN_NAME}"

# ── PATH sanity ─────────────────────────────────────────────────
case ":$PATH:" in
  *":${bindir}:"*) ;;
  *)
    warn "${bindir} is not on \$PATH; add this to your shell rc:"
    printf '\n    export PATH="%s:$PATH"\n\n' "$bindir" >&2
    ;;
esac

note "installed: $("${bindir}/${BIN_NAME}" --version 2>/dev/null || echo "${bindir}/${BIN_NAME}")"
cat <<EOF

Next:
  slop login                       # SSH-key handshake, cache identity
  slop poke                        # scan working tree
  slop --help                      # everything else

Launch deal: \$12/mo (was \$20) at sloppoke.me. Coupon LAUNCH40 auto-applied.
EOF
