import serial
import time
import sys
import os

bad_words = ['Wuwenjie',':count=0','CLI>']
send_char = '\r\n'

def response_format(response,ser_write):

	response_check = response.split(':')

	for i in response_check: 

		if (i == 'Wuwenjie'): 
			flag = 1
			if (flag != 1):
				time.sleep(1)

	for i in bad_words:
		response = response.replace(i,'').replace(ser_write,'')

	return response

def interactive_serial():

	i = 0
	flag = 0
	command = ''

	ser = serial.Serial(sys.argv[2],115200,parity="N",stopbits=1,bytesize=8,timeout=8,)

	if(ser.isOpen() == False): 
		try:
			ser.open()
		except ser.SerialException as error: 
			print("Can't open connection with " + sys.argv[1])
			print(error)

	while (command != 'exit'):

		command = input("pwn_link1>> ")
		ser.write((command + send_char).encode('utf-8'))
		ser.flush()
		response = ser.read(ser.inWaiting()).decode()
		ser.flush()
		response_check = response.split(':')

		response = response_format(response,command)

		if(command == 'clear'):

			os.system('cls' if os.name == 'nt' else 'clear')

		else:

			print(response)

def extract_envram_raw(file_name,port):

	ser = serial.Serial(port,115200,parity="N",stopbits=1,bytesize=8,timeout=8,)
	ser.write(('envram show' + send_char).encode('utf-8'))
	ser.flush()
	response = ser.read(ser.inWaiting()).decode()
	response = response_format(response,'envram show')
	file = open((file_name+'.txt'),"w+")
	file.write(response)
	file.close()

def extract_nvram_raw(file_name,port):

	ser = serial.Serial(port,115200,parity="N",stopbits=1,bytesize=8,timeout=8,)
	ser.write(('nvram show' + send_char).encode('utf-8'))
	ser.flush()
	response = ser.read(ser.inWaiting()).decode()
	response = response_format(response,'nvram show')
	file = open((file_name+'.txt'),"w+")
	file.write(response)
	file.close()

basic_help = r'''

This is the basic help. Use --help/-h for basic and -hh for advanced help

=====================================================================================
--shell 	Open the interactive serial "shell" with the device

	Format:

		>> py LinkOneShell.py --shell [PORT]

	Example: 

		>> py LinkOneShell.py --shell COM8

=====================================================================================
--Dump  	Dump data from nvram or envram and save it into a file

	Format:

		>> py LinkOneShell.py --dump [envram/nvram] [file name] [PORT]

	Example:

		>> py LinkOneShelltest.py --dump envram test COM8	

=====================================================================================
	'''
advanced_help = r'''

General:
	Basic options set

		--shell 				Open the interactive serial "shell" with the device
		--dump					Dump data from nvram or envram and save it into a file

Shell:
	These options can be used during the serial communication (--shell)

		reboot					Reboot the device
		restart					Restart the system
		time 					Return the time storage by the system
		syslog					Show the system log 
		ping 					Ping a defined host 
		wlconf					wl0 <up|down|start>
		route					Show Routing tables/Interface statistics
		thread					Show threads info
		mbuf					Network stack stats
		ifconfig				“Interface Configuration”
		?						Show all "supported" official commands (some of them not working)

Ethernet:
	These options can be use to manipulate ethernet settings (extract from the official help)

		usage: et [ [ -a | -i ] interface ] and one of:
        up
        down
        loop <0 or 1>
        dump
        msglevel <bitvec> (error=1, trace=2, prhdr=4, prpkt=8)
        promisc <0 or 1>
        qos <0 or 1>
        txdown
        speed <auto, 10half, 10full, 100half, 100full, 1000full>
        phyrd [<phyaddr>] <reg>
       	phywr [<phyaddr>] <reg> <val>
        robord <page> <reg>
        robowr <page> <reg> <val>

WL:
	These options may provide useful information (extract from the official help)

    	Usage: (null) [-a|i <adapter>] [-h] [-d|u|x] <command> [arguments]

        -h                    this message and command descriptions
        -h [cmd]              command description for cmd
        -a, -i                adapter name or number
        -d                    output format signed integer
        -u                    output format unsigned integer
        -x                    output format hexdecimal

        ver         get version information

        status      Print information about current network association.
                    (also known as "assoc")

        sta_info
                    sta_info <xx:xx:xx:xx:xx:xx>

        assoclist
                    AP only: G

				'''


if(sys.argv[1] == '--shell'):
	interactive_serial()

elif((sys.argv[1] == '--help') or (sys.argv[1] == '-h')):
	print(basic_help)

elif(sys.argv[1] == '-hh'):
	print(advanced_help)

elif((sys.argv[1] == '--dump')):

	if(sys.argv[2] == 'envram'):
		extract_envram_raw(sys.argv[3],sys.argv[4])
	elif(sys.argv[2] == 'nvram'):
		extract_nvram_raw(sys.argv[3],sys.argv[4])


	else:
		print("Cant dump '" + sys.argv[3] + "', unknowm parameter" '\n\n')
		print("Use --help/-h for basic and -hh for advanced help")

