#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2023 JELOS (https://github.com/JustEnoughLinuxOS)

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

tocon "Configuring Audio..."

STATE=$(systemctl is-active pipewire-pulse)
if [ "${STATE}" = "inactive" ]
then
  systemctl start pipewire-pulse
fi

### Auto switch between internal and bluetooth devices
pactl load-module module-switch-on-connect blocklist="DirtyWave_M8|hdmi" 2>/dev/null

### Set up audio routing (Internal or HDMI)
/usr/bin/hdmi_sense 2>/dev/null

### Set the default audio path, needed for some devices
if [ ! -z "${DEVICE_PLAYBACK_PATH_SPK}" ]
then
  if [ -z "${DEVICE_PLAYBACK_PATH}" ]
  then
    export DEVICE_PLAYBACK_PATH="Playback Path"
  fi
  amixer -c ${ALSA_PRIMARY_CARD:-0} cset name="${DEVICE_PLAYBACK_PATH}" ${DEVICE_PLAYBACK_PATH_SPK} 2>/dev/null
fi

VOLUME=$(get_setting audio.volume)
if [ -z ${VOLUME} ]
then
  VOLUME="60"
elif [ -n "${DEVICE_VOLUME}" ]
then
  VOLUME="${DEVICE_VOLUME}"
fi

### Set the primary card volume to 100%
### to eliminate low audio on some devices.
 amixer -c ${ALSA_PRIMARY_CARD:-0} -q sset "Master" 100%

### Now set the pipewire mixer volume
/usr/bin/volume ${VOLUME}

### Run quantum audio hack if exists
if [ -n "/usr/sbin/quantum" ]; then
  /usr/sbin/quantum
fi
