import os
import sys
import string
import rci
import digicli
import Queue
import thread
import time
from socket import *

#### FILES AND ARGS ####
file1 = "dia.py" #put file name to autostart here
args1 = "digi_dia.yml" #put args to use in autostart here
#### END ####

startup_telnet_commands = ["root\r\n", "nggpassword\r\n", "who\r\n", "set trace state=on mode=conc mask=printf:+awcid\r\n", "set trace mask=ppp:+awcid\r\n"] #put cli commands you'd like to start here, mostly for set trace commands
PYFOLDER = "WEB/python"
TELNET_HOST = "127.0.0.1"
TELNET_PORT = 23
MAX_SIZE = 1000
MAX_BUFFER = 2048

def clean_response(temp_string):
    temp_string = "".join(i for i in temp_string if ord(i)<128 and ord(i)>7)
    temp_string = temp_string.replace(">", "##gtr##")
    temp_string = temp_string.replace("<", "##less##")
    return temp_string 

def rci_telnet_connection(cmd):
    if cmd == "<get_data/>":
        response = ""
        while True:
            try:
                data = trace_read_queue.get(True, 1)
            except:
                break
            response = response + data
        return "<response>" + clean_response(response) + "</response>"
    elif cmd == "<send_break/>":
        try:
            trace_write_queue.put_nowait("\x03")
        except Exception, e:
            return "<response>Failed to place data</response>"
    elif cmd == "<flush_write_queue/>":
        while True:
            try:
                data = trace_write_queue.get_nowait()
            except Exception, e:
                break
    elif cmd == "<flush_read_queue/>":
        while True:
            try:
                data = trace_read_queue.get_nowait()
            except Exception, e:
                break
    else:
        try:
            trace_write_queue.put_nowait(cmd + "\r\n")
        except Exception, e:
            return "<response>Failed to place data</response>"
    return "<response>Success</response>"

def rci_cb_exec(cmd):
    response = ""
    status, output = digicli.digicli(cmd)
    for line in output:
        response = response + line

    response = clean_response(response)
    if status:
        return response
    else:
        return "Error: " + response

def callback_exec_thread():
    rci.add_rci_callback("exec", rci_cb_exec)

def callback_trace_thread():
    rci.add_rci_callback("tel_conn", rci_telnet_connection)

def telnet_connection_thread():
    while True:
        try:
            telnet_socket = socket(AF_INET, SOCK_STREAM)
            telnet_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            telnet_socket.connect((TELNET_HOST, TELNET_PORT))
            break
        except Exception, e:
            time.sleep(15)
        
    telnet_socket.settimeout(5)
    
    while True:
        time.sleep(2)
        data = ""
        try:
            data = trace_write_queue.get_nowait()
        except Exception, e:
            pass
        
        if data != "":
            try:
                telnet_socket.send(data)
            except Exception, e:
                pass
        
        data = ""        
        try:
            data = telnet_socket.recv(MAX_BUFFER)
        except Exception, e:
            continue
        
        if data != "":
            try:
                trace_read_queue.put_nowait(data)
            except Exception, e:
                pass

trace_read_queue = Queue.Queue(MAX_SIZE)
trace_write_queue = Queue.Queue(MAX_SIZE)
for command in startup_telnet_commands:
    trace_write_queue.put_nowait(command)

thread.start_new_thread(telnet_connection_thread, ())    
thread.start_new_thread(callback_exec_thread, ())
thread.start_new_thread(callback_trace_thread, ())

#TODO, look at all args...
if file1 != "":
    if args1 != "":
        sys.path.insert(0, os.path.join(PYFOLDER, args1))
    execfile(os.path.join(PYFOLDER, file1))

while True: #sleep forever in case we get here
    time.sleep(120)
