# Maintainer: Uyanide <pywang0608@foxmail.com>

pkgname=nipaplay-reload
pkgver=1.11.2
pkgrel=1
pkgdesc='A modern cross-platform local danmaku video player'
arch=('x86_64' 'aarch64')
url='https://github.com/AimesSoft/NipaPlay-Reload'
license=('MIT')
provides=('nipaplay')
conflicts=('nipaplay')
depends=(
	'glibc'
	'gcc-libs'
	'gtk3'
	'mpv'                      # libmpv, media_kit's playback backend; pulls in libass/ffmpeg
	'sqlite'                   # libsqlite3.so, dlopen'ed
	'libkeybinder3'            # hotkey_manager_linux
	'libayatana-appindicator'  # tray_manager
	'libepoxy'
)
# Note: upstream's linux/CMakeLists.txt does pass -lmimalloc, but the Flutter runner
# objects reference no allocator symbol at all, so Arch's default -Wl,--as-needed drops
# it again. The binary is able to run on glibc malloc, hence no mimalloc dependency here.
makedepends=(
	'git'
	'flutter'
	'flutter-target-linux'
	'flutter-target-web'  # embedded web remote UI; the build script skips it when absent
	'rustup'              # cargokit hard-requires `rustup run <toolchain> cargo build`
	'java-environment'    # the jni plugin's linux CMake needs the JNI headers
	'clang'
	'cmake'
	'ninja'
	'patchelf'            # strip the $srcdir flutter bakes into each plugin's DT_RUNPATH
	'pkgconf'
	'unzip'
)
optdepends=(
	'xdg-utils: open external links in the default browser'
)
# Flutter/Dart AOT output and the bundled .so files must not be post-processed by makepkg
options=('!strip' '!debug' '!lto')
source=(
	"${pkgname}::git+${url}.git#tag=v${pkgver}"
	'media-kit::git+https://github.com/AimesSoft/media-kit.git'
)
sha256sums=('SKIP'
            'SKIP')

prepare() {
	cd "${pkgname}"

	git submodule init third_party/media-kit-upstream
	git config submodule.third_party/media-kit-upstream.url "${srcdir}/media-kit"
	git -c protocol.file.allow=always submodule update third_party/media-kit-upstream

	# Restore media_kit's isolated EGL context; this fork reuses Flutter's context
	# instead, which blue-screens the video area on NVIDIA GPUs.
	# https://github.com/AimesSoft/NipaPlay-Reload/pull/798
	local _mkv_upstream='third_party/media-kit-upstream/media_kit_video/linux'
	cp "${_mkv_upstream}/video_output.cc" packages/media_kit_video/linux/video_output.cc
	cp "${_mkv_upstream}/texture_gl.cc" packages/media_kit_video/linux/texture_gl.cc

	# The desktop file name disagrees with appdata's <launchable>
	# (MCDFsteve vs MCDFSteve); settle on the AppStream ID.
	mv assets/linux/io.github.MCDFsteve.NipaPlay-Reload.desktop \
	   assets/linux/io.github.MCDFSteve.NipaPlay-Reload.desktop
	sed -i \
		-e "s|^Exec=.*|Exec=${pkgname} %f|" \
		-e 's|^Icon=.*|Icon=io.github.MCDFSteve.NipaPlay-Reload|' \
		assets/linux/io.github.MCDFSteve.NipaPlay-Reload.desktop

	flutter pub get
}

build() {
	cd "${pkgname}"

	export FLUTTER_SUPPRESS_ANALYTICS=true
	# Match upstream CI: fvp takes its deps from the latest mdk-sdk release
	export FVP_DEPS_URL='https://github.com/wang-bin/mdk-sdk/releases/latest/download/'
	export FVP_DEPS_LATEST=1

	# Build the embedded web remote UI into assets/web/ (the script degrades on failure)
	bash build_and_copy_web.sh

	flutter build linux --release
}

package() {
	cd "${pkgname}"

	local _flutter_arch
	case "${CARCH}" in
		x86_64)  _flutter_arch='x64' ;;
		aarch64) _flutter_arch='arm64' ;;
	esac

	# A source build has no reason to live in /opt; use /usr/lib as usual
	install -dm755 "${pkgdir}/usr/lib/${pkgname}"
	cp -a "build/linux/${_flutter_arch}/release/bundle/." "${pkgdir}/usr/lib/${pkgname}/"

	find "${pkgdir}/usr/lib/${pkgname}" -type d -exec chmod 755 {} +
	find "${pkgdir}/usr/lib/${pkgname}" -type f -exec chmod 644 {} +
	find "${pkgdir}/usr/lib/${pkgname}" -name '*.so*' -type f -exec chmod 755 {} +
	chmod 755 "${pkgdir}/usr/lib/${pkgname}/NipaPlay"

	# Unlike DT_RPATH, DT_RUNPATH is not inherited by the libraries the main binary
	# loads, so every .so has to locate its own siblings. Two spots get this wrong:
	#  1. flutter bakes $srcdir straight into each plugin's RUNPATH, and none of the
	#     14 plugins carry $ORIGIN at all -- librust_lib_nipaplay_plugin.so can only
	#     find librust_lib_nipaplay.so below $srcdir;
	#  2. mdk-sdk's libffmpeg.so.8 has no RUNPATH whatsoever and ends up loading the
	#     system libc++.so.1 (not a base package on Arch) even though the bundle
	#     ships one of its own.
	# Prepend $ORIGIN to every ELF under lib/, keeping the non-$srcdir entries.
	local _elf _entry _rpath
	while IFS= read -r -d '' _elf; do
		_rpath='$ORIGIN'
		while IFS= read -r _entry; do
			[[ -z ${_entry} || ${_entry} == '$ORIGIN' || ${_entry} == "${srcdir}"* ]] && continue
			_rpath+=":${_entry}"
		done < <(patchelf --print-rpath "${_elf}" | tr ':' '\n')
		patchelf --set-rpath "${_rpath}" "${_elf}"
	done < <(find "${pkgdir}/usr/lib/${pkgname}/lib" -type f -name '*.so*' -print0)

	# The binary's RUNPATH is $ORIGIN/lib, and $ORIGIN expands to the resolved real
	# path, so putting a symlink in /usr/bin is safe
	install -dm755 "${pkgdir}/usr/bin"
	ln -s "/usr/lib/${pkgname}/NipaPlay" "${pkgdir}/usr/bin/${pkgname}"

	install -Dm644 assets/linux/io.github.MCDFSteve.NipaPlay-Reload.desktop \
		-t "${pkgdir}/usr/share/applications"
	install -Dm644 assets/linux/io.github.MCDFSteve.NipaPlay-Reload.appdata.xml \
		-t "${pkgdir}/usr/share/metainfo"
	install -Dm644 assets/images/logo512.png \
		"${pkgdir}/usr/share/icons/hicolor/512x512/apps/io.github.MCDFSteve.NipaPlay-Reload.png"
	install -Dm644 LICENSE -t "${pkgdir}/usr/share/licenses/${pkgname}"
}
