Răsfoiți Sursa

feat(luci): luci-app-netpulse — node-local agent view (Phase 11) (#79)

* feat(luci): luci-app-netpulse — vista de nodo del agente (Fase 11) (#78)

Paquete LuCI moderno (JS cliente + plugin rpcd ucode, patrón
luci-app-example) con el alcance del ROADMAP §Fase 11:

- status.js: procd/PID, versión, RSS, uptime, heartbeat con frescura,
  logread -e netpulse con auto-refresco, botón restart y puente "Open
  NetPulse" con la URL de netpulse-agent.main.server (cero UCI nueva).
- settings.js: form.Map de /etc/config/netpulse-agent (server, slug,
  token password, interval, targets, insecure_tls); Save & Apply
  reinicia el agente vía el reload trigger existente.
- luci.netpulse (rpcd exec, ucode): status/logs/restart; ubus service
  list con fallback pidof; clamp de logs 10..300 con patrón fijo;
  parseo de /proc validado con proceso real.
- ACL mínima por sesión y menú en Servicios → NetPulse.
- Makefile plano (PKGARCH all, sin luci.mk: construye en SDK pelado) y
  package-luci.sh espejo del flujo del agente (.ipk ipkg-build, .apk
  SDK). Un artefacto para todos los routers.

Cero listener HTTP y cero RAM residente en el agente (criterio Fase 11);
el binario del agente no se toca.

Limitación conocida: el heartbeat lee /tmp/netpulse-agent.heartbeat,
que el agente v2.6.0 aún no escribe → "No heartbeat yet" hasta la
siguiente versión del agente.

* refactor(luci): eliminar pipe de logread, clase spinning, validar URL

- do_logs: split/slice/join en memoria en vez de tail con shell pipe
- handleRestart: cbi-modal-text en vez de spinning (no garantizada)
- settings: datatype url en el campo server (formato válido antes de guardar)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 4 luni în urmă
părinte
comite
1d7514537a

+ 82 - 0
deploy/openwrt/luci-app-netpulse/Makefile

@@ -0,0 +1,82 @@
+# luci-app-netpulse — OpenWrt Makefile (Fase 11)
+# Paquete LuCI de solo ficheros (JS/JSON/ucode, PKGARCH:=all): vista de nodo
+# del agente NetPulse. Makefile plano a propósito (no luci.mk): construye en
+# el SDK pelado igual que netpulse-agent, sin necesitar el feed luci en el
+# host de build. Las dependencias (luci-base) se resuelven al instalar.
+#
+# Uso (desde el SDK o buildroot de OpenWrt):
+#   cp -r luci-app-netpulse package/
+#   make package/luci-app-netpulse/compile V=s
+#
+# O empaquetado directo sin buildroot: deploy/openwrt/package-luci.sh
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=luci-app-netpulse
+PKG_VERSION:=2.7.2
+PKG_RELEASE:=1
+
+PKG_LICENSE:=AGPL-3.0-only
+PKG_MAINTAINER:=Nacho <netpulse@cloudless.club>
+PKGARCH:=all
+
+include $(INCLUDE_DIR)/package.mk
+
+define Package/luci-app-netpulse
+	SECTION:=luci
+	CATEGORY:=LuCI
+	SUBMENU:=3. Applications
+	TITLE:=Node-local NetPulse agent view for LuCI
+	URL:=https://github.com/gnacho/netpulse
+	DEPENDS:=+luci-base +netpulse-agent
+	PKGARCH:=all
+endef
+
+define Package/luci-app-netpulse/description
+	LuCI pages for the NetPulse agent on THIS router: procd status,
+	binary version, RSS, heartbeat, recent syslog lines, restart button
+	and editable UCI configuration, plus a link to the NetPulse web app
+	(network-wide view). Modern client-rendered LuCI (JS views + ucode
+	rpcd plugin); adds no HTTP listener or resident memory to the agent.
+endef
+
+# Sin compilación: todo son ficheros de texto.
+define Build/Compile
+endef
+
+define Package/luci-app-netpulse/install
+	$(INSTALL_DIR) $(1)/www/luci-static/resources/view/netpulse
+	$(INSTALL_DATA) ./files/www/luci-static/resources/view/netpulse/status.js $(1)/www/luci-static/resources/view/netpulse/
+	$(INSTALL_DATA) ./files/www/luci-static/resources/view/netpulse/settings.js $(1)/www/luci-static/resources/view/netpulse/
+
+	$(INSTALL_DIR) $(1)/usr/share/luci/menu.d
+	$(INSTALL_DATA) ./files/usr/share/luci/menu.d/luci-app-netpulse.json $(1)/usr/share/luci/menu.d/
+
+	$(INSTALL_DIR) $(1)/usr/share/rpcd/acl.d
+	$(INSTALL_DATA) ./files/usr/share/rpcd/acl.d/luci-app-netpulse.json $(1)/usr/share/rpcd/acl.d/
+
+	$(INSTALL_DIR) $(1)/usr/libexec/rpcd
+	$(INSTALL_BIN) ./files/usr/libexec/rpcd/luci.netpulse $(1)/usr/libexec/rpcd/luci.netpulse
+endef
+
+# rpcd descubre los plugins exec al arrancar y LuCI cachea el menú:
+# recargar ambos en instalación real (no en imagebuilder, $IPKG_INSTROOT).
+define Package/luci-app-netpulse/postinst
+#!/bin/sh
+if [ -z "$${IPKG_INSTROOT}" ]; then
+	/etc/init.d/rpcd restart 2>/dev/null || true
+	rm -f /tmp/luci-indexcache* 2>/dev/null || true
+fi
+exit 0
+endef
+
+define Package/luci-app-netpulse/postrm
+#!/bin/sh
+if [ -z "$${IPKG_INSTROOT}" ]; then
+	/etc/init.d/rpcd restart 2>/dev/null || true
+	rm -f /tmp/luci-indexcache* 2>/dev/null || true
+fi
+exit 0
+endef
+
+$(eval $(call BuildPackage,luci-app-netpulse))

+ 194 - 0
deploy/openwrt/luci-app-netpulse/files/usr/libexec/rpcd/luci.netpulse

@@ -0,0 +1,194 @@
+#!/usr/bin/ucode
+// luci.netpulse — plugin rpcd (protocolo exec) para luci-app-netpulse.
+//
+// Expone el estado LOCAL del agente sin abrir ningún puerto ni tocar el
+// binario del agente (criterio Fase 11: cero superficie/RAM extra):
+//
+//   status  → procd/pid, RSS, uptime del proceso, versión del binario,
+//             heartbeat (/tmp, epoch s) y si el servicio está habilitado.
+//   logs    → últimas N líneas de `logread -e netpulse` (10..300).
+//   restart → /etc/init.d/netpulse-agent restart (el "rearme" local).
+//
+// rpcd lo invoca como ejecutable: `list` imprime la firma de métodos;
+// `call <método>` recibe los argumentos JSON por stdin e imprime el
+// resultado JSON. El acceso por sesión lo limita la ACL
+// /usr/share/rpcd/acl.d/luci-app-netpulse.json.
+//
+// ubus se carga con require() dentro de la función (no import top-level):
+// si el módulo no está, se degrada a `pidof` en vez de romper el plugin.
+
+'use strict';
+
+const fs = require('fs');
+
+const INIT = '/etc/init.d/netpulse-agent';
+const BIN = '/usr/sbin/netpulse-agent';
+const HEARTBEAT = '/tmp/netpulse-agent.heartbeat';
+
+// popen_all ejecuta cmd por shell y devuelve stdout completo (o null).
+function popen_all(cmd) {
+	let p = fs.popen(cmd, 'r');
+	if (!p)
+		return null;
+	let out = p.read('all');
+	p.close();
+	return out;
+}
+
+// agent_pid: PID vía `ubus service list` (procd, fuente canónica) con
+// fallback a pidof (BusyBox) si ubus/el módulo no están disponibles.
+function agent_pid() {
+	try {
+		let ubus = require('ubus');
+		let conn = ubus.connect();
+		if (conn) {
+			let res = conn.call('service', 'list', { name: 'netpulse-agent' });
+			conn.disconnect();
+			let inst = res?.['netpulse-agent']?.instances;
+			for (let name in inst) {
+				let i = inst[name];
+				if (i?.running && int(i.pid) > 0)
+					return int(i.pid);
+			}
+		}
+	}
+	catch (e) {
+		// sin ubus: caemos a pidof
+	}
+	let out = popen_all('pidof netpulse-agent 2>/dev/null');
+	if (out) {
+		let pid = int(split(trim(out), ' ')[0]);
+		if (pid > 0)
+			return pid;
+	}
+	return 0;
+}
+
+// proc_rss_kb: VmRSS del proceso en KiB (null si no legible).
+function proc_rss_kb(pid) {
+	let st = fs.readfile(sprintf('/proc/%d/status', pid), 8192);
+	if (!st)
+		return null;
+	let m = match(st, /VmRSS:[ \t]+([0-9]+)[ \t]+kB/);
+	return m ? int(m[1]) : null;
+}
+
+// proc_uptime_s: segundos de vida del proceso — starttime (campo 22 de
+// /proc/pid/stat, en ticks de 100 Hz) contra /proc/uptime. El comm puede
+// llevar espacios/paréntesis: se parte por el ÚLTIMO ')'.
+function proc_uptime_s(pid) {
+	let stat = fs.readfile(sprintf('/proc/%d/stat', pid), 2048);
+	let up = fs.readfile('/proc/uptime', 128);
+	if (!stat || !up)
+		return null;
+	let rp = rindex(stat, ')');
+	if (rp < 0)
+		return null;
+	let f = split(trim(substr(stat, rp + 2)), ' ');
+	// f[0] = state (campo 3) → starttime (campo 22) = f[19]
+	let start_ticks = int(f[19]);
+	let boot_s = int(split(trim(up), '.')[0]);
+	if (start_ticks <= 0 || boot_s <= 0)
+		return null;
+	let secs = int(boot_s - start_ticks / 100);
+	return secs >= 0 ? secs : 0;
+}
+
+function do_status() {
+	let pid = agent_pid();
+	let running = pid > 0;
+
+	let res = {
+		installed: !!fs.access(BIN),
+		enabled: system([ INIT, 'enabled' ], 5000) == 0,
+		running: running,
+		pid: running ? pid : null,
+		rss_kb: running ? proc_rss_kb(pid) : null,
+		uptime_s: running ? proc_uptime_s(pid) : null,
+		version: null,
+		heartbeat_ts: null,
+		heartbeat_age_s: null
+	};
+
+	if (res.installed) {
+		let v = popen_all(BIN + ' --version 2>/dev/null');
+		if (v && trim(v) != '')
+			res.version = split(trim(v), '\n')[0];
+	}
+
+	// Heartbeat: epoch en segundos escrito por el agente tras cada push
+	// (agent/internal/heartbeat). Sin fichero (reboot reciente) → null.
+	let hb = fs.readfile(HEARTBEAT, 64);
+	if (hb) {
+		let ts = int(trim(hb));
+		if (ts > 0) {
+			res.heartbeat_ts = ts;
+			let age = time() - ts;
+			res.heartbeat_age_s = age >= 0 ? age : 0;
+		}
+	}
+	return res;
+}
+
+function do_logs(args) {
+	let n = int(args?.lines ?? 50);
+	if (n < 10)
+		n = 10;
+	if (n > 300)
+		n = 300;
+
+	// Leemos logread completo y procesamos en memoria (ucode nativo,
+	// cero shell string y cero pipes). En un router doméstico los logs
+	// de netpulse son de pocos KB: split/slice/join es más limpio.
+	let out = popen_all('logread -e netpulse 2>/dev/null');
+	if (!out)
+		return { lines: '' };
+
+	let lines = split(out, '\n');
+	if (length(lines) > 0 && lines[length(lines) - 1] === '')
+		lines = slice(lines, 0, -1);
+
+	let start = length(lines) - n;
+	if (start < 0)
+		start = 0;
+
+	return { lines: join('\n', slice(lines, start)) };
+}
+
+function do_restart() {
+	let rc = system([ INIT, 'restart' ], 20000);
+	return { ok: rc == 0, code: rc };
+}
+
+// ── Dispatcher del protocolo exec de rpcd ────────────────────────────────
+if (ARGV[0] == 'list') {
+	printf('%J\n', { status: {}, logs: { lines: 50 }, restart: {} });
+	exit(0);
+}
+
+if (ARGV[0] == 'call') {
+	let args = {};
+	try {
+		let raw = fs.stdin.read('all');
+		if (raw && trim(raw) != '')
+			args = json(raw);
+	}
+	catch (e) {
+		args = {};
+	}
+
+	if (ARGV[1] == 'status') {
+		printf('%J\n', do_status());
+		exit(0);
+	}
+	if (ARGV[1] == 'logs') {
+		printf('%J\n', do_logs(args));
+		exit(0);
+	}
+	if (ARGV[1] == 'restart') {
+		printf('%J\n', do_restart());
+		exit(0);
+	}
+}
+
+exit(1);

+ 30 - 0
deploy/openwrt/luci-app-netpulse/files/usr/share/luci/menu.d/luci-app-netpulse.json

@@ -0,0 +1,30 @@
+{
+	"admin/services/netpulse": {
+		"title": "NetPulse",
+		"order": 60,
+		"action": {
+			"type": "firstchild"
+		},
+		"depends": {
+			"acl": [ "luci-app-netpulse" ]
+		}
+	},
+
+	"admin/services/netpulse/status": {
+		"title": "Status",
+		"order": 10,
+		"action": {
+			"type": "view",
+			"path": "netpulse/status"
+		}
+	},
+
+	"admin/services/netpulse/settings": {
+		"title": "Settings",
+		"order": 20,
+		"action": {
+			"type": "view",
+			"path": "netpulse/settings"
+		}
+	}
+}

+ 17 - 0
deploy/openwrt/luci-app-netpulse/files/usr/share/rpcd/acl.d/luci-app-netpulse.json

@@ -0,0 +1,17 @@
+{
+	"luci-app-netpulse": {
+		"description": "Grant access to the NetPulse agent pages",
+		"read": {
+			"ubus": {
+				"luci.netpulse": [ "status", "logs" ]
+			},
+			"uci": [ "netpulse-agent" ]
+		},
+		"write": {
+			"ubus": {
+				"luci.netpulse": [ "restart" ]
+			},
+			"uci": [ "netpulse-agent" ]
+		}
+	}
+}

+ 58 - 0
deploy/openwrt/luci-app-netpulse/files/www/luci-static/resources/view/netpulse/settings.js

@@ -0,0 +1,58 @@
+'use strict';
+'require view';
+'require form';
+
+/*
+ * netpulse/settings — edición de /etc/config/netpulse-agent (Fase 11).
+ * "Save & Apply" hace uci commit + reload_config; el init del agente
+ * declara procd_add_reload_trigger, así que el servicio se reinicia solo
+ * con la config nueva — sin botones extra ni ejecuciones a mano.
+ */
+
+return view.extend({
+	render: function() {
+		var m, s, o;
+
+		m = new form.Map('netpulse-agent', _('NetPulse agent'),
+			_('Connection of the local agent to the NetPulse server. ' +
+			  'Saving applies the change and restarts the agent automatically.'));
+
+		s = m.section(form.NamedSection, 'main', 'main', _('Connection'));
+		s.addremove = false;
+
+		o = s.option(form.Value, 'server', _('Server URL'),
+			_('Base URL of the NetPulse server, e.g. http://192.168.1.226:3000.'));
+	o.placeholder = 'http://192.168.1.226:3000';
+	o.rmempty = false;
+	o.datatype = 'url';
+
+		o = s.option(form.Value, 'slug', _('Slug'),
+			_('Identifier of this router in NetPulse (as created in Settings → Agents).'));
+		o.rmempty = false;
+
+		o = s.option(form.Value, 'token', _('Token'),
+			_('Per-device token (64 hex). Shown once when the agent is created on the server.'));
+		o.password = true;
+		o.rmempty = false;
+
+		o = s.option(form.Value, 'interval', _('Push interval'),
+			_('Full probe cycle. Plain seconds or a Go duration ("30", "15s", "1m").'));
+		o.placeholder = '30s';
+
+		o = s.option(form.Value, 'wan_target', _('WAN ping target'),
+			_('Gateway only: public IP probed for WAN loss/latency (e.g. 1.1.1.1). Leave empty on access points.'));
+		o.datatype = 'host';
+		o.rmempty = true;
+
+		o = s.option(form.Value, 'gw_target', _('Gateway ping target'),
+			_('Access points only: LAN IP of the gateway for the short latency probe. Leave empty on the gateway.'));
+		o.datatype = 'host';
+		o.rmempty = true;
+
+		o = s.option(form.Flag, 'insecure_tls', _('Accept self-signed TLS'),
+			_('Skips server certificate verification. Only for LANs without a CA; scheduled for removal once fingerprint pinning lands (Fase 9).'));
+		o.rmempty = true;
+
+		return m.render();
+	}
+});

+ 206 - 0
deploy/openwrt/luci-app-netpulse/files/www/luci-static/resources/view/netpulse/status.js

@@ -0,0 +1,206 @@
+'use strict';
+'require view';
+'require rpc';
+'require poll';
+'require uci';
+'require ui';
+
+/*
+ * netpulse/status — vista de nodo (Fase 11): estado LOCAL del agente en
+ * ESTE router, leído del plugin rpcd luci.netpulse (procd + /proc +
+ * heartbeat + logread). Complementa a la webapp sin duplicarla: el puente
+ * "Open NetPulse" usa la URL del servidor ya configurada en UCI.
+ */
+
+var callStatus = rpc.declare({
+	object: 'luci.netpulse',
+	method: 'status',
+	expect: { }
+});
+
+var callLogs = rpc.declare({
+	object: 'luci.netpulse',
+	method: 'logs',
+	params: [ 'lines' ],
+	expect: { }
+});
+
+var callRestart = rpc.declare({
+	object: 'luci.netpulse',
+	method: 'restart',
+	expect: { }
+});
+
+var LOG_LINES = 80;
+
+function fmtDuration(s) {
+	if (s == null || s < 0)
+		return '—';
+	if (s < 60)
+		return '%ds'.format(s);
+	if (s < 3600)
+		return '%dm %ds'.format(Math.floor(s / 60), s % 60);
+	if (s < 86400)
+		return '%dh %dm'.format(Math.floor(s / 3600), Math.floor((s % 3600) / 60));
+	return '%dd %dh'.format(Math.floor(s / 86400), Math.floor((s % 86400) / 3600));
+}
+
+function fmtRss(kb) {
+	if (kb == null)
+		return '—';
+	return '%.1f MiB'.format(kb / 1024);
+}
+
+function badge(text, kind) {
+	/* kind: ok | warn | err — colores propios para no depender de clases
+	 * concretas del tema activo. */
+	var colors = { ok: '#2e7d32', warn: '#b26a00', err: '#c62828' };
+	return E('span', {
+		'style': 'display:inline-block;padding:1px 8px;border-radius:9px;' +
+			'color:#fff;font-size:90%;background:' + (colors[kind] || '#666')
+	}, text);
+}
+
+function serviceBadge(st) {
+	if (!st.installed)
+		return badge(_('Not installed'), 'err');
+	if (!st.running)
+		return badge(_('Stopped'), 'err');
+	return badge(_('Running (PID %d)').format(st.pid), 'ok');
+}
+
+function heartbeatBadge(st) {
+	if (st.heartbeat_age_s == null)
+		return badge(_('No heartbeat yet'), 'warn');
+	/* El agente late tras cada ciclo de push (30 s por defecto); el
+	 * watchdog del router actúa a los 300 s. Umbral visual intermedio. */
+	if (st.heartbeat_age_s <= 90)
+		return badge(_('Pushing (%s ago)').format(fmtDuration(st.heartbeat_age_s)), 'ok');
+	return badge(_('Stalled (%s ago)').format(fmtDuration(st.heartbeat_age_s)), 'warn');
+}
+
+function updateView(st, logs) {
+	var set = function(id, node) {
+		var el = document.getElementById(id);
+		if (!el)
+			return;
+		while (el.firstChild)
+			el.removeChild(el.firstChild);
+		el.appendChild(typeof node == 'string' ? document.createTextNode(node) : node);
+	};
+
+	set('np-service', serviceBadge(st));
+	set('np-heartbeat', heartbeatBadge(st));
+	set('np-version', st.version || '—');
+	set('np-enabled', st.enabled ? _('Yes') : _('No'));
+	set('np-rss', fmtRss(st.rss_kb));
+	set('np-uptime', fmtDuration(st.uptime_s));
+
+	var pre = document.getElementById('np-logs');
+	if (pre) {
+		var atBottom = (pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 8);
+		pre.textContent = logs || _('(no log lines matched)');
+		if (atBottom)
+			pre.scrollTop = pre.scrollHeight;
+	}
+}
+
+function handleRestart() {
+	ui.showModal(_('Restarting'), [
+		E('p', { 'class': 'cbi-modal-text' }, _('Restarting the NetPulse agent…'))
+	]);
+	return callRestart().then(function(res) {
+		ui.hideModal();
+		if (res && res.ok)
+			ui.addNotification(null, E('p', _('NetPulse agent restarted.')), 'info');
+		else
+			ui.addNotification(null, E('p', _('Restart failed (exit code %s).').format(res ? res.code : '?')), 'error');
+	}).catch(function(err) {
+		ui.hideModal();
+		ui.addNotification(null, E('p', _('Restart failed: %s').format(err.message)), 'error');
+	});
+}
+
+function row(label, id, initial) {
+	return E('tr', { 'class': 'tr' }, [
+		E('td', { 'class': 'td left', 'width': '33%' }, label),
+		E('td', { 'class': 'td left', 'id': id }, [ initial != null ? initial : '—' ])
+	]);
+}
+
+return view.extend({
+	handleSave: null,
+	handleSaveApply: null,
+	handleReset: null,
+
+	load: function() {
+		return Promise.all([
+			uci.load('netpulse-agent'),
+			callStatus().catch(function() { return {}; }),
+			callLogs(LOG_LINES).catch(function() { return {}; })
+		]);
+	},
+
+	render: function(data) {
+		var st = data[1] || {};
+		var logs = (data[2] && data[2].lines) || '';
+		var server = uci.get('netpulse-agent', 'main', 'server') || '';
+		var slug = uci.get('netpulse-agent', 'main', 'slug') || '';
+
+		var buttons = [
+			E('button', {
+				'class': 'btn cbi-button cbi-button-action',
+				'click': function() { handleRestart(); }
+			}, _('Restart agent'))
+		];
+		if (server != '') {
+			buttons.push(' ');
+			buttons.push(E('a', {
+				'class': 'btn cbi-button cbi-button-apply',
+				'href': server,
+				'target': '_blank',
+				'rel': 'noopener'
+			}, _('Open NetPulse ↗')));
+		}
+
+		var root = E('div', { 'class': 'cbi-map' }, [
+			E('h2', {}, _('NetPulse')),
+			E('div', { 'class': 'cbi-map-descr' },
+				slug != ''
+					? _('Local state of the NetPulse agent on this router (slug “%s”). The network-wide view lives in the NetPulse web app.').format(slug)
+					: _('Local state of the NetPulse agent on this router. The network-wide view lives in the NetPulse web app.')),
+
+			E('div', { 'class': 'cbi-section' }, [
+				E('table', { 'class': 'table' }, [
+					row(_('Service'), 'np-service', serviceBadge(st)),
+					row(_('Heartbeat'), 'np-heartbeat', heartbeatBadge(st)),
+					row(_('Agent version'), 'np-version', st.version || '—'),
+					row(_('Start on boot'), 'np-enabled', st.enabled ? _('Yes') : _('No')),
+					row(_('Memory (RSS)'), 'np-rss', fmtRss(st.rss_kb)),
+					row(_('Process uptime'), 'np-uptime', fmtDuration(st.uptime_s))
+				]),
+				E('div', { 'style': 'margin-top:.5em' }, buttons)
+			]),
+
+			E('div', { 'class': 'cbi-section' }, [
+				E('h3', {}, _('Recent log')),
+				E('pre', {
+					'id': 'np-logs',
+					'style': 'height:20em;overflow:auto;font-size:90%;' +
+						'white-space:pre-wrap;word-break:break-all'
+				}, [ logs || _('(no log lines matched)') ])
+			])
+		]);
+
+		poll.add(function() {
+			return Promise.all([
+				callStatus().catch(function() { return {}; }),
+				callLogs(LOG_LINES).catch(function() { return {}; })
+			]).then(function(r) {
+				updateView(r[0] || {}, (r[1] && r[1].lines) || '');
+			});
+		}, 5);
+
+		return root;
+	}
+});

+ 112 - 0
deploy/openwrt/package-luci.sh

@@ -0,0 +1,112 @@
+#!/bin/bash
+# package-luci.sh — empaqueta luci-app-netpulse en .ipk y .apk con el SDK.
+# Espejo de package.sh (agente) sin la parte de binario: el paquete es solo
+# ficheros (PKGARCH all), así que el MISMO artefacto vale para gateway y APs.
+#
+# Uso:
+#   package-luci.sh <SDK_VERSION> <SDK_TARGET> <SDK_SUBTARGET> <FORMAT>
+#
+#   SDK_VERSION:  24.10.5  o  25.12.5
+#   SDK_TARGET:   mediatek/filogic  o  qualcommax/ipq807x
+#   SDK_SUBTARGET: (vacío, se detecta solo)
+#   FORMAT:       ipk  o  apk
+#
+# Ejemplo:
+#   package-luci.sh 24.10.5 mediatek/filogic "" ipk
+#   package-luci.sh 25.12.5 qualcommax/ipq807x "" apk
+
+set -euo pipefail
+
+SDK_VERSION="${1:?falta SDK_VERSION}"
+SDK_TARGET="${2:?falta SDK_TARGET}"
+SDK_SUBTARGET="${3:-}"
+FORMAT="${4:?falta FORMAT (ipk|apk)}"
+
+echo "=== package-luci.sh: $FORMAT SDK=$SDK_VERSION target=$SDK_TARGET ==="
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+APP_DIR="$SCRIPT_DIR/luci-app-netpulse"
+WORK_DIR="$(mktemp -d)"
+trap 'rm -rf "$WORK_DIR"' EXIT
+
+PKG_VERSION=$(sed -n 's/^PKG_VERSION:=//p' "$APP_DIR/Makefile" | head -1)
+PKG_RELEASE=$(sed -n 's/^PKG_RELEASE:=//p' "$APP_DIR/Makefile" | head -1)
+
+# ── SDK URL (mismo esquema que package.sh) ───────────────────────────
+SDK_NAME="openwrt-sdk-${SDK_VERSION}-${SDK_TARGET//\//-}_gcc-13.3.0_musl.Linux-x86_64"
+SDK_URL="https://downloads.openwrt.org/releases/${SDK_VERSION}/targets/${SDK_TARGET}/${SDK_NAME}.tar.zst"
+
+echo "  SDK: $SDK_URL"
+
+cd "$WORK_DIR"
+curl -fsSL "$SDK_URL" -o sdk.tar.zst
+tar --zstd -xf sdk.tar.zst
+SDK_DIR="$WORK_DIR/$SDK_NAME"
+
+OUT_DIR="$REPO_ROOT/dist/packages"
+mkdir -p "$OUT_DIR"
+
+if [ "$FORMAT" = "ipk" ]; then
+  echo "  Construyendo .ipk (ipkg-build, arch all)..."
+  PKG_DIR="$WORK_DIR/luci-app-netpulse-pkg"
+  mkdir -p "$PKG_DIR/CONTROL"
+  cp -r "$APP_DIR/files/." "$PKG_DIR/"
+  chmod 755 "$PKG_DIR/usr/libexec/rpcd/luci.netpulse"
+
+  cat > "$PKG_DIR/CONTROL/control" << CTRL
+Package: luci-app-netpulse
+Version: ${PKG_VERSION:-0.0.0}-${PKG_RELEASE:-1}
+Depends: luci-base, netpulse-agent
+License: AGPL-3.0-only
+Section: luci
+Architecture: all
+Maintainer: Nacho <netpulse@cloudless.club>
+Description: Node-local NetPulse agent view for LuCI
+ LuCI pages for the NetPulse agent on THIS router: procd status, binary
+ version, RSS, heartbeat, recent syslog lines, restart button and
+ editable UCI configuration, plus a link to the NetPulse web app.
+CTRL
+
+  cat > "$PKG_DIR/CONTROL/postinst" << 'POSTINST'
+#!/bin/sh
+[ -n "$IPKG_INSTROOT" ] && exit 0
+/etc/init.d/rpcd restart 2>/dev/null || true
+rm -f /tmp/luci-indexcache* 2>/dev/null || true
+exit 0
+POSTINST
+  chmod 755 "$PKG_DIR/CONTROL/postinst"
+
+  cat > "$PKG_DIR/CONTROL/postrm" << 'POSTRM'
+#!/bin/sh
+[ -n "$IPKG_INSTROOT" ] && exit 0
+/etc/init.d/rpcd restart 2>/dev/null || true
+rm -f /tmp/luci-indexcache* 2>/dev/null || true
+exit 0
+POSTRM
+  chmod 755 "$PKG_DIR/CONTROL/postrm"
+
+  "$SDK_DIR/scripts/ipkg-build" "$PKG_DIR" "$OUT_DIR"
+  echo "  IPK: $(ls "$OUT_DIR"/luci-app-netpulse_*.ipk)"
+
+elif [ "$FORMAT" = "apk" ]; then
+  echo "  Construyendo .apk vía SDK..."
+  cp -r "$APP_DIR" "$SDK_DIR/package/luci-app-netpulse"
+
+  cd "$SDK_DIR"
+  # luci-base solo como dependencia de instalación; el feed luci se indexa
+  # para que el resolutor del SDK la conozca.
+  ./scripts/feeds update luci 2>/dev/null || true
+  ./scripts/feeds install luci-base 2>/dev/null || true
+  make defconfig >/dev/null 2>&1 || true
+  make package/luci-app-netpulse/compile V=s 2>&1 | tail -20
+
+  find bin/packages -name "luci-app-netpulse*.apk" -exec cp {} "$OUT_DIR/" \;
+  echo "  APK: $(ls "$OUT_DIR"/luci-app-netpulse*.apk 2>/dev/null || echo 'NO ENCONTRADO')"
+
+else
+  echo "ERROR: FORMAT debe ser ipk o apk" >&2
+  exit 1
+fi
+
+echo "=== package-luci.sh: OK ==="