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

EAPI=8

inherit systemd unpacker

MY_PN="${PN/-bin/}"

DESCRIPTION="Native Linux backend for Claude Desktop Cowork (unofficial)"
HOMEPAGE="https://github.com/patrickjaja/claude-cowork-service"
SRC_URI="https://github.com/patrickjaja/claude-cowork-service/releases/download/v${PV}/${MY_PN}_${PV}_amd64.deb"

S="${WORKDIR}"

LICENSE="MIT"
SLOT="0"
KEYWORDS="-* ~amd64"
RESTRICT="mirror strip bindist"

RDEPEND="
	sys-apps/systemd
	app-shells/bash
"
# NOTE: Runtime also requires the Claude Code CLI (>= 2.1.86) on $PATH.
# Not packaged in Portage. Install via:  npm i -g @anthropic-ai/claude-code
# Optional: net-misc/socat (used as health-check fallback)

QA_PREBUILT="*"

src_install() {
	# Binary: upstream .deb installs to /usr/bin/cowork-svc-linux
	if [[ -f "${S}/usr/bin/cowork-svc-linux" ]]; then
		dobin "${S}/usr/bin/cowork-svc-linux"
	else
		die "cowork-svc-linux binary not found in unpacked .deb (path changed upstream?)"
	fi

	# systemd user service unit (.deb may place in /lib or /usr/lib)
	local unit_src=""
	local candidate
	for candidate in \
		"${S}/usr/lib/systemd/user/claude-cowork.service" \
		"${S}/lib/systemd/user/claude-cowork.service" \
	; do
		if [[ -f "${candidate}" ]]; then
			unit_src="${candidate}"
			break
		fi
	done

	if [[ -n "${unit_src}" ]]; then
		systemd_douserunit "${unit_src}"
	else
		die "claude-cowork.service unit file not found in unpacked .deb"
	fi

	# Docs if shipped
	local doc_dir="${S}/usr/share/doc/${MY_PN}"
	if [[ -d "${doc_dir}" ]]; then
		dodoc -r "${doc_dir}/."
	fi
}

pkg_postinst() {
	elog "claude-cowork-service installed."
	elog ""
	elog "Enable and start the user service:"
	elog "  systemctl --user daemon-reload"
	elog "  systemctl --user enable --now claude-cowork"
	elog ""
	elog "REQUIRED runtime dependency (NOT in Portage):"
	elog "  Claude Code CLI >= 2.1.86 must be on \$PATH"
	elog "  Install via:  npm i -g @anthropic-ai/claude-code"
	elog "  Without it, the daemon starts but spawn() RPCs fail."
	elog ""
	elog "Verify the installed user-unit contains an ExecStartPre line that"
	elog "imports WAYLAND_DISPLAY/DISPLAY/DBUS_SESSION_BUS_ADDRESS — without it"
	elog "spawned 'claude' processes lose access to the desktop session."
	elog ""
	elog "After service is active, restart Claude Desktop fully so the Cowork"
	elog "VM boot succeeds (check ~/.config/Claude/logs/cowork_vm_node.log)."
	elog ""
	elog "This is an unofficial community service. Required because Anthropic's"
	elog "official Cowork bundle does not support this platform (yukonSilver)."
	elog "Upstream: https://github.com/patrickjaja/claude-cowork-service"
}