#
# Copyright (C) 2026 Teltonika
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#

include $(TOPDIR)/rules.mk

PKG_NAME:=asterisk-config
PKG_RELEASE:=5
PKG_LICENSE:=GPL-2.0

include $(INCLUDE_DIR)/package.mk

define Package/asterisk-config/Default
  SUBMENU:=Telephony
  SECTION:=net
  CATEGORY:=Network
  DEPENDS:=+asterisk
endef

define Package/$(PKG_NAME)
$(call Package/asterisk-config/Default)
  TITLE:=Device-specific Asterisk configuration
endef

define Package/$(PKG_NAME)/description
 Device-specific Asterisk configuration overlay templates.
 Templates are copied on first boot or package install based on the
 detected device model and may replace defaults installed by other
 Asterisk packages.
endef

define Build/Configure
endef

define Build/Compile
endef

# map device to asterisk-config template family.
# this must mirror map_family() in files/90-asterisk-config
ASTERISK_FAMILY = $(strip \
	$(if $(filter teg100,$(call device_shortname)),teg100,\
	$(if $(filter rutx atrm50,$(call device_shortname)),rutx)))

define Package/$(PKG_NAME)/install
	$(INSTALL_DIR) $(1)/usr/share/asterisk-config
	if [ -z "$(ASTERISK_FAMILY)" ] || [ ! -d "./files/$(ASTERISK_FAMILY)" ]; then \
		echo "ERROR: no asterisk-config family for device_shortname '$(call device_shortname)' in $(PKG_NAME)." >&2; \
		exit 1; \
	fi
	$(CP) -r ./files/$(ASTERISK_FAMILY) $(1)/usr/share/asterisk-config/

	# Per-family UCI seed for /etc/config/asterisk; 90-asterisk-config
	# copies the matching one into /etc/config on first boot.
	$(INSTALL_DIR) $(1)/usr/share/asterisk-config/uci
	if [ -d "./files/uci/$(ASTERISK_FAMILY)" ]; then \
		$(CP) -r ./files/uci/$(ASTERISK_FAMILY) $(1)/usr/share/asterisk-config/uci/; \
	fi

	$(INSTALL_DIR) $(1)/usr/sbin
	$(INSTALL_BIN) ./files/asterisk-uci-gen $(1)/usr/sbin/asterisk-uci-gen
	$(INSTALL_BIN) ./files/generate_asterisk_tls_cert $(1)/usr/sbin/generate_asterisk_tls_cert

	$(INSTALL_DIR) $(1)/etc/uci-defaults
	$(INSTALL_BIN) ./files/90-asterisk-config \
		$(1)/etc/uci-defaults/90-asterisk-config

	# Re-register SIP trunks on interface-up (e.g. mobile WAN recovery)
	$(INSTALL_DIR) $(1)/etc/hotplug.d/iface
	$(INSTALL_DATA) ./files/asterisk-reregister.hotplug \
		$(1)/etc/hotplug.d/iface/99-asterisk-reregister
endef

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