#!/bin/sh
set -eu

EXPECTED_OS="Linux"
BINARY_OS="linux"
BASE_URL="https://sitebrush.com/download/latest/server-app"
INSTALL_PATH="/usr/local/bin/sitebrush"

OS="$(uname -s)"
ARCH="$(uname -m)"

if [ "$OS" != "$EXPECTED_OS" ]; then
    echo "This installer is for Linux. Detected: $OS" >&2
    exit 1
fi

case "$ARCH" in
    x86_64|amd64) BINARY_ARCH="amd64" ;;
    aarch64|arm64) BINARY_ARCH="arm64" ;;
    *) echo "Unsupported CPU architecture: $ARCH" >&2; exit 1 ;;
esac

URL="$BASE_URL/sitebrush_${BINARY_OS}_${BINARY_ARCH}"
TMP="${TMPDIR:-/tmp}/sitebrush.$$"
trap 'rm -f "$TMP"' EXIT HUP INT TERM

echo "SiteBrush installer"
echo "Detected Linux / $BINARY_ARCH"
echo "Downloading $URL"

if command -v curl >/dev/null 2>&1; then
    curl -fL "$URL" -o "$TMP"
elif command -v wget >/dev/null 2>&1; then
    wget -O "$TMP" "$URL"
else
    echo "curl or wget is required." >&2
    exit 1
fi

install -m 0755 "$TMP" "$INSTALL_PATH"
echo "Installed: $INSTALL_PATH"
"$INSTALL_PATH" -install
