#!/bin/bash
# asus-px13-audio-setup - probe this machine and (re)generate the ALSA UCM
# card override that asus-px13-audio depends on.
#
# WHY THIS EXISTS
#   ALSA UCM loads a card override from
#       /usr/share/alsa/ucm2/conf.d/${CardDriver}/${CardLongName}.conf
#   and ${CardLongName} is built from DMI, so it differs between the ASUS
#   ProArt PX13 (2026) models - HN7306EA, HN7306EAC (GoPro Edition),
#   HN7306EA-LX005X, ... A file installed under another model's long name is
#   never read, and the failure is completely silent (no Speaker device,
#   PipeWire falls back to a dummy sink). An RPM cannot know the name of the
#   machine it will be installed on, so the override is rendered here, at
#   install time, from the probed card - never from a hardcoded string.
#
# It is run by %posttrans on every install/upgrade and is idempotent:
#   sudo asus-px13-audio-setup
#
# Every value is probed (see lib/px13-detect.sh from upstream); the only
# escape hatches are the PX13_* environment overrides documented there
# (PX13_CARD, PX13_DRIVER, PX13_LONGNAME, ...).
set -u

UCM_DIR="@UCM_DIR@"
LIBEXECDIR="@LIBEXECDIR@"
DATADIR="@DATADIR@"
SYSCONFDIR="@SYSCONFDIR@"

DETECT="$LIBEXECDIR/px13-audio-detect.sh"
TEMPLATE="$DATADIR/ucm-card-override.conf.in"
CACHE="$SYSCONFDIR/px13-audio-fix.conf"   # same cache file upstream writes
CACHE_MARK="generated by asus-px13-audio-setup"
OVERRIDE_MARK="Generated by asus-px13-audio-setup"

fail() {
	echo "asus-px13-audio-setup: FAILED: $*" >&2
	exit 1
}

[ -r "$DETECT" ] || fail "$DETECT is missing - the package install is broken"
[ -r "$TEMPLATE" ] || fail "$TEMPLATE is missing - the package install is broken"

# shellcheck source=lib/px13-detect.sh
. "$DETECT"

# Root is only needed for the writes; the PipeWire half of upstream's
# installer does not run here, so a missing session user is not an error.
px13_init_privs || :
root_run() { px13_root_run "$@"; }

echo "asus-px13-audio-setup: probing the SoundWire audio hardware"

CARD="$(px13_find_card)" || fail "no SoundWire ALSA card found.
    'cat /proc/asound/cards' has no card whose driver mentions soundwire.
    Is snd_pci_ps loaded? Is this really a ProArt PX13 (2026) on a stock
    kernel >= 7.1? Run this again after a reboot."
DRIVER="$(px13_card_driver "$CARD")" || fail "could not read the ALSA driver name of card $CARD"
LONG="$(px13_card_longname "$CARD")" || fail "could not read the CardLongName of card $CARD.
    UCM keys the override file on that exact string; without it nothing can be installed."
COMPONENTS="$(px13_card_components "$CARD" || true)"

printf '    card index    : %s\n' "$CARD"
printf '    ALSA driver   : %s\n' "$DRIVER"
printf '    CardLongName  : %s\n' "$LONG"
printf '    components    : %s\n' "${COMPONENTS:-(empty)}"
printf '    UCM override  : %s\n' "$UCM_DIR/conf.d/$DRIVER/$LONG.conf"
[ -n "$PX13_SESSION_USER" ] && printf '    running as    : root\n'

[ -f "$UCM_DIR/conf.d/$DRIVER/$DRIVER.conf" ] || fail "base UCM config not found:
    $UCM_DIR/conf.d/$DRIVER/$DRIVER.conf
    The override includes it. Install/upgrade alsa-ucm-conf."

if px13_has_tas2783 "$CARD"; then
	echo "    amplifier     : TAS2783 present"
else
	echo "    WARNING       : no TAS2783 amplifier visible (codec driver not
                    loaded yet?) - installing the override anyway"
fi

# --- the override ------------------------------------------------------------
OVERRIDE="$UCM_DIR/conf.d/$DRIVER/$LONG.conf"
TMP="$(mktemp)" || fail "mktemp failed"
trap 'rm -f "$TMP"' EXIT
# @DRIVER@ / @LONGNAME@ come from the probe above; the marker after Syntax is
# how %postun finds the files this package generated (and only those).
sed -e "s|@DRIVER@|$DRIVER|g" \
    -e "s|@LONGNAME@|$LONG|g" \
    -e "1a\\# $OVERRIDE_MARK on $(date '+%F %T') - do not edit; regenerate with: asus-px13-audio-setup" \
    "$TEMPLATE" > "$TMP"
grep -q 'Syntax' "$TMP" || fail "the generated override has no Syntax line ($TEMPLATE?)"
root_run install -Dm644 "$TMP" "$OVERRIDE"
echo "    installed     : $OVERRIDE"

# An override this project wrote under ANOTHER model's long name (copied from
# a guide, or left by a different checkout) is dead weight: UCM never reads it.
# Remove those, keep everything we did not write.
for f in "$UCM_DIR/conf.d/$DRIVER"/*.conf; do
	[ -f "$f" ] || continue
	[ "$f" = "$OVERRIDE" ] && continue
	if grep -q 'px13-audio-fix' "$f" 2>/dev/null; then
		root_run rm -f "$f"
		echo "    removed stale override for another model: $(basename "$f")"
	fi
done

# --- cache: values that cannot be probed once the card has vanished ----------
# (used by px13-soundwire-recover.sh after a bad s2idle resume; the user's
# PX13_RECOVER_POLICY is preserved across regeneration)
PCI="$(px13_acp_pci || true)"
POLICY="$(px13_cache_get PX13_RECOVER_POLICY 2>/dev/null || true)"
{
	printf '# %s on %s - edit only PX13_RECOVER_POLICY\n' "$CACHE_MARK" "$(date '+%F %T')"
	printf 'PX13_ACP_PCI=%s\n' "${PCI:-}"
	printf 'PX13_CARD_DRIVER=%s\n' "$DRIVER"
	printf 'PX13_CARD_LONGNAME=%s\n' "$LONG"
	if [ -n "${POLICY:-}" ]; then
		printf 'PX13_RECOVER_POLICY=%s\n' "$POLICY"
	fi
} | root_run tee "$CACHE" >/dev/null
echo "    cached        : ACP PCI=${PCI:-?} -> $CACHE"

# --- rt721 jack codec (rule ships in /usr/lib/udev/rules.d) ------------------
if command -v udevadm >/dev/null 2>&1; then
	udevadm control --reload >/dev/null 2>&1 || :
fi
for d in /sys/bus/soundwire/devices/sdw:*:025d:0721:*; do
	[ -e "$d/power/control" ] || continue
	echo on | root_run tee "$d/power/control" >/dev/null 2>/dev/null || :
	echo "    rt721 jack codec: runtime suspend forbidden ($d)"
done

# --- what is not active yet ---------------------------------------------------
if amixer -D "hw:$CARD" controls 2>/dev/null | grep -q 'Channel Playback'; then
	echo "    module        : patched snd-soc-tas2783-sdw is loaded (stereo control present)"
else
	echo "    module        : 'Channel Playback' not present - the KMP for this kernel
                    is not loaded yet. Reboot (or load the module), then
                    verify with: sudo asus-px13-audio-setup"
fi

# --- validation: refuse to report success without a Speaker device ------------
if command -v alsaucm >/dev/null 2>&1; then
	if alsaucm -c "$CARD" list _devices/HiFi 2>/dev/null | grep -qw Speaker; then
		echo "    UCM           : HiFi profile exposes a Speaker device"
	else
		echo "asus-px13-audio-setup: FAILED: UCM exposes no Speaker device for card $CARD." >&2
		echo "    override : $OVERRIDE ($([ -f "$OVERRIDE" ] && echo exists || echo MISSING))" >&2
		echo "    longname : $LONG" >&2
		echo "    components: ${COMPONENTS:-(empty)}" >&2
		echo "    Re-run with PX13_LONGNAME='<name>' asus-px13-audio-setup if the probe" >&2
		echo "    is wrong for this machine, and report the output above." >&2
		exit 1
	fi
else
	echo "    UCM           : alsaucm not installed - Speaker check skipped"
fi

echo "asus-px13-audio-setup: done."
echo "  Next: reboot if the module was just installed, restart the session audio"
echo "  stack (systemctl --user restart pipewire wireplumber pipewire-pulse),"
echo "  then: speaker-test -D pulse -c2 -l1 -t wav   (Front Left / Front Right)"
exit 0
