include $(TOPDIR)/rules.mk

PKG_NAME:=kit-connect
PKG_VERSION:=0.1.0
PKG_RELEASE:=1

include $(INCLUDE_DIR)/package.mk

define Package/kit-connect
  SECTION:=net
  CATEGORY:=Network
  TITLE:=Pioneer Bus Fleet — Connectivity Agent
  DEPENDS:=+curl +openssh-client +tailscale
  PKGARCH:=all
endef

define Package/kit-connect/description
  Unified management connectivity for Pioneer bus fleet routers.
  Deploys Tailscale + reverse SSH tunnel. Hub auto-assigns ports.
  Includes one-button setup wizard and local status dashboard.

  Compatible: GL-XE3000, GL-MT3000, and all OpenWrt-based fleet routers.
endef

define Build/Compile
endef

define Package/kit-connect/install
	$(INSTALL_DIR) $(1)/etc/init.d $(1)/etc/config $(1)/etc/kitconnect
	$(INSTALL_DIR) $(1)/usr/sbin $(1)/www/kitconnect

	# Init + config
	$(INSTALL_BIN) ./files/etc/init.d/kitconnect $(1)/etc/init.d/kitconnect
	$(INSTALL_CONF) ./files/etc/config/kitconnect $(1)/etc/config/kitconnect

	# Binaries
	$(INSTALL_BIN) ./files/usr/sbin/connect-daemon.sh $(1)/usr/sbin/connect-daemon.sh
	$(INSTALL_BIN) ./files/usr/sbin/connect-register.sh $(1)/usr/sbin/connect-register.sh
	$(INSTALL_BIN) ./files/usr/sbin/connect-wizard.sh $(1)/usr/sbin/connect-wizard.sh

	# SSH key (private — must be 600)
	$(INSTALL_DATA) ./files/etc/kitconnect/connect_id_ed25519 $(1)/etc/kitconnect/connect_id_ed25519
	chmod 600 $(1)/etc/kitconnect/connect_id_ed25519

	# Web UI
	$(INSTALL_DATA) ./files/www/kitconnect/index.html $(1)/www/kitconnect/index.html
	$(INSTALL_BIN)  ./files/www/kitconnect/wizard.cgi $(1)/www/kitconnect/wizard.cgi
endef

define Package/kit-connect/postinst
#!/bin/sh
# Run the setup wizard on first install
if [ -z "$${IPKG_INSTROOT}" ]; then
	/etc/init.d/kitconnect enable 2>/dev/null || true
	/usr/sbin/connect-wizard.sh --auto 2>/dev/null || true
	/etc/init.d/kitconnect start 2>/dev/null || true
fi
endef

define Package/kit-connect/prerm
#!/bin/sh
# Stop service before removal
if [ -z "$${IPKG_INSTROOT}" ]; then
	/etc/init.d/kitconnect stop 2>/dev/null || true
	/etc/init.d/kitconnect disable 2>/dev/null || true
fi
endef

$(eval $(call BuildPackage,kit-connect))
