#!/bin/sh
# pyblox.com device agent installer (v632). Oryx-OS, Debian, Ubuntu, Raspberry Pi OS.
#   curl -fsSL https://pyblox.com/agent/install.sh | sh                 install only
#   curl -fsSL https://pyblox.com/agent/install.sh | sh -s -- CODE      install, then pair with CODE
# Also: PYBLOX_PAIR_CODE=CODE sh install.sh
# No prompts. Safe to run again: an unchanged agent is left as is, and an existing
# pairing is kept. Writes no token or secret unless you pair. HTTPS 443 only, no open ports.
# As a normal user it installs to ~/.local/bin/pyblox-com-agent.
# As root it also installs /usr/local/bin/pyblox-com-agent.
# This is the pyblox.com agent. It never touches the hub agent (pyblox-agent)
# or ~/.config/pyblox-agent/.
set -eu
URL="https://pyblox.com/agent/pyblox-agent.py"
SHA="021d910b508453b4103cb14cebe7cbc080930f0a712ea920904a794b330177d0"
CODE="${1:-${PYBLOX_PAIR_CODE:-}}"
command -v python3 >/dev/null 2>&1 || { echo "python3 is needed (apt install python3)"; exit 1; }
command -v curl >/dev/null 2>&1 || { echo "curl is needed (apt install curl)"; exit 1; }
put() {  # put SRC DEST MODE : install only if missing or different
  if [ -f "$2" ] && [ "$(sha256sum "$2" | cut -d' ' -f1)" = "$SHA" ]; then
    echo "Already up to date: $2"
  else
    mkdir -p "$(dirname "$2")"
    cp "$1" "$2.new" && chmod "$3" "$2.new" && mv -f "$2.new" "$2"
    echo "Installed $2"
  fi
}
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT
curl -fsSL --proto '=https' --tlsv1.2 "$URL" -o "$TMP"
if [ "$(sha256sum "$TMP" | cut -d' ' -f1)" != "$SHA" ]; then
  echo "Download check failed (sha256 mismatch). Nothing installed."; exit 1
fi
BIN="$HOME/.local/bin/pyblox-com-agent"
put "$TMP" "$BIN" 700
if [ "$(id -u)" = "0" ]; then
  put "$TMP" /usr/local/bin/pyblox-com-agent 755
fi
if [ -n "$CODE" ]; then
  python3 "$BIN" pair "$CODE"
else
  echo "Next: $BIN pair YOUR-CODE   (the code from pyblox.com Settings > Devices)"
fi
