#!/bin/bash

###########################################################################
#
#	Shell program to dial through wvdial and cut out automatically
#       after a specified interval given in seconds
#
#	Copyright 2002, USM Bish <bish@nde.vsnl.net.in>.
#
#	This program is free software; you can redistribute it and/ or
#	modify it under the terms of the GNU General Public License as
#	published by the Free Software Foundation; either version 2 of
#	the License, or (at your option) any later version. 
#
#	This program is distributed in the hope that it will be useful
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY  or  FITNESS FOR A PARTICULAR PURPOSE. See the
#	GNU General Public License for more details.
#
#	NOTE: You must be the superuser to run this script.
#	WARNING!: wvdial.conf contains security info (passwords).  
#                 Do not set world-readable.
#
#	Usage:
#
#		auto-cut [ -h | --help ] [-c duration] [-d]
#
#	Options:
#
#		-h, --help	Display this help message and exit.
#		-c  duration    connect
#		-d              disconnect
#
#       Note : Duration in sec.
#
#	Revisions:
#
#	Jan/29/2002	File created			ver 0.1
#
###########################################################################


PROGNAME=$(basename $0)
VERSION="0.1"
TEMP_FILE1=/tmp/${PROGNAME}.$$.1
TEMP_FILE2=/tmp/${PROGNAME}.$$.2
HOW_MANY_SECS=$2
ONLINE=22

###########################################################################
#	Editable variables
###########################################################################

# Change this as per your preferred dialer
CONNECTION="Defaults"

# Name of log file for wvdial
WV_LOG=$HOME/wv.log

# Name of log file of this script
PROG_LOG=$HOME/$PROGNAME.log

###########################################################################
#	Functions
###########################################################################

function chk_if_root
{
    if ! [ `whoami` = "root" ]; then
       echo "Super-user privileges for -c and -d options"
       term_exit
    fi
}    
     
function disconnect
{        
        ## Time over : disconnect
        killall -INT pppd 2>/dev/null
        killall -INT wvdial 2>/dev/null
        rm -f /var/run/ppp*.pid
        rm -f /var/lock/LCK*
        echo -en "Disconnected at : " >> $PROG_LOG
        date >> $PROG_LOG
        echo "------------------------------------------------------------------" >> $PROG_LOG
        clean_up
        echo -en "Disconnected at : "
        date
        echo "See $PROG_LOG for details ..."
        exit
}

function keep_time_check
{
        # keeps a seconds count and gives three warning beeps
        # at 30, 20 and 10 sec before disconnecting
        ALIGN="\033[5G"
        CUT_OFF=$((HOW_MANY_SECS-5))
        echo -en "Connected at : "
        date    
        echo "Connection will be cut off after $CUT_OFF secs"

        WARN1=$((CUT_OFF-10))
        SEC=0
        while [ $SEC -lt $CUT_OFF ]
        do
           SEC=$((SEC + 1))
           if [ $SEC -ge $WARN1 ]; then
              echo -en "\07"
           fi
           sleep 1
           echo -en $ALIGN$SEC" secs"
        done
        echo
        disconnect
}
        
function chk_if_online
{
        rm -f /var/run/ppp*.pid
        # Remove old ppp*.pid files if any

        while [ 0 ]  #Endless loop.
        do
           # Checks for presence of the ppp?.pid,
           # indicating a successful logon.

           if [ -e /var/run/ppp0.pid ]; then
              clean_up
              
              ### However, quit if pppd is started by default            
              tail  $WV_LOG | grep "know what to do" > $TEMP_FILE1
              PPP_ERROR=`cat $TEMP_FILE1`
              if ! [ "$PPP_ERROR" = "" ]; then
                  echo $PPP_ERROR
                  killall -INT pppd 2>/dev/null
                  killall -INT wvdial 2>/dev/null
                  rm -f /var/run/ppp*.pid
                  rm -f /var/lock/LCK*
                  clean_up
                  term_exit
              fi    

              echo "------------------------------------------------------------------" >> $PROG_LOG
              while [ ! -s $TEMP_FILE2 ]; do
                 ### Wait till IP addresses are established
                 tail -6 /var/log/messages | grep "IP" > $TEMP_FILE2
              done

              # Keep a log of IP addresses in log file              
              cat $TEMP_FILE2 >> $PROG_LOG
              
              # Also note when successfully connected
              echo -en "Connected at : " >> $PROG_LOG
              date >> $PROG_LOG
              keep_time_check
                    
         else

              LYNE=`tail -1 $WV_LOG | cut -b 1-55`
              echo $LYNE | grep "not responding" > $TEMP_FILE2
              PPP_ERROR=`cat $TEMP_FILE2`
              if ! [ "$PPP_ERROR" = "" ]; then
                 echo -en "\n\nCheck your modem and retry :-)\n\n"
                 clean_up
                 term_exit
              fi   

           fi
        done 

}	# end of chk_if_online

function clean_up
{
	rm -f ${TEMP_FILE1}
	rm -f ${TEMP_FILE2}
}


function graceful_exit
{
	clean_up
	exit
}

function term_exit
{
	echo "${PROGNAME}: Terminated"
	clean_up
	exit
}


function usage
{
	echo "Usage: ${PROGNAME} [-h | --help] [-c sec] [-d]"
}


function helptext
{
	local tab=$(echo -en "\t\t")
		
	cat <<- -EOF-

        ${PROGNAME}                                       ver. ${VERSION}
	
        This is a  program to dial through wvdial and cut out 
        automatically after given number of secs.
	
        $(usage)
	
        Options:
	
        -h, --help	Display this help message and exit.
        -c  sec		connect
        -d              disconnect
			
        NOTE: 1] You must be the superuser to run this script.
              2] For -c option run in background with &
                 [viz. $PROGNAME -c 540 & (to disconnect after
                 9 min )]

-EOF-
}	


###########################################################################
#	Program starts here
###########################################################################

# Trap TERM, HUP, and INT signals and properly exit

trap term_exit TERM HUP

# Process command line arguments

if [ "$1" = "" ]; then
    helptext
    graceful_exit
fi

if [ "$1" = "--help" ]; then
    helptext
    graceful_exit
fi

# Process arguments - edit to taste

while getopts ":hc:d" opt; do
    case $opt in

    c )	chk_if_root
        HOW_MANY_SECS=$2
        echo $PROGNAME"                     ver - "$VERSION
        echo
        echo "Dialing $CONNECTION ..."
        echo 
        wvdial $CONNECTION > $WV_LOG 2>&1 &
        chk_if_online
        ;;

    d )	chk_if_root
        disconnect 
        ;;

    h ) helptext
	graceful_exit 
	;;

    * )	usage
	exit 1
    esac
done

clean_up
graceful_exit


###########################################################################
#	Everything below ignored
###########################################################################
