#!/bin/sh
# Ubique installer.  One-liner:
#
#   curl -fsSL https://ubq.sh/install.sh | sh
#
# Detects your OS and CPU, downloads the matching release from the ubq.sh
# stable channel, verifies its SHA-256, and installs the `ubq` binary into
# ~/.local/bin (override with UBQ_INSTALL_DIR).  No root required.
#
# Config (environment):
#   UBQ_INSTALL_DIR   where to put the binary   (default: ~/.local/bin)
#   UBQ_INSTALL_BASE  download site base URL    (default: https://ubq.sh)
#   UBQ_TARGET        force a target triple, skipping OS/CPU detection
set -eu

BASE=${UBQ_INSTALL_BASE:-https://ubq.sh}
DIR=${UBQ_INSTALL_DIR:-$HOME/.local/bin}

say()  { printf '%s\n' "$*"; }
err()  { printf 'error: %s\n' "$*" >&2; exit 1; }

# --- fetch abstraction: curl or wget, whichever is present ------------------
if command -v curl >/dev/null 2>&1; then
    fetch()   { curl -fsSL "$1" -o "$2"; }        # url dest
    fetchout(){ curl -fsSL "$1"; }                # url -> stdout
elif command -v wget >/dev/null 2>&1; then
    fetch()   { wget -qO "$2" "$1"; }
    fetchout(){ wget -qO- "$1"; }
else
    err "need curl or wget to download"
fi

sha256() {
    if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'
    else shasum -a 256 "$1" | awk '{print $1}'; fi
}

# --- work out which release to pull -----------------------------------------
if [ -n "${UBQ_TARGET:-}" ]; then
    TARGET=$UBQ_TARGET
else
    os=$(uname -s); arch=$(uname -m)
    case "$os" in
        Linux)  os_part=unknown-linux-gnu ;;
        Darwin) os_part=apple-darwin ;;
        MINGW*|MSYS*|CYGWIN*)
            err "on Windows use the PowerShell installer:
    irm https://ubq.sh/install.ps1 | iex" ;;
        *) err "unsupported OS: $os" ;;
    esac
    case "$arch" in
        x86_64|amd64)   arch_part=x86_64 ;;
        aarch64|arm64)  arch_part=aarch64 ;;
        *) err "unsupported CPU: $arch" ;;
    esac
    TARGET="$arch_part-$os_part"
fi

CHANNEL="$BASE/stable/$TARGET"
say "==> installing ubq for $TARGET"

VERSION=$(fetchout "$CHANNEL/VERSION" 2>/dev/null || true)
[ -n "$VERSION" ] && say "    release: $VERSION"

# --- download + verify -------------------------------------------------------
tmp=$(mktemp -d 2>/dev/null || mktemp -d -t ubq)
trap 'rm -rf "$tmp"' EXIT

if ! fetch "$CHANNEL/ubq.tar.gz" "$tmp/ubq.tar.gz"; then
    err "no release for $TARGET at $CHANNEL
    (browse https://ubq.sh/stable/ for available targets, or build from source)"
fi
fetch "$CHANNEL/ubq.tar.gz.sha256" "$tmp/ubq.tar.gz.sha256"

want=$(awk '{print $1}' "$tmp/ubq.tar.gz.sha256")
got=$(sha256 "$tmp/ubq.tar.gz")
[ "$want" = "$got" ] || err "checksum mismatch
    expected $want
    got      $got"
say "    checksum ok"

# --- unpack + install --------------------------------------------------------
tar -xzf "$tmp/ubq.tar.gz" -C "$tmp"
bin=$(find "$tmp" -type f -name ubq -perm -u+x 2>/dev/null | head -1)
[ -z "$bin" ] && bin=$(find "$tmp" -type f -name ubq | head -1)
[ -n "$bin" ] || err "archive did not contain a ubq binary"

mkdir -p "$DIR"
cp "$bin" "$DIR/ubq"
chmod +x "$DIR/ubq"
# macOS quarantines downloaded, unsigned binaries; clear it so it runs.
[ "$(uname -s)" = Darwin ] && xattr -d com.apple.quarantine "$DIR/ubq" 2>/dev/null || true

say "==> installed $DIR/ubq"

# --- PATH hint ---------------------------------------------------------------
case ":$PATH:" in
    *":$DIR:"*) say "    run 'ubq --help' to get started" ;;
    *)
        say ""
        say "$DIR is not on your PATH. Add it:"
        say "    export PATH=\"$DIR:\$PATH\""
        say "then reopen your shell (or add that line to ~/.profile / ~/.zshrc)."
        ;;
esac
