# Copyright 2026 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

EAPI=8

inherit desktop

MY_PN="YAVSRG"
MY_TAG="interlude-v${PV}"

DESCRIPTION="Vertical scrolling rhythm game (Interlude / YAVSRG) - Pre-built release"
HOMEPAGE="https://github.com/YAVSRG/YAVSRG"
SRC_URI="https://github.com/YAVSRG/${MY_PN}/releases/download/${MY_TAG}/Interlude-linux-x64.zip -> ${P}-Linux.zip"

S="${WORKDIR}"

LICENSE="GPL-3"
SLOT="0"
KEYWORDS="~amd64"
RESTRICT="strip"

RDEPEND="
	net-misc/rsync
	media-libs/openal
	media-libs/libpng
	virtual/zlib
	x11-libs/libX11
	x11-libs/libXi
	x11-libs/libXcursor
	x11-libs/libXrandr
"
BDEPEND="app-arch/unzip"

src_install() {
	local install_dir="/opt/${PN}"

	insinto "${install_dir}"
	doins -r .
	fperms +x "${install_dir}/Interlude"
	find "${ED}${install_dir}" -name "*.so" -exec chmod +x {} + 2>/dev/null

	echo "${PV}" >"${T}/.version" || die
	insinto "${install_dir}"
	doins "${T}/.version"

	mkdir -p "${ED}/usr/bin" || die
	cat <<-EOF >"${ED}/usr/bin/yavsrg"
		#!/bin/bash
		set -e

		INSTALL_DIR="${install_dir}"
		GAME_DIR="\${XDG_DATA_HOME:-\$HOME/.local/share}/interlude"
		VERSION_FILE="\${GAME_DIR}/.interlude-bin-version"
		INSTALLED_VERSION="\$(cat "\${INSTALL_DIR}/.version" 2>/dev/null || echo unknown)"

		mkdir -p "\${GAME_DIR}"

		# Sync the read-only install into the user's writable game dir on
		# first run and whenever the package is updated. --update (not
		# --delete) so existing save data (Data/, Songs/, Logs/, config.json)
		# in \${GAME_DIR} is left alone; only files present in INSTALL_DIR are
		# refreshed.
		if [ ! -f "\${VERSION_FILE}" ] || [ "\$(cat "\${VERSION_FILE}")" != "\${INSTALLED_VERSION}" ]; then
		    rsync -a --update "\${INSTALL_DIR}/" "\${GAME_DIR}/"
		    echo "\${INSTALLED_VERSION}" > "\${VERSION_FILE}"
		fi

		cd "\${GAME_DIR}" || exit 1
		exec "\${GAME_DIR}/Interlude" "\$@"
	EOF
	fperms +x /usr/bin/yavsrg

	make_desktop_entry yavsrg "YAVSRG (Interlude)" "game-card" "Game;ArcadeGame;"
}

pkg_postinst() {
	elog "Interlude is a portable app that stores its config, data, songs"
	elog "and logs next to its own executable, which is incompatible with"
	elog "a shared read-only /opt install. On first launch, 'yavsrg' will"
	elog "copy the game into \${XDG_DATA_HOME:-\$HOME/.local/share}/interlude"
	elog "and run it from there. Your save data and settings live in that"
	elog "per-user directory, not under /opt."
}