import os
import sys
import string
import time
import Queue
import threading
import socket
import telnetlib
from utilities import *
from telnet_functions import *

USERNAME      = "root"                 #username on that account
USERNAMEALT   = "root"                 #alternate username on that account
PASSWORD      = "nalcopassword"        #alternate password on that account
PASSWORDALT   = "nggpassword"          #password on that account        
IP_LIST       = "iplist.txt"           #List of devices to upgrade
CFG_LIST      = "config.txt"           #configuration file to use
OUTPUT_CSV    = "output.csv"
UPDATE_SUCCESS= "UPDATE_SUCCESS"
UPDATED_FAILED= "UPDATED_FAILED"
REBOOT_GW     = 1
MAX_THREADS   = 30

def cleanup(id, ipaddr, output, iplog, mysock, response_queue, print_queue):
    print_queue.put("[" + str(id) + "] " + output)
    response_queue.put(ipaddr + "," + output + "\n")
    iplog.write(output)                    
    iplog.close()
    if mysock != "":
        mysock.close()

class clientThread (threading.Thread):
    def __init__(self, id):
        self.id = id
        threading.Thread.__init__(self)
        
    def run(self):
        self.runcount = 0
        while True:
            self.runcount = self.runcount + 1
            try:
                self.ipaddr = ip_queue.get()
            except Exception, e:
                break
            
            if self.ipaddr != "":
                self.error_con = 0
                print_queue.put("[" + str(self.id) + "] Working on " + self.ipaddr + "...")
                self.iplog = open(".\\logs\\" + self.ipaddr + ".txt", "w")

                self.tn, self.output = tryconnect(self.ipaddr)
                if self.output != "":
                    cleanup(self.id, self.ipaddr, self.output, self.iplog, self.tn, \
                            response_queue, print_queue)
                    continue
                
                self.status, self.output = trylogin(self.tn, USERNAME, PASSWORD, self.iplog)
                if self.status != UPDATE_SUCCESS:
                    if self.output.find("Failed to get prompt:") < 0:
                        cleanup(self.id, self.ipaddr, self.output, self.iplog, self.tn, \
                                response_queue, print_queue)
                        continue
                    else:
                        self.status, self.output = trylogin(self.tn, USERNAMEALT, PASSWORDALT, self.iplog)
                        if self.status != UPDATE_SUCCESS:
                            cleanup(self.id, self.ipaddr, self.output, self.iplog, self.tn, \
                                    response_queue, print_queue)
                            continue
            
                for cfgline in cfglist:
                    self.output = trywrite(self.tn, cfgline)
                    if self.output != UPDATE_SUCCESS:
                        self.iplog.write(self.output)
                        self.error_con = 1 
                        break
                    
                    self.status, self.output = tryread(self.tn, "#>", TELNET_TIMEOUT)
                    self.iplog.write(self.output)
                    
                if (REBOOT_GW == 1) and (self.error_con == 0):
                    trywrite(self.tn, "boot a=r\n")
                    self.status, self.output = tryread(self.tn, "rebooting", TELNET_TIMEOUT)
                    self.iplog.write(self.output)
                
                if(self.error_con == 0):
                    self.output = "Updated Success"
                
                cleanup(self.id, self.ipaddr, self.output, self.iplog, self.tn, \
                        response_queue, print_queue)
                ip_queue.task_done()
            else:
                print "[" + str(self.id) + "] Empty: " + str(self.runcount)
            
            if ip_queue.empty() == True:
                break

iplist = getIPlist(IP_LIST)
cfglist = getConfigList(CFG_LIST)
queue_len = len(iplist)

ip_queue = Queue.Queue(queue_len)
response_queue = Queue.Queue(queue_len)
print_queue = Queue.Queue(queue_len * 2)

for ip in iplist:
    ip_queue.put(ip)

try:
    os.mkdir(".\\logs\\")
except Exception, e:
    pass

for x in xrange(MAX_THREADS):
    clientThread(x).start()

count = 0
while count < (queue_len * 2):
    try:
        data = print_queue.get()
        print data
        count = count + 1
    except Exception, e:
        break

fh = open(OUTPUT_CSV, "w")
for x in xrange(queue_len):
    data = response_queue.get()
    if data != "":
        fh.write(data)
fh.close

print "Complete"
sys.exit(0)
