#!/bin/sh
#Barry Kauler 2010 LGPL

#Find another candidate for USB modem, for device in argument 1.
DEVM=$1
DEVMALT=""
if [ "`echo "$DEVM" | grep -E 'ttyACM[0-9]|ttyHS[0-9]|ttyUSB[0-9]|rfcomm[0-9]'`" != "" ];then

 INTERRUPTLIST="`grep -H -s 'Interrupt' /sys/bus/usb/devices/*-*:*.*/ep_??/type | cut -f 1-6 -d /`"
 DEVLISTACM="`ls -1 -d /sys/bus/usb/devices/*-*:*.*/tty/tty????* 2>/dev/null | sed 's/ /\n/g' | grep -F "$INTERRUPTLIST" | cut -f 8 -d / | sed 's/\(tty...\)\([0-9]$\)/\10\2/' | sort | sed 's/\(tty...\)\(0\)/\1/'`"
 DEVLISTHS="`grep -l -s 'Modem' /sys/class/tty/ttyHS?*/hsotype | cut -f 5 -d / | sort -u`"
 DEVLISTUSB="`ls -1 -d /sys/bus/usb/devices/*-*:*.*/tty????* 2>/dev/null | sed 's/ /\n/g' | grep -F "$INTERRUPTLIST" | cut -f 7 -d / | sed 's/\(tty...\)\([0-9]$\)/\10\2/' | sort | sed 's/\(tty...\)\(0\)/\1/'`"
 DEVMLIST="`grep -s 'converter now attached' /var/log/messages | grep ' modem ' | grep -o 'ttyUSB[0-9][0-9]*' | sort -u`"
 [ "$DEVMLIST" != "" ] && DEVLISTUSB="`echo "$DEVLISTUSB" | grep -F "$DEVMLIST"`"
 #Prepend any bluetooth modems to list...
 DUNRFCLIST=""
 if which rfcomm >/dev/null && which sdptool >/dev/null;then  
  DUNPATTERN="`sdptool search DUN | sed -n -e '/^Searching/h' -e '/^    Channel:/{H;x}' -e 's/Searching for DUN on //' -e 's/ ...\n    Channel://p'`"
  [ "$DUNPATTERN" != "" ] \
   && DUNRFCLIST="`rfcomm -a | grep ' connected' | sed -e 's/ channel//' | grep -F "$DUNPATTERN" | cut -f 1 -d :`"
  echo "Modemtest/probe: DUNPATTERN: $DUNPATTERN  DUNRFCLIST: $DUNRFCLIST" >> /tmp/udevtrace-modem.log #DEBUG
 fi
 DEVLISTALL="`echo "$DUNRFCLIST $DEVLISTACM $DEVLISTHS $DEVLISTUSB" | tr ' ' '\n' | sed /^$/d`"
 SEDSCRIPT1="/${DEVM}/"'{n;p;q}'
 DEVMALT="`echo "$DEVLISTALL" | sed -n "$SEDSCRIPT1"`"
 [ "$DEVMALT" = "" ] \
  && SEDSCRIPT2="/${DEVM}/"'!{p;q}' \
  && DEVMALT="`echo "$DEVLISTALL" | sed -n "$SEDSCRIPT2"`"
 echo -e "Modemtest/probe: DEVM: $DEVM  DEVMALT: $DEVMALT  DEVLISTALL:\n$DEVLISTALL" >> /tmp/udevtrace-modem.log #DEBUG
fi
echo "$DEVMALT"
exit 0

###END###