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

EAPI=8

inherit go-module optfeature systemd tmpfiles

DESCRIPTION="FLOSS alternative to subsonic"
HOMEPAGE="https://github.com/sentriz/gonic"
SRC_URI="https://github.com/sentriz/${PN}/archive/refs/tags/v${PV}.tar.gz -> ${P}.tar.gz"
SRC_URI+=" https://pub.sinustrom.info/gentoo/${P}-deps.tar.xz"

LICENSE="GPL-3"
SLOT="0"
KEYWORDS="~amd64"
IUSE="systemd"

DEPEND="
	>=dev-lang/go-1.25
	acct-group/gonic
	acct-user/gonic
	dev-db/sqlite
	media-libs/taglib
"

src_prepare() {
	default

	# Use Gentoo's naming convention for configuration file names
	sed -i -e 's/\/config/\/gonic.conf/' contrib/gonic.service || die "sed failed!"
	# Update binary path in systemd unit
	sed -i -e 's/\/local\/bin/\/sbin/' contrib/gonic.service || die "sed failed!"
}

src_compile() {
	ego build ./cmd/${PN}
}

src_install() {
	# Binary
	dobin "${PN}"

	# Configuration
	insinto "/etc/${PN}"
	newins "${S}/contrib/config" "${PN}.conf"

	# Init system configs
	if use systemd; then
		systemd_dounit "${S}/contrib/${PN}.service"
	else
		newinitd "${FILESDIR}/${PN}.initd" "${PN}"
		newconfd "${FILESDIR}/${PN}.confd" "${PN}"
	fi

	# Log directory
	keepdir "/var/log/${PN}"

	# Default state directory
	keepdir "/var/lib/${PN}"
	newtmpfiles "${S}/contrib/${PN}.tmpfiles" "${PN}.conf"

	dodoc README.md

	default
}

pkg_postinst() {
	chown gonic:gonic "${EPREFIX}/var/lib/${PN}"
	chown gonic:gonic "${EPREFIX}/var/log/${PN}"
	chmod 750 "${EPREFIX}/var/log/${PN}"
	tmpfiles_process "${PN}.conf"

	optfeature "Running in jukebox mode" media-video/mpv
	optfeature "Transcoding audio" media-video/ffmpeg[encode,libsoxr,mp3,opus]

	einfo ""
	einfo "gonic presents an HTTP server for the admin interface. The default"
	einfo "user/pass is admin/admin. The web UI listens on 127.0.0.1:4747. It's"
	einfo "highly recommended to use a reverse proxy to serve the admin interface"
	einfo "via HTTPS or to configure a TLS certificate for the service."
	einfo ""

	if ! use systemd; then
		ewarn ""
		ewarn "gonic currently does not self clean it's transcoding cache directory."
		ewarn "While there is a tmpfiles config included with the install, on hosts"
		ewarn "with long uptimes users may want to consider scheduling a cron job"
		ewarn "to call systemd-tmpfiles periodically to avoid running out of disk space."
		ewarn ""
	fi
}