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

pkgname=throne-git
_pkgname=${pkgname%-git}
_srcname=Throne
pkgver=1.2.4.r0.g33777e2
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=('git' 'cmake' 'go' 'qt6-tools' 'protobuf' 'vulkan-headers')
optdepends=(
	'sing-geoip-db: geoip database for Throne'
	'sing-geosite-db: geosite database for Throne'
)
conflicts=('throne' 'nekoray-git')
provides=('throne')
replaces=('nekoray-git')
source=(
	"git+https://github.com/throneproj/${_srcname}.git"
	"https://raw.githubusercontent.com/throneproj/routeprofiles/rule-set/srslist.h"
	"${_pkgname}.sh"
	"${_srcname}.desktop"
)
sha512sums=('SKIP'
            'SKIP'
            '28275441d2d1eb3203d3d4084666d5f8f8af03e29feee97fb758f6ba87396a45876221316e11aab1a159ef8a67fe8d62d75ff8d38131cb3dca3221bb1d98085c'
            'a47e8b547bd8759e7bc5c31f6055ad5ed3f6ee5879c07de8c05349b381578f907d3bdfb833fd5296fb4b20b6cacae6b622b2ab1fc7e46fce309cb273e82bc1c5')

pkgver() {
	git -C "${_srcname}" describe --long --tags --abbrev=7 | sed 's/\([^-]*-g\)/r\1/;s/-/./g'
}

prepare() {
	cd "${_srcname}/"
	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}/"

	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,with_purego,with_naive_outbound"
}

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

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