# Maintainer: Chi_Tang <me@chitang.dev>
# Maintainer: Integral <integral@member.fsf.org>

pkgname=throne
_srcname=Throne
pkgver=1.2.4
pkgrel=1
pkgdesc="Qt based cross-platform GUI proxy configuration manager (backend: sing-box)"
arch=('x86_64' 'aarch64' 'riscv64')
url="https://throneproj.github.io"
license=('GPL-3.0-or-later')
depends=('qt6-base' 'qt6-charts')
makedepends=('cmake' 'go' 'qt6-tools' 'protobuf' 'vulkan-headers')
optdepends=(
	'sing-geoip-db: geoip database for Throne'
	'sing-geosite-db: geosite database for Throne'
)
conflicts=('nekoray')
replaces=('nekoray')
source=(
	"${pkgname}-${pkgver}.tar.gz::https://github.com/throneproj/${_srcname}/archive/${pkgver}.tar.gz"
	"https://raw.githubusercontent.com/throneproj/routeprofiles/rule-set/srslist.h"
	"${pkgname}.sh"
	"${_srcname}.desktop"
)
sha512sums=('e7c90978eebf6d44e8db99f9f7bc67add22bdfd1aeffb094ceb3cb7a50d3fed24b91ca7a316ddaf1c59e249495ca62e0861099b136c6136b008d72dd55728e66'
            '93bf24ab74c38f4cb66cfe04d1d51e589a7692383e9b5a8369eb74c3f4f4dfdad108f540e3f62970fa7e916eba9a828446855e9090da4dc7e20c012bab9a775b'
            '28275441d2d1eb3203d3d4084666d5f8f8af03e29feee97fb758f6ba87396a45876221316e11aab1a159ef8a67fe8d62d75ff8d38131cb3dca3221bb1d98085c'
            'a47e8b547bd8759e7bc5c31f6055ad5ed3f6ee5879c07de8c05349b381578f907d3bdfb833fd5296fb4b20b6cacae6b622b2ab1fc7e46fce309cb273e82bc1c5')

prepare() {
	cd "${_srcname}-${pkgver}/"
	cp "${srcdir}/srslist.h" .

	cd core/server
	export GOBIN="${srcdir}/bin"
	export PATH="${PATH}:${GOBIN}"
	go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
	go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

	cd gen
	protoc -I . --go_out=. --go-grpc_out=. libcore.proto
}

build() {
	cd "${_srcname}-${pkgver}/"

	cmake -B build \
		-DCMAKE_BUILD_TYPE=None \
		-DCMAKE_INSTALL_PREFIX=/usr

	cmake --build build

	export CGO_CPPFLAGS="${CPPFLAGS}"
	export CGO_CFLAGS="${CFLAGS}"
	export CGO_CXXFLAGS="${CXXFLAGS}"
	export CGO_LDFLAGS="${LDFLAGS}"

	cd core/server

	VERSION_SINGBOX=$(go list -m -f '{{.Version}}' github.com/sagernet/sing-box)
	go build -o ../../build/ \
		-buildmode=pie \
		-trimpath \
		-ldflags "-linkmode=external -w -s -X 'github.com/sagernet/sing-box/constant.Version=${VERSION_SINGBOX}' -X 'internal/godebug.defaultGODEBUG=multipathtcp=0' -checklinkname=0" \
		-mod=readonly \
		-modcacherw \
		-tags "with_clash_api,with_gvisor,with_quic,with_wireguard,with_utls,with_dhcp,with_tailscale,badlinkname,tfogo_checklinkname0"
}

package() {
	install -Dm644 "${_srcname}.desktop" -t "${pkgdir}/usr/share/applications/"
	install -Dm755 "${pkgname}.sh" "${pkgdir}/usr/bin/${pkgname}"

	cd "${_srcname}-${pkgver}/"
	install -Dm644 "res/public/${_srcname}.png" -t "${pkgdir}/usr/share/pixmaps/"
	install -Dm755 build/Throne{,Core} -t "${pkgdir}/usr/lib/${pkgname}/"
}
