#!/bin/sh
# markets CLI installer - https://markets.sh
#
#   curl -fsSL https://markets.sh/install | sh
#
# Overrides:
#   MARKETS_BASE_URL     distribution host (default https://markets.sh)
#   MARKETS_INSTALL_DIR  install directory (default ~/.local/bin)
#
# Note: keep this script pure ASCII — some shells parse multibyte bytes
# adjacent to expansions as part of the variable name.
set -eu

BASE="${MARKETS_BASE_URL:-https://markets.sh}"
DIR="${MARKETS_INSTALL_DIR:-$HOME/.local/bin}"

case "$(uname -s)" in
  Darwin) OS=darwin ;;
  Linux) OS=linux ;;
  *)
    echo "install: unsupported OS $(uname -s) - download a binary from ${BASE}/cli/manifest.json" >&2
    exit 1
    ;;
esac

case "$(uname -m)" in
  arm64 | aarch64) ARCH=arm64 ;;
  x86_64 | amd64) ARCH=amd64 ;;
  *)
    echo "install: unsupported architecture $(uname -m)" >&2
    exit 1
    ;;
esac

VERSION=$(curl -fsSL "${BASE}/cli/manifest.json" |
  sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
if [ -z "$VERSION" ]; then
  echo "install: could not read version from ${BASE}/cli/manifest.json" >&2
  exit 1
fi

FILE="markets_${VERSION}_${OS}_${ARCH}"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

echo "downloading markets ${VERSION} (${OS}/${ARCH}) from ${BASE} ..."
curl -fsSL -o "${TMP}/${FILE}" "${BASE}/cli/download/${VERSION}/${FILE}"
curl -fsSL -o "${TMP}/checksums.txt" "${BASE}/cli/checksums.txt"

EXPECTED=$(awk -v f="$FILE" '$2 == f { print $1 }' "${TMP}/checksums.txt")
if [ -z "$EXPECTED" ]; then
  echo "install: no checksum for ${FILE} in checksums.txt" >&2
  exit 1
fi
if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL=$(sha256sum "${TMP}/${FILE}" | awk '{ print $1 }')
else
  ACTUAL=$(shasum -a 256 "${TMP}/${FILE}" | awk '{ print $1 }')
fi
if [ "$EXPECTED" != "$ACTUAL" ]; then
  echo "install: checksum mismatch for ${FILE} (expected ${EXPECTED}, got ${ACTUAL})" >&2
  exit 1
fi

mkdir -p "$DIR"
install -m 0755 "${TMP}/${FILE}" "${DIR}/markets"

echo "installed markets ${VERSION} to ${DIR}/markets"
case ":$PATH:" in
  *":$DIR:"*) ;;
  *)
    echo ""
    echo "note: ${DIR} is not in your PATH. Add it with:"
    echo "  export PATH=\"${DIR}:\$PATH\""
    ;;
esac
echo ""
echo "get started:  markets login"
