#!/bin/sh
#Barry Kauler, LGPL 2010

#If a different modem selected, quit...
[ -h /dev/modem ] && exit

[ ! $1 ] && exit
[ "$1" != "start" ] && exit

echo "" >> /tmp/udevtrace-modem.log  #DEBUG
echo "Script Allusbserial: `date | tr -s ' ' | cut -f 4 -d ' '` - No modem found yet." >> /tmp/udevtrace-modem.log  #DEBUG
#Verify all usbserial-related drivers loaded, then let them settle.
/sbin/pup_event_backend_modprobe_protect --modcheck=usbserial || exit
echo "Script Allusbserial: usbserial module is loaded." >> /tmp/udevtrace-modem.log  #DEBUG
sleep 1

#Let high-speed modems to be detected by hso init script.
[ "`grep -l -s 'Modem' /sys/class/tty/ttyHS?*/hsotype`" != "" ] && exit
echo "Script Allusbserial: No ttyHS modem found, so continuing." >> /tmp/udevtrace-modem.log  #DEBUG

#Select interrupt-type device - first one or one identified in log as modem.
INTERRUPTLIST="`grep -H -s 'Interrupt' /sys/bus/usb/devices/*-*:*.*/ep_??/type | cut -f 1-6 -d /`"
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/'`"

#echo -e "Script Allusbserial - INTERRUPTLIST:\n$INTERRUPTLIST\nDEVLISTUSB:\n$DEVLISTUSB" >> /tmp/udevtrace-modem.log  #DEBUG

DEVMLIST="`grep -s 'converter now attached' /var/log/messages | grep ' modem ' | grep -o 'ttyUSB[0-9][0-9]*' | sort -u`"

#echo -e "Script Allusbserial: DEVLIST1:\n`grep -l -s -H 'Interrupt' /sys/bus/usb/devices/*-*:*.*/ep_??/type`" >> /tmp/udevtrace-modem.log  #DEBUG
#echo -e "Script Allusbserial: DEVLIST2:\n`ls -1 -d /sys/bus/usb/devices/*-*:*.*/tty* 2>/dev/null`" >> /tmp/udevtrace-modem.log  #DEBUG

if [ "$DEVLISTUSB" != "" ] && [ "$DEVMLIST" != "" ];then
 MODEM="`echo "$DEVLISTUSB" | grep -F "$DEVMLIST" | head -n 1`"
else
 MODEM="`echo "$DEVMLIST" | head -n 1`"
fi
echo "Script Allusbserial - MODEM: '$MODEM'  DEVLISTUSB: '$DEVLISTUSB'  DEVMLIST: '$DEVMLIST'" | tr '\n' ' ' | sed 's/ $/\n/' >> /tmp/udevtrace-modem.log  #debug
[ "$MODEM" = "" ] && exit

ln -snf $MODEM /dev/modem

#the module doesn't seem to support any country setting, so...
if [ -f /etc/countryinfo ];then
 SPATTERN="s/^MODEM_COUNTRY_STRING.*/MODEM_COUNTRY_STRING=''/"
 sed -i -e "$SPATTERN" /etc/countryinfo
fi
#.../usr/sbin/gen_modem_init_string reads this variable.

###END###
