#!/bin/sh
set -eu

EXPECTED_OS="NetBSD"
BINARY_OS="netbsd"
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 NetBSD. Detected: $OS" >&2
    exit 1
fi

case "$ARCH" in
    amd64|x86_64) BINARY_ARCH="amd64" ;;
    arm64|aarch64) 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 NetBSD / $BINARY_ARCH"
echo "Downloading $URL"

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

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