#!/bin/bash

echo "Starting Bose Debugger..."
echo "--------------------------------------------------------"

# 1. Find Bose Devices and their Hostnames
echo "Searching for Bose services..."
TMP_DEVICES=$(mktemp)
dns-sd -B _soundtouch._tcp . 2>/dev/null | awk 'NR>4 && $1!="" {print $7}' > "$TMP_DEVICES" &
dns-sd -B _bose-one-api._tcp . 2>/dev/null | awk 'NR>4 && $1!="" {print $7}' >> "$TMP_DEVICES" &
sleep 2
kill $(jobs -p) 2>/dev/null

DEVICES=$(sort -u "$TMP_DEVICES")

if [ -z "$DEVICES" ]; then
    echo "[!] No Bose services found via mDNS."
    echo "    Try power-cycling the speaker or checking your Wi-Fi."
    rm "$TMP_DEVICES"
    exit 1
fi

for dev in $DEVICES; do
    echo "Found Service: $dev"
    
    # 2. Resolve Hostname to IP
    echo "Resolving IP address..."
    IP=$(ping -c 1 "$dev.local" 2>/dev/null | grep -E -o "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | head -n 1)
    
    if [ -z "$IP" ]; then
        echo "[-] Could not resolve $dev.local to an IP."
        continue
    fi
    
    echo "[+] IP Found: $IP"

    # 3. Ping Test
    echo "Testing reachability (Ping)..."
    if ping -c 3 "$IP" > /dev/null; then
        echo "[+] Device is UP and responding to pings."
    else
        echo "[!] Device is NOT responding to pings. (Firewall or Connection issue)"
    fi

    # 4. API Port Check (SoundTouch uses 8090)
    echo "Checking Bose API Port (8090)..."
    if nc -zv -w 2 "$IP" 8090 2>&1 | grep -q succeeded; then
        echo "[+] Bose API is active on port 8090."
        echo "Fetching device info..."
        curl -s "http://$IP:8090/info" | grep -E "<name>|<type>|<mnetId>" | sed 's/<[^>]*>//g'
    else
        echo "[!] API Port 8090 is closed. (This may be a newer Smart Speaker or crashed)"
        # Check port 80/443 for newer speakers
        nc -zv -w 2 "$IP" 80 2>&1 | grep -q succeeded && echo "[+] Web server active on port 80."
    fi
    echo "--------------------------------------------------------"
done

rm "$TMP_DEVICES"
