#!/bin/sh
# Meris worker installer (macOS, Linux).
#   curl -fsSL https://app.meris.network/install.sh | sh -s -- ABCD-1234   install, pair and start
#   curl -fsSL https://app.meris.network/install.sh | sh                   install only
# Uses Node.js 22.4+ when it is installed; otherwise downloads a private copy into ~/.meris/node.
set -e

ORIGIN="https://app.meris.network"
DIR="$HOME/.meris"
FILE="$DIR/meris-worker.mjs"
CHECK='const [a,b]=process.versions.node.split(/[.]/).map(Number);process.exit(a>22||(a===22&&b>=4)?0:1)'

say() { printf '%s\n' "$*"; }
mkdir -p "$DIR"
say "Setting up the Meris worker. This takes about a minute, keep this window open."

NODE=""
if command -v node >/dev/null 2>&1 && node -e "$CHECK" >/dev/null 2>&1; then
  NODE="$(command -v node)"
elif [ -x "$DIR/node/bin/node" ]; then
  NODE="$DIR/node/bin/node"
else
  case "$(uname -s)" in
    Darwin) os=darwin ;;
    Linux) os=linux ;;
    *) say "This system is not supported. Install Node.js 22 from https://nodejs.org and run this again."; exit 1 ;;
  esac
  case "$(uname -m)" in
    x86_64 | amd64) cpu=x64 ;;
    arm64 | aarch64) cpu=arm64 ;;
    *) say "This processor ($(uname -m)) is not supported. Install Node.js 22 from https://nodejs.org and run this again."; exit 1 ;;
  esac
  base="https://nodejs.org/dist/latest-v22.x"
  say "Downloading Node.js 22 for the worker (about 30 MB)..."
  line="$(curl -fsSL "$base/SHASUMS256.txt" | grep "  node-v[0-9.]*-$os-$cpu\.tar\.gz\$" | head -n 1)"
  [ -n "$line" ] || { say "Could not find Node.js for $os-$cpu. Install Node.js 22 from https://nodejs.org and run this again."; exit 1; }
  sum="${line%% *}"
  tarball="${line##* }"
  tmp="$(mktemp -d)"
  curl -fsSL "$base/$tarball" -o "$tmp/$tarball"
  if command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$tmp/$tarball" | cut -d ' ' -f 1)"; else actual="$(shasum -a 256 "$tmp/$tarball" | cut -d ' ' -f 1)"; fi
  [ "$actual" = "$sum" ] || { rm -rf "$tmp"; say "The Node.js download was corrupted. Run this again."; exit 1; }
  rm -rf "$DIR/node"
  mkdir -p "$DIR/node"
  tar -xzf "$tmp/$tarball" -C "$DIR/node" --strip-components 1
  rm -rf "$tmp"
  NODE="$DIR/node/bin/node"
fi

curl -fsSL "$ORIGIN/downloads/meris-worker.mjs" -o "$FILE"
printf '#!/bin/sh\nexec "%s" "%s" "$@"\n' "$NODE" "$FILE" > "$DIR/meris"
chmod +x "$DIR/meris"
say "Meris worker 0.2.0 installed."

if [ -n "$1" ]; then
  MERIS_INSTALLER=1 "$NODE" "$FILE" pair "$1"
  MERIS_INSTALLER=1 "$NODE" "$FILE" start
elif [ -f "$DIR/worker.json" ]; then
  "$NODE" "$FILE" start
else
  say ""
  say "Copy the command from $ORIGIN/worker instead: it includes your pairing code. Or pair by hand:"
  say "  ~/.meris/meris pair ABCD-1234"
  say "  ~/.meris/meris start"
fi
