#!/bin/sh

LOG_TAG="BluetoothManager"
DBUS_INIT=/etc/init.d/dbus-1
BLUETOOTH_INIT=/etc/init.d/bluetooth
DBUS_WAS_STARTED=0
RETRY_SECONDS=30

log() {
    logger -t "$LOG_TAG" "$1"
}

dbus_ready() {
    [ -S /run/dbus/system_bus_socket ] || return 1
    dbus-send --system --dest=org.freedesktop.DBus --type=method_call --print-reply / org.freedesktop.DBus.ListNames >/dev/null 2>&1
}

start_dbus() {
    dbus_ready && return 0
    DBUS_WAS_STARTED=1
    [ -x "$DBUS_INIT" ] && "$DBUS_INIT" start >/dev/null 2>&1 || true
    i=0
    while [ $i -lt $RETRY_SECONDS ]; do
        dbus_ready && return 0
        sleep 1
        i=$((i+1))
    done
    log "D-Bus system bus not ready"
    return 1
}

start_bluetoothd() {
    if [ "$DBUS_WAS_STARTED" = "1" ] && pidof bluetoothd >/dev/null 2>&1; then
        "$BLUETOOTH_INIT" restart >/dev/null 2>&1 || true
        return 0
    fi
    pidof bluetoothd >/dev/null 2>&1 && return 0
    [ -x "$BLUETOOTH_INIT" ] && "$BLUETOOTH_INIT" start >/dev/null 2>&1 || true
    i=0
    while [ $i -lt $RETRY_SECONDS ]; do
        pidof bluetoothd >/dev/null 2>&1 && return 0
        sleep 1
        i=$((i+1))
    done
    log "bluetoothd not running"
    return 1
}

log "Script started"

default_asoundconf() {
cat << EOF > /etc/asound.conf
pcm.!default {
    type plug
    slave.pcm "hw:0"
}

ctl.mixer0 {
    type hw
    card 0
}
EOF
log "Reset /etc/asound.conf to default configuration"
}

bluetooth_asoundconf() {
cat << EOF >> /etc/asound.conf
pcm.bluetooth {
    type plug
    slave.pcm {
        type bluealsa
        interface "hci0"
        device "$1"
        profile "a2dp"
    }
    hint {
        show on
        description "Bluetooth $2"
    }
}

ctl.bluetooth {
    type bluealsa
}
EOF
log "Added Bluetooth device '$2' ($1) to /etc/asound.conf"
}

log "Checking for existing aplay process"
if [ -f /var/run/aplay.pid ]; then
    PID=$(cat /var/run/aplay.pid)
    log "Stopping existing aplay process (PID: $PID)"
    kill $PID
    while ps -p $PID > /dev/null; do
        sleep 1
    done
    log "Previous aplay process stopped"
fi

log "Applying default sound configuration"
default_asoundconf

start_dbus || exit 1
start_bluetoothd || exit 1

if [ -n "$1" ]; then
    bluetoothaddr="$@"
    log "Bluetooth address provided: $bluetoothaddr"

    if ! bluetoothctl info "$bluetoothaddr" >/dev/null 2>&1; then
        log "Error: Bluetooth device $bluetoothaddr not found"
        exit 1
    fi

    log "Connecting to Bluetooth device: $bluetoothaddr"
    bluetoothctl connect "$bluetoothaddr"
    
    if ! bluetoothctl info "$bluetoothaddr" | grep -q "Audio Sink"; then
        log "Error: No Audio Sink profile found for $bluetoothaddr"
        exit 1
    fi

    bluetoothname="$(bluetoothctl info "$bluetoothaddr" | grep "Name" | cut -d ':' -f 2 | xargs)"
    log "Device name detected: $bluetoothname"

    bluetooth_asoundconf "$bluetoothaddr" "$bluetoothname"

    log "Starting audio streaming to Bluetooth device"
    arecord -q -f dat -t raw | aplay -q -f dat --buffer-size=16384 --period-size=2048 -t raw -D bluetooth --process-id-file /var/run/aplay.pid &
else
    log "No Bluetooth address provided, exiting"
fi

log "Script finished"
exit 0
