#!/bin/bash

# Check if display_num is provided
if [ -z "$1" ]; then
    echo "Error: Please provide a display number as an argument."
    exit 1
fi

DISPLAY_NUM=$1
SINK_NAME="virtual_sink_${DISPLAY_NUM}"

# Start Pulseaudio server if not running
if ! pulseaudio --check; then
    echo "Pulseaudio server not running. Starting it in daemon mode..."
    pulseaudio --start --daemonize --exit-idle-time=-1
    sleep 2
    if ! pulseaudio --check; then
        echo "Failed to start Pulseaudio server. Exiting."
        exit 1
    fi
else
    echo "Pulseaudio server is already running."
fi

# Check if the sink already exists
if pactl list sinks short | grep -q "$SINK_NAME"; then
    echo "Virtual sink '$SINK_NAME' already exists."
    # Find the module ID for the existing sink
    MODULE_ID=$(pactl list modules short | grep "module-null-sink.*sink_name=$SINK_NAME" | awk '{print $1}')
else
    echo "Loading module-null-sink '$SINK_NAME'..."
    MODULE_ID=$(pactl load-module module-null-sink sink_name="$SINK_NAME" format=s16le channels=2 rate=44100 sink_properties="device.description=Virtual_Sink_for_Recording_${DISPLAY_NUM}")
    sleep 1
    if [ -z "$MODULE_ID" ]; then
        echo "Failed to load module-null-sink for '$SINK_NAME'. Exiting."
        exit 1
    fi
    echo "module-null-sink loaded with ID: $MODULE_ID"
fi

# Verify the monitor source exists
MONITOR_SOURCE="${SINK_NAME}.monitor"
if pactl list sources short | grep -q "$MONITOR_SOURCE"; then
    echo "Pulseaudio monitor source '$MONITOR_SOURCE' found."
else
    echo "Warning: Monitor source '$MONITOR_SOURCE' not found. Falling back to 'default'."
    MONITOR_SOURCE="default"
fi

# Output the module ID and monitor source for use in Python
echo "MODULE_ID=$MODULE_ID"
echo "MONITOR_SOURCE=$MONITOR_SOURCE"