import os
import sys
import string
import socket
import telnetlib

UPDATE_SUCCESS= "UPDATE_SUCCESS"
UPDATED_FAILED= "UPDATED_FAILED"
TELNET_TIMEOUT= 20

def trywrite(sock, data):
    output = UPDATE_SUCCESS
    try:
        sock.write(data)
    except Exception, e:
        output = "%s" % e
        output = output.strip(",")
    
    return output

def tryread(sock, delimiter, timeout):
    status = UPDATE_SUCCESS
    output = ""
    try:
        output = sock.read_until(delimiter, timeout)
        if output.find(delimiter) < 0:
            output = output.strip(",")
            status = UPDATED_FAILED           
    except Exception, e:
        output = "%s" % e
        output = output.strip(",")
        status = UPDATED_FAILED
    
    return status, output

def trylogin(tn, username, password, iplog):
    status, return_stuff = tryread(tn, "login:", TELNET_TIMEOUT)
    if iplog != "":
        iplog.write(return_stuff)
    
    return_stuff = trywrite(tn, username + "\n")
    if return_stuff != UPDATE_SUCCESS:
        if iplog != "":
            iplog.write(return_stuff)
        return UPDATED_FAILED, "Error while sending username"
    
    status, return_stuff = tryread(tn, "word:", TELNET_TIMEOUT)
    if iplog != "":
        iplog.write(return_stuff)
    if status != UPDATE_SUCCESS:
        return UPDATED_FAILED, "Error while waiting for the password prompt: " + return_stuff
    
    if iplog != "":
        iplog.write(" " + password + "\n")
    return_stuff = trywrite(tn, password + "\n")
    if return_stuff != UPDATE_SUCCESS:
        if iplog != "":
            iplog.write(return_stuff)
        return UPDATED_FAILED, "Error while sending password"
    
    status, return_stuff = tryread(tn, "#>", TELNET_TIMEOUT)
    if iplog != "":
        iplog.write(return_stuff)
    if status != UPDATE_SUCCESS:
        return UPDATED_FAILED, "Failed to get prompt: " + return_stuff

    return UPDATE_SUCCESS, ""

def tryconnect(ipaddr):
    output = ""
    try:
        sock = telnetlib.Telnet(ipaddr)
    except Exception, e:
        sock = ""
        output = "Failed to connect %s" % e
    return sock, output