#!/bin/sh
set -e

URL="https://farpy.com/node/farpy-nodemuncher-linux-v1.tar.gz"

echo "== NodeMuncher (Linux) installer =="
echo "Downloading: $URL"

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

curl -fsSL "$URL" -o "$TMP/nodemuncher.tgz"
tar -xzf "$TMP/nodemuncher.tgz" -C "$TMP"

BIN="$(find "$TMP" -maxdepth 4 -type f \( -name "nodemuncher" -o -name "nodemuncher-linux*" \) 2>/dev/null | head -n 1 || true)"
if [ -z "$BIN" ]; then
  echo "ERR: could not find nodemuncher binary inside tarball"
  exit 2
fi

chmod +x "$BIN"
sudo install -m 0755 "$BIN" /usr/local/bin/nodemuncher

sudo tee /etc/systemd/system/nodemuncher.service >/dev/null <<'UNIT'
[Unit]
Description=NodeMuncher (Farpy worker)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/nodemuncher
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target
UNIT

sudo systemctl daemon-reload
sudo systemctl enable --now nodemuncher.service

echo "OK:INSTALLED"
