#!/usr/local/bin/python

# ftpy is ftp clone.

import ftpui,ftpclient,sys,getpass,string,socket
from ftpy_define import *

class ftpy:

	#Print normal massege
	def printMassege(self,msg_list):
		for ent in msg_list:
			print ent

	#Print error massege
	def printError(self,err_msg,err_obj):
		if len(err_obj.args) == 1:
			args = err_obj.args[0]
			print "%s %s" % (err_msg,args[4:])
		elif len(err_obj.args) == 2:
			args = err_obj.args[1]
			print "%s %s" % (err_msg,args)
		else:
			print err_msg
		
	#FTP Connection to FTP Server
	def connect(self,hostname,portno):
		self.ftpclient.setHostname(hostname)
		self.ftpclient.setPortno(portno)
		res = self.ftpclient.connect()
		if res == C_OK:
			user = raw_input("Name (" + hostname + "):")
			password = getpass.getpass()
			self.ftpclient.setUser(user)
			self.ftpclient.setPassword(password)
			res = self.ftpclient.login()
			if res <> C_OK:
				self.printError("Login Failure:",self.ftpclient.getError_Obj())
		else:
			self.printError("Connection Error:",self.ftpclient.getError_Obj())
			
	#Close Connection
	def bye(self):
		self.ftpclient.close()
	
	#Open Connection
	def open(self,command):
		if len(command) == 2:
			hostname = command[1]
			try:
				socket.gethostbyname(hostname)
				self.connect(hostname,None)
			except Exception, e:
				print "Could not find server."
		else:
			print "usage : open <hostname>"

	#Print remore dir
	def ls(self,command):
		if len(command) > 2:
			print "usage : ls [<pattarn>]"
		elif len(command) == 1:
			res = self.ftpclient.getRemoteDirData()
			if res == C_OK:
				self.printMassege(self.ftpclient.getRemoteDir_Obj())
			else:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		elif len(command) == 2:
			res = self.ftpclient.getRemoteDirData(command[1])
			if res == C_OK:
				self.printMassege(self.ftpclient.getRemoteDir_Obj())
			else:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())

	#Print current dir
	def pwd(self):
		res = self.ftpclient.getCurrentRemoteDir()
		if res == C_OK:
			self.printMassege(self.ftpclient.getMsg_Obj())
		else:
			self.printError("Connection Error:",self.ftpclient.getError_Obj())

	#Change remote dir
	def cd(self,command):
		if len(command) == 2:
			res = self.ftpclient.changeRemoteDir(command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		else:
			print "usage : cd <dir_name>"

	#Get file
	def get(self,command):
		if len(command) == 1 or len(command) > 3:
			print "usage : get <remore_filename> [<local_filename>]"
		elif len(command) == 2:
			res = self.ftpclient.getRemoteFile(command[1],command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		elif len(command) == 3:
			res = self.ftpclient.getRemoteFile(command[1],command[2])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
	
	#Put file
	def put(self,command):
		if len(command) == 1 or len(command) > 3:
			print "usage : put <local_filename> [<remote_filename>]"
		elif len(command) == 2:
			res = self.ftpclient.putLocalFile(command[1],command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		elif len(command) == 3:
			res = self.ftpclient.putLocalFile(command[2],command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
	
	#Create dir
	def mkdir(self,command):
		if len(command) == 2:
			res = self.ftpclient.createRemote_dir(command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		else:
			print "usage : mkdir <dir_name>"

	#Remove dir
	def rmdir(self,command):
		if len(command) == 2:
			res = self.ftpclient.removeRemote_dir(command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		else:
			print "usage : rmdir <dir_name>"

	#Remove file
	def rm(self,command):
		if len(command) == 2:
			res = self.ftpclient.removeRemoteFile(command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		else:
			print "usage : rm <file_name>"

	#Change mode
	def chmod(self,command):
		if len(command) == 3:
			res = self.ftpclient.changeModeRemoteFile(command[2],command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		else:
			print "usage : chmod <mode> <file_name>"

	#Get Directroy
	def getdir(self,command):
		if len(command) == 2:
			if string.find(command[1],"/") >= 0:
				print string.find(command[1],"/")
				print "sorry <dir_name>/<subdir_name>.. not support"
			else:
				res = self.ftpclient.getRemoteDir(command[1])
				if res <> C_OK:
					self.printError("Connection Error:",self.ftpclient.getError_Obj())
		else:
			print "usage : getdir <dir_name>"
	
	#Print local current dir
	def lpwd(self):
		res = self.ftpclient.getCurrentLocalDir()
		if res == C_OK:
			self.printMassege(self.ftpclient.getMsg_Obj())
		else:
			self.printError("Connection Error:",self.ftpclient.getError_Obj())

	#Change local dir
	def lcd(self,command):
		if len(command) == 2:
			res = self.ftpclient.changeLocalDir(command[1])
			if res <> C_OK:
				self.printError("Connection Error:",self.ftpclient.getError_Obj())
		else:
			print "usage : lcd <dir_name>"

	#Output prompt and Input command
	def prompt(self):
		command = self.ftpui.user_input()
		command = string.split(command," ")
		res = self.method_call(command)
		return res

	def method_call(self,command):
	
		if command[0] == "bye":
			self.bye()
			return 0
		elif command[0] == "open":
			self.open(command)
		elif command[0] == "ls":
			self.ls(command)
		elif command[0] == "pwd":
			self.pwd()
		elif command[0] == "cd":
			self.cd(command)
		elif command[0] == "get":
			self.get(command)
		elif command[0] == "put":
			self.put(command)
		elif command[0] == "mkdir":
			self.mkdir(command)
		elif command[0] == "rmdir":
			self.rmdir(command)
		elif command[0] == "rm":
			self.rm(command)
		elif command[0] == "chmod":
			self.chmod(command)
		elif command[0] == "getdir":
			self.getdir(command)
		elif command[0] == "lpwd":
			self.lpwd()
		elif command[0] == "lcd":
			self.lcd(command)
		else:
			print "?Invalid command"
		return 1
		
	#Main Loop
	def main(self):
		while self.prompt():
			pass
	
	#Class Initial
	def __init__(self,hostname="",portno=21,pasv=False):
		self.ftpclient = ftpclient.ftpclient()
		self.ftpui = ftpui.ftpui()
		res = C_OK
		if pasv == True:
			res = self.ftpclient.setPasvmode()
		if hostname <> "":
			self.connect(hostname,portno)
		self.main()

#Initial
def init():
	#Arg Check
	hostname,portno,ui,pasv,result = checkArgv()
	if result == C_OK:
		if hostname <> "":
			result = checkHostname(hostname)
			if result <> C_OK:
				print "Could not find server."
				return None,None,None,None,C_NG
		if portno <> "":
			result = checkPortno(portno)
			if result <> C_OK:
				print "Portno not Integer."
				return None,None,None,None,C_NG
		return hostname,portno,ui,pasv,result
	else:
		print "usage: ftpy [-g] [hostname] [portno]"
		return None,None,None,None,C_NG
	
#Check Argv
def checkArgv():
	hostname = ""
	portno = 21
	ui = ""
	pasv = False
	result = C_OK
	if len(sys.argv) == 1:
		ui = C_CUI
	elif len(sys.argv) == 2:
		ui = C_CUI
		hostname = sys.argv[1]
	elif len(sys.argv) == 3:
		if sys.argv[1][0] == "-":
			find_g = string.find(sys.argv[1],"g")
			find_p = string.find(sys.argv[1],"p")
			if find_g >= 0:
				ui = C_GUI
			if find_p >= 0:
				pasv = True
			if find_g < 0 and find_p < 0:
				return C_NG
			hostname = sys.argv[2]
		else:
			ui = C_CUI
			hostname = sys.argv[1]
			portno = sys.argv[2]
	elif len(sys.argv) == 4:
		if sys.argv[1][0] == "-":
			find_g = string.find(sys.argv[1],"g")
			find_p = string.find(sys.argv[1],"p")
			if find_g >= 0:
				ui = C_GUI
			if find_p >= 0:
				pasv = True
			if find_g < 0 and find_p < 0:
				return C_NG
			hostname = sys.argv[2]
			portno = sys.argv[3]
		else:
			result = C_NG
	elif len(sys.argv) > 4:
		result = C_NG
		
	return hostname,portno,ui,pasv,result
	
#Check hostname
def checkHostname(hostname):
	try:
		socket.gethostbyname(hostname)
		return C_OK
	except Exception, e:
		return C_NG
		
#Check port no
def checkPortno(portno):	
	try:
		portno = int(portno)
		return C_OK
	except Exception, e:
		result = C_NG

if __name__ == "__main__":

	hostname,portno,ui,pasv,result = init()
	if result == C_OK:
		if ui == C_GUI:
			print "Sorry -g Not Support..."
		else:
			#ftpy Class
			app = ftpy(hostname,portno,pasv)
		
