#
# Copyright (C) 2022-2024 IOPSYS Software Solutions AB
#

include $(TOPDIR)/rules.mk

PKG_NAME:=sshmngr
PKG_VERSION:=1.1.1

LOCAL_DEV:=0
ifneq ($(LOCAL_DEV),1)
PKG_SOURCE_PROTO:=git
PKG_SOURCE_URL:=https://dev.iopsys.eu/network/sshmngr.git
PKG_SOURCE_VERSION:=dc0e3933231680aec844d587d49fefbc0cc7f8d7
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION)-$(PKG_SOURCE_VERSION).tar.gz
PKG_MIRROR_HASH:=skip
endif

PKG_LICENSE:=BSD-3-Clause
PKG_LICENSE_FILES:=LICENSE

include $(INCLUDE_DIR)/package.mk
include ../bbfdm/bbfdm.mk

MAKE_PATH:=src

define Package/sshmngr
  SECTION:=net
  CATEGORY:=Network
  TITLE:=Package to add Device.SSH data model support.
  DEPENDS:=+libuci +libubox +libubus +libblobmsg-json +libjson-c
  DEPENDS+=+libbbfdm-api +libbbfdm-ubus +dm-service
  DEPENDS+=+SSHMNGR_BACKEND_OPENSSH:openssh-server +SSHMNGR_BACKEND_OPENSSH:openssh-client-utils
  DEPENDS+=+SSHMNGR_BACKEND_OPENSSH_PAM:openssh-server-pam +SSHMNGR_BACKEND_OPENSSH_PAM:openssh-client-utils
  DEPENDS+=+SSHMNGR_BACKEND_DROPBEAR:dropbear
  DEPENDS+=+SSHMNGR_SFTP:openssh-sftp-server
endef

define Package/sshmngr/description
  Package to add Device.SSH data model support.
endef

define Package/$(PKG_NAME)/config
        source "$(SOURCE)/Config.in"
endef

ifeq ($(LOCAL_DEV),1)
define Build/Prepare
	$(CP) -rf ./sshmngr/* $(PKG_BUILD_DIR)/
endef
endif

ifeq ($(CONFIG_SSHMNGR_BACKEND_DROPBEAR),y)
	TARGET_CFLAGS += -DDROPBEAR_BACKEND
endif

define Package/sshmngr/install
	$(INSTALL_DIR) $(1)/lib/sshmngr
	$(INSTALL_DIR) $(1)/usr/libexec/rpcd

	$(INSTALL_BIN) ./files/common/usr/libexec/rpcd/sshmngr $(1)/usr/libexec/rpcd/
ifeq ($(CONFIG_SSHMNGR_BACKEND_DROPBEAR),y)
	$(INSTALL_DATA) ./files/dropbear_backend/lib/sshmngr/backend.sh $(1)/lib/sshmngr/
else
	$(INSTALL_DATA) ./files/openssh_backend/lib/sshmngr/backend.sh $(1)/lib/sshmngr/
endif
	$(BBFDM_REGISTER_SERVICES) ./bbfdm_service.json $(1) $(PKG_NAME)
	$(BBFDM_INSTALL_MS_DM) $(PKG_BUILD_DIR)/src/libsshmngr.so $(1) $(PKG_NAME)

ifeq ($(CONFIG_PACKAGE_fail2ban),y)
	$(INSTALL_DIR) $(1)/etc/fail2ban/jail.d
	$(INSTALL_DIR) $(1)/etc/fail2ban/filter.d/
ifeq ($(CONFIG_SSHMNGR_BACKEND_DROPBEAR),y)
	$(INSTALL_CONF) ./files/dropbear_backend/fail2ban/sshmngr.local $(1)/etc/fail2ban/jail.d/
	$(INSTALL_DATA) ./files/dropbear_backend/fail2ban/sshmngr.conf $(1)/etc/fail2ban/filter.d/
else
	$(INSTALL_CONF) ./files/openssh_backend/fail2ban/sshmngr.local $(1)/etc/fail2ban/jail.d/
	$(INSTALL_DATA) ./files/openssh_backend/fail2ban/sshmngr.conf $(1)/etc/fail2ban/filter.d/
endif
endif
endef

$(eval $(call BuildPackage,sshmngr))
