include $(TOPDIR)/rules.mk

PKG_NAME:=client2server-unified
PKG_VERSION:=2.0.0
PKG_RELEASE:=1
PKG_LICENSE:=MIT
PKG_MAINTAINER:=Luis Rosales <lrosales@techno-world.net>

PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://git3.techno-world.net/lrosales/client2server

include $(INCLUDE_BASE)/package

define Package/$(PKG_NAME)
  SECTION:=utils
  CATEGORY:=Utilities
  TITLE:=Event forwarder for OpenWrt to central server
  DESCRIPTION:=All-in-one Lua event forwarder that monitors DHCP, WAN link, and forwards to central server via WebSocket with offline buffering
  DEPENDS:=+lua +luasocket +openssl-util
  TITLE:=Client2Server Unified
endef

define Package/$(PKG_NAME)/description
  All-in-one Lua event forwarder for OpenWrt routers.
  
  Features:
  - WebSocket connection with auto-reconnect
  - Local buffer (store-and-forward while offline)
  - DHCP lease events (new/expire) via luv + hotplug
  - WiFi connect/disconnect events via hotplug
  - WAN link state monitoring
  - DHCP IP changes (new ISP detection)
  - Bidirectional commands from server (uci_set, shell, reboot)
endef

define Build/Prepare
	mkdir -p $(PKG_BUILD_DIR)
	$(CP) ./src/* $(PKG_BUILD_DIR)/
	chmod +x $(PKG_BUILD_DIR)/*
endef

define Build/Configure
endef

define Build/Compile
endef

define Package/$(PKG_NAME)/install
	$(CP) $(PKG_BUILD_DIR)/* $(1)/usr/sbin/
	chmod +x $(1)/usr/sbin/*.lua

	# Init script
	$(INSTALL_DIR) $(1)/etc/init.d
	$(INSTALL_BIN) ./files/etc/init.d/client2server $(1)/etc/init.d/client2server

	# Config
	$(INSTALL_DIR) $(1)/etc/config
	$(INSTALL_DATA) ./files/etc/config/client2server $(1)/etc/config/client2server

	# Hotplug scripts (instant WiFi/DHCP events)
	$(INSTALL_DIR) $(1)/etc/hotplug.d/wireless
	$(INSTALL_BIN) ./hotplug/01-wifi $(1)/etc/hotplug.d/wireless/01-wifi
	$(INSTALL_DIR) $(1)/etc/hotplug.d/dhcp
	$(INSTALL_BIN) ./hotplug/02-dhcp $(1)/etc/hotplug.d/dhcp/02-dhcp

	# Shared hotplug lib (sourced by all hotplug scripts)
	$(INSTALL_DIR) $(1)/usr/share/client2server
	$(INSTALL_DATA) ./hotplug/_lib.sh $(1)/usr/share/client2server/hotplug-lib.sh
endef

$(eval $(call BuildPackage,$(PKG_NAME)))