include $(TOPDIR)/rules.mk

PKG_NAME:=netbird
PKG_VERSION:=0.51.1
PKG_RELEASE:=2

PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://codeload.github.com/netbirdio/netbird/tar.gz/v$(PKG_VERSION)?
PKG_HASH:=8635b7a075038cd720e56728341b4639352798a9567ccad3718a1df4b906df0b

PKG_MAINTAINER:=Wesley Gimenes <wehagy@proton.me>
PKG_LICENSE:=BSD-3-Clause
PKG_LICENSE_FILES:=LICENSE

PKG_BUILD_DEPENDS:=golang/host
PKG_BUILD_PARALLEL:=1
PKG_BUILD_FLAGS:=no-mips16

GO_PKG:=github.com/netbirdio/netbird
GO_PKG_BUILD_PKG:=$(GO_PKG)/client
GO_PKG_LDFLAGS:=-s -w
GO_PKG_LDFLAGS_X:=$(GO_PKG)/version.version=$(PKG_VERSION)

include $(INCLUDE_DIR)/package.mk
include $(TOPDIR)/package/lang/golang/golang-package.mk

RSTRIP:=:
STRIP:=:

define Package/netbird
  SECTION:=net
  CATEGORY:=Network
  SUBMENU:=VPN
  TITLE:=Connect your devices into a single secure private WireGuard®-based mesh network
  URL:=https://netbird.io
  DEPENDS:=$(GO_ARCH_DEPENDS) +kmod-wireguard +iptables-mod-extra
  USERID:=netbird:netbird
  FATTRS:=/usr/bin/netbird::::cap_net_admin,cap_net_raw,cap_bpf+ep
endef

define Package/netbird/description
  NetBird is an open-source VPN management platform built on top of WireGuard® making it easy to create
  secure private networks for your organization or home.

  It requires zero configuration effort leaving behind the hassle of opening ports, complex firewall rules, VPN
  gateways, and so forth.
endef

define Build/Compile
	$(call GoPackage/Build/Compile)
	$(STAGING_DIR_HOST)/bin/upx -9 $(GO_PKG_BUILD_BIN_DIR)/client
endef

define Package/netbird/conffiles
/etc/netbird/config.json
/etc/config/netbird
endef

define Package/netbird/install
	$(call GoPackage/Package/Install/Bin,$(PKG_INSTALL_DIR))
	$(INSTALL_DIR) $(1)/usr/bin $(1)/etc/init.d $(1)/etc/config $(1)/etc/permtab.d
	$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/client $(1)/usr/bin/netbird
	$(INSTALL_BIN) ./files/netbird.init $(1)/etc/init.d/netbird
	$(INSTALL_CONF_USR) ./files/netbird.config $(1)/etc/config/netbird
	$(INSTALL_DATA) ./files/netbird.permtab $(1)/etc/permtab.d/netbird
endef

define Package/netbird/prerm
	#!/bin/sh
	. /lib/functions.sh

	clean_zones() {
		config_get name "$$1" name ""
		[ "$$name" = "netbird" ] && uci_remove firewall "$$1"
	}

	clean_forwardings() {
		config_get dest "$$1" dest ""
		config_get src "$$1" src ""
		[ "$$dest" = "netbird" ] || [ "$$src" = "netbird" ] && uci_remove firewall "$$1"
	}

	config_load 'firewall'
	config_foreach clean_zones "zone"
	config_foreach clean_forwardings "forwarding"
	uci_commit firewall
	/etc/init.d/firewall reload > /dev/null 2>&1
	exit 0
endef

$(eval $(call GoBinPackage,netbird))
$(eval $(call BuildPackage,netbird))
