#!/bin/sh
# frontpage installer — fetches a prebuilt binary from the latest release.
# Usage:  curl -fsSL https://frontpage.sh/install | sh
set -eu

VERSION="${FRONTPAGE_CLI_VERSION:-0.1.0}"
BASE="https://github.com/DFectuoso/frontpage-cli/releases/download/cli-v${VERSION}"
INSTALL_DIR="${FRONTPAGE_INSTALL_DIR:-${XDG_BIN_HOME:-$HOME/.local/bin}}"

die() { printf "frontpage installer: %s\n" "$1" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64) ARCH="x86_64";;
  aarch64|arm64) ARCH="${OS_ARCH_FALLBACK:-$([ "$OS" = darwin ] && echo arm64 || echo aarch64)}";;
  *) die "unsupported architecture: $ARCH";;
esac

target=""
sha256=""
case "$OS-$ARCH" in
        linux-x86_64) target="x86_64-unknown-linux-musl"; sha256="798a2d9e47187f816ce5b8a8381f84643c94c06f57ed449bc84ed454ff3d2a8c";;
        linux-aarch64) target="aarch64-unknown-linux-musl"; sha256="bfba1036f8d5655fa7a5e213dba7242fde54ec97f76f1b57c9227a5170420149";;
        darwin-arm64) target="aarch64-apple-darwin"; sha256="e5b3da222f49b2bd58f70d73e23e943543f9cca473b3ee9ab99d137793bbb03c";;
        darwin-x86_64) target="x86_64-apple-darwin"; sha256="6d7ed1681c3fa43ac1d71b456a06bf5d266908079657a30d1f129b77bcd14ada";;
        *) die "unsupported platform: $OS-$ARCH";;
esac

ARCHIVE="frontpage-v${VERSION}-${target}.tar.gz"
URL="${BASE}/${ARCHIVE}"

TMP="$(mktemp -d 2>/dev/null || mktemp -d -t frontpage)"
trap 'rm -rf "$TMP"' EXIT

printf "downloading %s\n" "$URL"
if have curl; then
  curl --fail --location --silent --show-error "$URL" -o "$TMP/$ARCHIVE"
elif have wget; then
  wget -q -O "$TMP/$ARCHIVE" "$URL"
else
  die "need curl or wget"
fi

if [ -n "$sha256" ]; then
  printf "verifying checksum\n"
  if have shasum; then
    printf "%s  %s\n" "$sha256" "$TMP/$ARCHIVE" | shasum -a 256 -c - || die "checksum mismatch"
  elif have sha256sum; then
    printf "%s  %s\n" "$sha256" "$TMP/$ARCHIVE" | sha256sum -c - || die "checksum mismatch"
  else
    printf "warning: no shasum/sha256sum found, skipping verification\n"
  fi
fi

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

mkdir -p "$INSTALL_DIR"
mv "$TMP/frontpage" "$INSTALL_DIR/frontpage"
chmod +x "$INSTALL_DIR/frontpage"

printf "\nfrontpage v%s installed to %s/frontpage\n" "$VERSION" "$INSTALL_DIR"
case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *) printf "\nadd %s to your PATH to run \`frontpage\` from anywhere.\n" "$INSTALL_DIR";;
esac

printf "\nnext: \`frontpage\` (or \`frontpage login\` to bind a wallet)\n"
