#!/bin/bash

# Expanded list of services for all network devices
SERVICES=(
    "_airplay._tcp"          # Apple Devices
    "_googlecast._tcp"       # Google/Chrome Devices
    "_soundtouch._tcp"       # Bose
    "_bose-one-api._tcp"     # Bose Smart
    "_spotify-connect._tcp"  # Spotify Speakers
    "_workstation._tcp"      # Computers (Linux/Mac)
    "_ssh._tcp"              # SSH Servers
    "_http._tcp"             # Web Interfaces (Routers, Hubs)
    "_smb._tcp"              # Windows/Mac File Sharing
    "_ipp._tcp"              # Printers
    "_rfb._tcp"              # Screen Sharing (VNC)
    "_companion-link._tcp"   # Apple Companion Devices
)

TMP_FILE=$(mktemp)

echo "Scanning for all network devices (4s)..."

# Start discovery in background
for svc in "${SERVICES[@]}"; do
    dns-sd -B "$svc" . 2>/dev/null | awk 'NR>4 && $1!="" { 
        name=""; for(i=7;i<=NF;i++) name=name $i " ";
        gsub(/^[ \t]+|[ \t]+$/, "", name);
        # Clean hex strings
        gsub(/-[a-f0-9]{32}/, "", name);
        gsub(/-[a-f0-9]{12}/, "", name);
        print name "|" $6
        fflush()
    }' >> "$TMP_FILE" &
done

sleep 4

# Kill background processes quietly
kill $(jobs -p) 2>/dev/null
wait $(jobs -p) 2>/dev/null

echo "------------------------------------------------------------------"
printf "%-40s %-20s\n" "DEVICE NAME / INSTANCE" "SERVICE TYPE"
echo "------------------------------------------------------------------"

if [ -s "$TMP_FILE" ]; then
    grep "|" "$TMP_FILE" | sort -u | awk -F'|' '{ 
        type=$2; 
        gsub(/\._tcp\./, "", type);
        gsub(/^_/, "", type);
        printf "%-40s %-20s\n", $1, type 
    }'
else
    echo "No devices found. Check your connection."
fi

echo "------------------------------------------------------------------"
rm "$TMP_FILE"
