#!/bin/sh
# Install the Nugezza worker on Linux or a Mac (Apple Silicon):
#
#   curl -fsSL https://nugezza.com/downloads/install-worker.sh | sudo sh -s -- --key nze_…   (Linux)
#   curl -fsSL https://nugezza.com/downloads/install-worker.sh | sudo sh -s -- --key nze_…   (Mac)
#
# It downloads the program for this machine, checks it against the SHA-256
# the platform published, and runs its own installer (a system service on
# Linux, a launch daemon on a Mac — both start at power-on, nobody signs in).
# Without --key the PC joins as waiting for
# Approve on the admin page. A Synology NAS installs the .spk instead.
set -eu
SERVER="${NUGEZZA_SERVER:-https://nugezza.com}"
KEY=""; LABEL=""
while [ $# -gt 0 ]; do
  case "$1" in
    --key) KEY="$2"; shift 2 ;;
    --label) LABEL="$2"; shift 2 ;;
    --server) SERVER="$2"; shift 2 ;;
    *) echo "unknown option: $1" >&2; exit 2 ;;
  esac
done
OS="$(uname -s)"; ARCH="$(uname -m)"
case "$OS/$ARCH" in
  Linux/x86_64) P=linux ;;
  Linux/aarch64|Linux/arm64) P=linux-arm64 ;;
  Darwin/arm64) P=macos ;;
  *) echo "The Nugezza worker does not run on $OS $ARCH (Linux x64/ARM64 or a Mac with Apple Silicon)." >&2; exit 1 ;;
esac
REL="$(curl -fsSL "$SERVER/api/ai-worker/release?platform=$P")"
URL="$(printf '%s' "$REL" | sed -n 's/.*"url":"\([^"]*\)".*/\1/p')"
SHA="$(printf '%s' "$REL" | sed -n 's/.*"sha256":"\([0-9a-f]*\)".*/\1/p')"
[ -n "$URL" ] && [ -n "$SHA" ] || { echo "No Nugezza worker is published for $P yet." >&2; exit 1; }
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
curl -fL --progress-bar -o "$TMP/nugezza-worker" "$SERVER$URL"
if command -v sha256sum >/dev/null 2>&1; then GOT="$(sha256sum "$TMP/nugezza-worker" | cut -d' ' -f1)"; else GOT="$(shasum -a 256 "$TMP/nugezza-worker" | cut -d' ' -f1)"; fi
[ "$GOT" = "$SHA" ] || { echo "The download does not match its published checksum — not installed." >&2; exit 1; }
chmod 755 "$TMP/nugezza-worker"
set -- install --server "$SERVER"
[ -n "$KEY" ] && set -- "$@" --key "$KEY"
[ -n "$LABEL" ] && set -- "$@" --label "$LABEL"
"$TMP/nugezza-worker" "$@"
