#!/bin/bash

# Set localization environment variables
export TEXTDOMAINDIR="/usr/share/locale"
export TEXTDOMAIN=biglinux-noise-reduction-pipewire

# Define the name of the noise-free microphone
mic_name=$"Reduce Microphone Noise"
config_path_old="$HOME/.config/pipewire/filter-chain.conf.d/source-rnnoise.conf"
config_path="$HOME/.config/pipewire/filter-chain.conf.d/source-rnnoise-smart.conf"
system_file="/usr/share/pipewire/filter-chain/source-rnnoise-smart.conf"
bluetooth_policy="$HOME/.config/wireplumber/wireplumber.conf.d/11-bluetooth-policy.conf"

# Update to new version (07/07/2024)
if [[ -e "$config_path_old" ]]; then
    rm -f "$config_path_old"
    cp "$system_file" "$config_path"
fi

# Check for the first argument to determine the action (start, stop, status, etc.)
case "$1" in
    start)
        # Find and kill the pipewire process
        pipewirePidFiltered=$(ps -aux | grep '/usr/bin/[p]ipewire -c filter-chain.conf' | awk '{ print $2 }')
        for pid in $pipewirePidFiltered; do
            kill $pid
        done

        # Check if the configuration file exists
        if [ ! -e "$config_path" ]; then
            # Create the directory if it doesn't exist
            mkdir -p "$(dirname "$config_path")"

            # Copy the configuration file
            cp -f "$system_file" "$config_path"
        fi

        # Start the noise reduction services
        /usr/bin/pipewire -c filter-chain.conf &
        sleep 1
        pactl set-source-mute $(pactl list sources short | grep -o 'output.filter-chain[[:alnum:]_-]*') 0
        pactl set-source-volume $(pactl list sources short | grep -o 'output.filter-chain[[:alnum:]_-]*') 100%
        sleep 3
        pactl set-source-mute $(pactl list sources short | grep -o 'output.filter-chain[[:alnum:]_-]*') 0
        pactl set-source-volume $(pactl list sources short | grep -o 'output.filter-chain[[:alnum:]_-]*') 100%
        wait

        # If need uncomment to use alternative way to detect device name
        # See all audio configuration in json format and filter with jq and save device path in variable
        #Filter_Microphone_Device=$(pw-dump | jq -r '.[].info.props |
        #select(."port.alias" == "Noise Canceling Microphone:capture_1") |
        #."object.path" |
        #split(":")[0]')

        ;;
    
    stop)
        # Remove the configuration file
        rm -f "$config_path"

        # Find and kill the pipewire process
        pipewirePidFiltered=$(ps -aux | grep '/usr/bin/[p]ipewire -c filter-chain.conf' | awk '{ print $2 }')
        for pid in $pipewirePidFiltered; do
            kill $pid
        done
        ;;
    
    status)
        # Check if the configuration file exists
        if [ -e "$config_path" ]; then
            echo "enabled"
            exit 0
        else
            echo "disabled"
            exit 1
        fi
        ;;
    
    enable-bluetooth-autoswitch-to-headset)
        mkdir -p "$(dirname "$bluetooth_policy")"
        echo 'wireplumber.settings = {
    bluetooth.autoswitch-to-headset-profile = true
}' > "$bluetooth_policy"
        systemctl --user restart wireplumber
        ;;
    
    disable-bluetooth-autoswitch-to-headset)
        mkdir -p "$(dirname "$bluetooth_policy")"
        echo 'wireplumber.settings = {
    bluetooth.autoswitch-to-headset-profile = false
}' > "$bluetooth_policy"
        systemctl --user restart wireplumber
        ;;
    
    status-bluetooth)
        # Check if the configuration file exists
        if [[ -e "$bluetooth_policy" ]] && grep -q 'bluetooth.autoswitch-to-headset-profile = false' "$bluetooth_policy"; then
            echo "disabled"
            exit 1
        else
            echo "enabled"
            exit 0
        fi
        ;;
    
    *)
        # Print usage information if no valid argument is provided
        echo "Usage: $0 {start|stop|status|enable-bluetooth-autoswitch-to-headset|disable-bluetooth-autoswitch-to-headset|status-bluetooth}"
        echo ""
        echo "Commands:"
        echo "  start                             Start the noise reduction services"
        echo "  stop                              Stop the noise reduction services"
        echo "  status                            Check if the noise reduction is enabled or disabled"
        echo "  enable-bluetooth-autoswitch-to-headset  Enable automatic switching to Bluetooth headset profile"
        echo "  disable-bluetooth-autoswitch-to-headset Disable automatic switching to Bluetooth headset profile"
        echo "  status-bluetooth                  Check the status of the Bluetooth headset auto-switch"
        ;;
esac
