#!/bin/sh
#Barry Kauler 2007 LGPL

#[ ! $1 ] && exit
DEVM=$1

#return the IRQ that respond to a given device...
irq_from_device_func() { #device passed in, ex: /dev/ttyS0
 #v1.0.2 it seems that setserial may be more trouble than its worth...
 #in the case of linmodems it often doesn't work...
 set -- `setserial -v -b ${1} auto_irq skip_test autoconfig session_lockout`
 [ "$6" ] && echo $6 | tr -d \) 
}

#talk to modem, wait for response...
chat_with_func() { #device passed in.
 rm -f /tmp/answer.txt
 #TODO maybe send +++ to return modem to command-mode.
 #hangs if modem unplugged or turned off (contrary to what docs say)...
 modem-stats -c "ATZ" $1 > /tmp/answer.txt &
 sleep 3
 killall modem-stats
 if [ -e /tmp/answer.txt ];then
  if [ -s /tmp/answer.txt ];then #nonzero size.
   grep "^OK" /tmp/answer.txt > /dev/null 2>&1
   [ $? -eq 0 ] && return 0 #success
  fi
 fi
 return 1
}

modem_test_func() {
 [ "$DEVM" = "" ] && DEVM='invalid'
 case $DEVM in
 tty*)
  IRQM=$(irq_from_device_func /dev/${DEVM})
  fuser -k /dev/${DEVM} 2>/dev/null #kill processing attached to device.
  chat_with_func /dev/$DEVM
  if [ $? -eq 0 ];then
   Xdialog --center --wmclass "pupdial" --title "PupDial: モデムテスト" --no-cancel --msgbox "成功。モデムは応答します！ (モデムはありますがダイアルアウトできる事は別の問題です！)" 0 0
  else
   Xdialog --center --wmclass "pupdial" --title "PupDial: モデムテスト" --no-cancel --msgbox "残念。モデムは見つかりませんでした。" 0 0
  fi
  ;;
 *)
   Xdialog --center --wmclass "pupdial" --title "PupDial: モデムテスト" --no-cancel --msgbox "テストするモデムがありません。" 0 0
  ;;
 esac
}

modem_test_func

###END###
