#!/usr/bin/env sh
# PostToMe CLI installer
#
# Usage:
#   curl -fsSL https://posttome.app/install.sh | sh
#
# Environment variables:
#   POSTTOME_VERSION   Specific version to install (e.g. v0.1.0). Default: latest release.
#   POSTTOME_INSTALL   Install directory. Default: /usr/local/bin (uses sudo if needed).
#
# What it does:
#   1. Detects your OS / arch.
#   2. Resolves the latest (or pinned) release from
#      https://github.com/allwefantasy/posttome-skills/releases.
#      (Release artifacts live in the public posttome-skills repo so the
#       main posttome source repo can remain private.)
#   3. Downloads the matching tarball, verifies its SHA-256 against the
#      published checksums.txt, and installs the `posttome` binary.

set -eu

REPO="allwefantasy/posttome-skills"
BIN_NAME="posttome"
INSTALL_DIR="${POSTTOME_INSTALL:-/usr/local/bin}"
VERSION="${POSTTOME_VERSION:-latest}"

# ---------- helpers ----------
red()    { printf '\033[31m%s\033[0m\n' "$*" >&2; }
green()  { printf '\033[32m%s\033[0m\n' "$*"; }
yellow() { printf '\033[33m%s\033[0m\n' "$*"; }

die() { red "error: $*"; exit 1; }

need() {
  command -v "$1" >/dev/null 2>&1 || die "required command not found: $1"
}

need curl
need tar
need uname

# ---------- detect platform ----------
OS_RAW="$(uname -s)"
case "$OS_RAW" in
  Darwin) OS="darwin" ;;
  Linux)  OS="linux" ;;
  MINGW*|MSYS*|CYGWIN*)
    die "Windows is not supported by this shell installer. Download a release archive manually from https://github.com/$REPO/releases." ;;
  *) die "Unsupported OS: $OS_RAW" ;;
esac

ARCH_RAW="$(uname -m)"
case "$ARCH_RAW" in
  x86_64|amd64) ARCH="amd64" ;;
  arm64|aarch64) ARCH="arm64" ;;
  *) die "Unsupported arch: $ARCH_RAW" ;;
esac

# ---------- resolve version ----------
# We resolve "latest" via github.com's HTML redirect first, since
# api.github.com is sometimes throttled or DNS-poisoned in mainland China
# while github.com itself stays reachable. We fall back to the JSON API
# only if the redirect approach fails.
if [ "$VERSION" = "latest" ]; then
  yellow "Resolving latest release..."

  # Method 1: follow the /releases/latest redirect -> /releases/tag/<tag>
  FINAL_URL="$(curl -sIL -o /dev/null -w '%{url_effective}' \
    "https://github.com/$REPO/releases/latest" 2>/dev/null || true)"
  case "$FINAL_URL" in
    *"/releases/tag/"*) VERSION="${FINAL_URL##*/tag/}" ;;
  esac

  # Method 2: fall back to the JSON API.
  if [ -z "$VERSION" ] || [ "$VERSION" = "latest" ]; then
    VERSION="$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" 2>/dev/null \
      | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -n1)"
  fi

  if [ -z "$VERSION" ] || [ "$VERSION" = "latest" ]; then
    die "Could not resolve latest version. Check that github.com is reachable, \
or pin a specific version with POSTTOME_VERSION=v0.1.0 (see https://github.com/$REPO/releases)."
  fi
fi

# Strip leading "v" for asset name (asset uses bare version).
VERSION_NOV="${VERSION#v}"

ASSET="${BIN_NAME}_${VERSION_NOV}_${OS}_${ARCH}.tar.gz"
URL="https://github.com/$REPO/releases/download/$VERSION/$ASSET"
SUMS_URL="https://github.com/$REPO/releases/download/$VERSION/checksums.txt"

yellow "Installing $BIN_NAME $VERSION for $OS/$ARCH..."
yellow "  from: $URL"

# ---------- download to tmp ----------
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT INT TERM

curl -fL --progress-bar -o "$TMP/$ASSET" "$URL" \
  || die "Failed to download $URL"

# ---------- verify checksum ----------
if curl -fsSL "$SUMS_URL" -o "$TMP/checksums.txt" 2>/dev/null; then
  EXPECTED="$(grep " $ASSET\$" "$TMP/checksums.txt" | awk '{print $1}')"
  if [ -n "$EXPECTED" ]; then
    if command -v sha256sum >/dev/null 2>&1; then
      ACTUAL="$(sha256sum "$TMP/$ASSET" | awk '{print $1}')"
    elif command -v shasum >/dev/null 2>&1; then
      ACTUAL="$(shasum -a 256 "$TMP/$ASSET" | awk '{print $1}')"
    else
      ACTUAL=""
      yellow "  (no sha256sum/shasum available; skipping checksum verification)"
    fi
    if [ -n "$ACTUAL" ]; then
      if [ "$EXPECTED" != "$ACTUAL" ]; then
        die "checksum mismatch for $ASSET (expected $EXPECTED, got $ACTUAL)"
      fi
      green "  ✓ sha256 verified"
    fi
  else
    yellow "  (no checksum entry for $ASSET; skipping verification)"
  fi
else
  yellow "  (could not fetch checksums.txt; skipping verification)"
fi

# ---------- extract ----------
tar -xzf "$TMP/$ASSET" -C "$TMP" || die "Failed to extract $ASSET"
[ -f "$TMP/$BIN_NAME" ] || die "Archive did not contain '$BIN_NAME' binary."
chmod +x "$TMP/$BIN_NAME"

# ---------- install ----------
DEST="$INSTALL_DIR/$BIN_NAME"
mkdir -p "$INSTALL_DIR" 2>/dev/null || true

if [ -w "$INSTALL_DIR" ] || { [ ! -e "$INSTALL_DIR" ] && mkdir -p "$INSTALL_DIR" 2>/dev/null; }; then
  mv "$TMP/$BIN_NAME" "$DEST"
else
  yellow "Need sudo to write to $INSTALL_DIR"
  sudo mv "$TMP/$BIN_NAME" "$DEST"
fi

green "✓ Installed $BIN_NAME $VERSION → $DEST"
"$DEST" version || true

# ---------- next-step hints ----------
cat <<EOF

Next steps:
  1. Create an API key in the PostToMe web app:
       https://posttome.app
  2. Save it locally:
       posttome config --set-key pr_xxx
  3. Send your first payload:
       posttome post --text "hello from $(uname -n)" --event hello

If '$BIN_NAME' is not in your PATH, add this to your shell rc:
  export PATH="$INSTALL_DIR:\$PATH"

Docs: https://github.com/$REPO
EOF
