#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2026-present Noxwell (https://github.com/beebono)

# RK3566 currently requires this service-run script to correct an intermittent volume
# issue with PipeWire setting volumes to 100% that happens at some point between 
# audio configuration and EmulationStation being launched.

# Minimal OS variable loading for performance
. /etc/profile.d/001-functions

VOLUME=$(get_setting "audio.volume")

# pw-cli uses perceptually based cubic volume levels directly
CUBIC_VOL=$(echo "scale=6; ($VOLUME / 100) ^ 3" | bc)

# pw-cli doesn't accept @DEFAULT_SINK@ so we have to get that first
DEFAULT_SINK=$(wpctl inspect @DEFAULT_SINK@ | grep -ozP 'id \K\d+')

# Use pw-cli specifically instead of pactl and wpctl which don't apply changes if they think
# the volume levels are already correct, because they track a separate unified volume value
pw-cli set-param $DEFAULT_SINK Props "{ channelVolumes: [ $CUBIC_VOL, $CUBIC_VOL ], softVolumes: [ $CUBIC_VOL, $CUBIC_VOL ] }"