#!/usr/bin/env bash
# Local distribution installer for the unmodified gateway converter executable.
set -euo pipefail
[[ ${EUID} -eq 0 ]] || { echo 'Run this installer as root.' >&2; exit 1; }
for command in wget tar sha256sum node systemctl; do
  command -v "$command" >/dev/null || { echo "Required command missing: $command" >&2; exit 1; }
done
node -e 'if (Number(process.versions.node.split(".")[0]) < 22) process.exit(1)' || { echo 'Node.js 22 or later is required.' >&2; exit 1; }
node <<'JS'
const fs = require('fs');
const paths = ['/root/zigbee2mqtt/package.json','/mnt/data/root/zigbee2mqtt/package.json','/mnt/data/zigbee2mqtt/package.json'];
const p = paths.find(x => fs.existsSync(x));
if (!p) { console.error('Install Zigbee2MQTT 2.5.1 or later first.'); process.exit(1); }
const v = JSON.parse(fs.readFileSync(p)).version.split('.').map(Number);
if (v[0] < 2 || (v[0] === 2 && (v[1] < 5 || (v[1] === 5 && v[2] < 1)))) {
 console.error('Zigbee2MQTT 2.5.1 or later is required.'); process.exit(1);
}
JS
# Retain the runtime path expected by the original executable and schema.
INSTALL_DIR=/mnt/data/ONOKOM
SERVICE=ok-converters.service
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
wget -O "$TMP/package.tar.xz" https://wirenboard.wiki/downloads/ventalen/ventalen-converters.tar.xz
printf '%s  %s\n' '52465137345e889fd585f0efd4a61f5441368f4a724ec180d9057fe3889c55b4' "$TMP/package.tar.xz" | sha256sum -c -
if [[ -d "$INSTALL_DIR/converters" ]]; then
  cp -a "$INSTALL_DIR/converters" "$INSTALL_DIR/converters.backup-$(date +%Y%m%d-%H%M%S)"
fi
mkdir -p "$INSTALL_DIR"
tar -xf "$TMP/package.tar.xz" -C "$INSTALL_DIR"
chmod +x "$INSTALL_DIR/converters/ok-converters"
SCHEMA_DST=/usr/share/wb-mqtt-confed/schemas/ok-schemas
mkdir -p "$SCHEMA_DST"
if [[ -f "$SCHEMA_DST/zb2wb.schema.json" ]]; then cp -a "$SCHEMA_DST/zb2wb.schema.json" "$SCHEMA_DST/zb2wb.schema.json.backup-$(date +%Y%m%d-%H%M%S)"; fi
cp "$INSTALL_DIR/converters/wb-confed/ok-schemas/zb2wb.schema.json" "$SCHEMA_DST/"
if [[ -f "/etc/systemd/system/$SERVICE" ]]; then cp -a "/etc/systemd/system/$SERVICE" "/etc/systemd/system/$SERVICE.backup-$(date +%Y%m%d-%H%M%S)"; fi
cat > "/etc/systemd/system/$SERVICE" <<UNIT
[Unit]
Description=Ventalen gateway UI converter
After=network-online.target
[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR/converters
ExecStart=$INSTALL_DIR/converters/ok-converters
User=root
Environment=LANG=C.UTF-8 LC_ALL=C.UTF-8
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable "$SERVICE"
systemctl restart "$SERVICE"
systemctl is-active --quiet "$SERVICE"
echo 'Ventalen gateway converter installed and running.'
