#!/usr/bin/python

import sys
import os
import telnetlib, socket
import getopt
from time import sleep


HOST = "localhost"
PORT = 3217

Destnumber = 0
Fromnumber = 1
Protocol = 'pmp'
Automatic = 0
Debuglevel = 0

def wait(s):
    print tn.read_until(s,120)

def displayAvailable():
    print tn.read_some()

def cmd(c):
    tn.write(c + "\n")

def usage():
    print "usage: ltest -t <destination numer> -p <protocol (pmp|pp)>"




try:
    opts, args = getopt.getopt(sys.argv[1:], "ahf:t:p:H:d:", ["automatic", "help", "from=", "to=", "Protocol=", "host=", "debug="])
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err)
    usage()
    sys.exit(2)

for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit(0)
    elif o in ("-a", "--automatic"):
        Automatic = 1
        try:
            fn=open('/data/number')
            Destnumber=fn.readline().rstrip('\n')
            fn.close
        except:
            Destnumber = 8111
        try:
            fp=open('/data/protocol')
            Protocol=fp.readline().rstrip('\n')
            fp.close
        except:
            Protocol = 'pmp'
        break
    elif o in ("-h", "--help"):
        usage()
        sys.exit(0)
    elif o in ("-t", "--to"):
        Destnumber = a
    elif o in ("-H", "--host"):
        HOST = a
    elif o in ("-d", "--debug"):
        Debuglevel = a
    elif o in ("-p", "--protocol"):
        if a == 'pmp' or a == 'pp':
            Protocol = a
        else:
            usage()
            sys.exit(1)
    else:
        assert False, "unhandled option"
if Destnumber == 0:
    usage()
    sys.exit(1)

if Automatic != 1:
    sc = os.environ.get('CHANNELS')
    if sc == None:
        sc = raw_input("Cannot determine channels from environment, so tell me: ")
    channels = int(sc)
else:
    channels = 4


# O.K. loop through channels

for i in range(channels):

    print "Testing port",PORT+i
    try:
        tn = telnetlib.Telnet(HOST, PORT+i)
    except socket.error, (v,m):
        print "Failed to connect:",m
        sys.exit(1)

    tn.set_debuglevel(Debuglevel)


    cmd(':c -y') 
    cmd(':c -y') 
    cmd(':c -D "--l2-protocol=%s --l3-protocol=dss1" -n %s -N %i' % (Protocol, Destnumber, i+1))
    cmd(':p')
    cmd(':dstart')
    cmd(':s')

    ok = 0
    index = 9

    while index != 0:
        (index,match,string)=tn.expect([':dchannel --message="onhook"','end_of_fax','\n'],120)
        if index == 1:
            ok = 1
        print string,

    cmd(':quit')
    print tn.read_all()


    if ok == 1:
        print "***** Test OK *****"
    else:                
        print "***** Test FAILED *****"

    tn.close()

    if i < (channels - 1) and channels != 1:
        answer=raw_input('Hit Enter for next channel, q to quit ')
        if answer == "q":
            sys.exit(0)
        print "Waiting 5 seconds ..."
        sleep(5)
# end of loop
sys.exit(1)
