#!/bin/sh
##Copyright: Cloux <cloux@rote.ch>
##           2026 Aitor <aitor@genuen.org>
##License: CC0-1.0
##Comment: based on runit's /etc/sv/svlogd/run; writable /run fallback for live/RO /var
##Comment: do NOT use "exec 2>&1" here — this script is a logger; stdin must stay
##Comment: the log pipe from runsv. Never enable /etc/sv/svlogd as a service.

# Preserve stdin (log pipe). Logger stderr goes to the console via runsv.
UPDIR=$(dirname "$PWD")
SERVICE=${UPDIR##*/}
RUNITLOG=/var/log/runit
LOGDIR=$RUNITLOG/$SERVICE
BUFFER=2048
LOGUSER=_runit-log

if [ -r ./conf ]; then
	. ./conf
fi
if [ -r /etc/sv/svlogd/conf ] && [ ! -r ./conf ]; then
	. /etc/sv/svlogd/conf
fi

# Prefer /var/log/runit; if read-only (live), use /run/log/runit
if ! mkdir -p "$LOGDIR" 2>/dev/null || ! touch "$LOGDIR/.writetest" 2>/dev/null; then
	RUNITLOG=/run/log/runit
	LOGDIR=$RUNITLOG/$SERVICE
	mkdir -p "$LOGDIR" || exit 1
fi
rm -f "$LOGDIR/.writetest"

if [ ! -e "$LOGDIR/.pkg" ] && [ -e "$UPDIR/.meta/pkg" ]; then
	cp "$UPDIR/.meta/pkg" "$LOGDIR/.pkg" 2>/dev/null || true
fi

if [ -f "$PWD"/log.config ]; then
	install -Tm 0644 -o "$LOGUSER" "$PWD"/log.config "$LOGDIR"/config 2>/dev/null || \
		install -Tm 0644 "$PWD"/log.config "$LOGDIR"/config 2>/dev/null || true
fi
if [ -f /etc/sv/svlogd/log.config ] && [ ! -f "$PWD"/log.config ]; then
	install -Tm 0644 -o "$LOGUSER" /etc/sv/svlogd/log.config "$LOGDIR"/config 2>/dev/null || \
		install -Tm 0644 /etc/sv/svlogd/log.config "$LOGDIR"/config 2>/dev/null || true
fi

chown "$LOGUSER":adm "$LOGDIR" 2>/dev/null || true
chmod 750 "$LOGDIR" 2>/dev/null || true

# If _runit-log is missing, still log as root rather than dying (pipe SIGPIPE → main svc).
if getent passwd "$LOGUSER" >/dev/null 2>&1 && command -v chpst >/dev/null 2>&1; then
	exec chpst -u "$LOGUSER" svlogd -tt -b "$BUFFER" "$LOGDIR"
fi
exec svlogd -tt -b "$BUFFER" "$LOGDIR"
