#!/bin/sh
# JoyMux customer installer — downloads a macOS archive from joymux.com.
# Review first:
#   curl -fsSL https://joymux.com/releases/install.sh -o joymux-install.sh
#   less joymux-install.sh
#   sh joymux-install.sh
set -eu

VERSION="0.1.0"
ORIGIN="${JOYMUX_ORIGIN:-https://joymux.com}"
PREFIX="${JOYMUX_PREFIX:-$HOME/.local}"
BASE="${ORIGIN%/}/releases/${VERSION}"

uname_s=$(uname -s)
uname_m=$(uname -m)

platform=""
case "$uname_s:$uname_m" in
  Darwin:arm64) platform="macos-arm64" ;;
  Darwin:x86_64) platform="macos-x86_64" ;;
  Linux:*)
    echo "This release ships macOS archives only. A Linux tarball is not published yet." >&2
    echo "Docs: ${ORIGIN%/}/docs/install/" >&2
    exit 1
    ;;
  *)
    echo "Unsupported platform: $uname_s $uname_m" >&2
    echo "Available: macOS Apple Silicon and macOS Intel." >&2
    exit 1
    ;;
esac

archive="joymux-${VERSION}-${platform}.tar.gz"
url="${BASE}/${archive}"
expected=""
case "$platform" in
  macos-arm64) expected="6df308565168dccb0b66679b4a024662f029aec32382556379aaccf8275e5e7d" ;;
  macos-x86_64) expected="e797bc3a20e0e7f46f3c12653a4539b6f4c74f73a0b44e85757fa8a3a74f5d2e" ;;
esac

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
echo "Downloading ${url}"
curl -fL --retry 3 --retry-delay 1 -o "$tmp/$archive" "$url"

if command -v shasum >/dev/null 2>&1; then
  actual=$(shasum -a 256 "$tmp/$archive" | awk '{print $1}')
elif command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$tmp/$archive" | awk '{print $1}')
else
  echo "Need shasum or sha256sum to verify the archive." >&2
  exit 1
fi

if [ "$actual" != "$expected" ]; then
  echo "Checksum mismatch for $archive" >&2
  echo "expected $expected" >&2
  echo "got      $actual" >&2
  exit 1
fi
echo "Checksum OK"

tar -xzf "$tmp/$archive" -C "$tmp"
root=$(find "$tmp" -mindepth 1 -maxdepth 1 -type d | head -1)
mkdir -p "${PREFIX}/bin"
install -m 755 "${root}/bin/joymux" "${PREFIX}/bin/joymux"
if [ -f "${root}/bin/joymux-reference-client" ]; then
  install -m 755 "${root}/bin/joymux-reference-client" "${PREFIX}/bin/joymux-reference-client"
fi

echo "Installed to ${PREFIX}/bin"
echo "Ensure ${PREFIX}/bin is on PATH, then:"
echo "  mkdir -p ~/.joymux"
echo "  # save entitlement_lease.json from the trial success page to ~/.joymux/entitlement_lease.json"
echo "  joymux init"
echo "  joymux doctor --json"
echo "  joymux license status"
