# -*- Mode: Python; tab-width: 4 -*-

#
# demo program for the ftp client library
#

from ftp import *

class grabber_client (ftp_client):
	def command (self, command, done_fun, line_fun=toss):
		if command is not None:
			self.grabber.log ('> %s' % command)
		ftp_client.command (self, command, done_fun, line_fun)


class grabber_receiver (local_file_receiver):
	def data_callback (self, data):
		sys.stdout.write ('%d ' % self.server.grabber.id)
		sys.stdout.flush()
		self.bytes = self.bytes + len(data)
		self.fd.write (data)

class file_grabber:
	counter = 0
	def __init__ (self,
				  host,
				  path,
				  userid=None,
				  local_path=None,
				  type='I'):
		self.host = host
		self.path = path
		self.type = type
		if local_path is None:
			import os
			dirname, rpath = os.path.split (path)
			self.local_path = rpath
		else:
			self.local_path = local_path

		if userid is None:
			# an hp site didn't like this
			#userid = 'user@%s' % (socket.gethostname())
			userid = 'user@'

		self.id = file_grabber.counter
		file_grabber.counter = file_grabber.counter + 1

		self.fc = grabber_client (host, 'anonymous', userid)
		self.fc.grabber = self
		self.fc.connect (self.connected_fun, self.print_server_info_line)

	def log (self, stuff):
		print '%d: %s' % (self.id, stuff)

	def print_server_info_line (self, line):
		self.log ('< %s' % line)

	def connected_fun (self, status):
		if status:
			self.log ('Logged in')
			self.fc.type (self.type, self.st_type)
		else:
			print status
			self.fc.close()

	def st_type (self, status):
		if status:
			self.fc.get (
				self.path,
				self.local_path,
				self.retr_result,
				grabber_receiver
				)
		else:
			print status
			self.fc.close()

	def retr_result (self, status):
		if status:
			self.log ('RETR command successful')
		else:
			self.log ('Transfer failed %s' % (repr(status)))
		self.fc.close()

import regex

urlreg = regex.compile ('ftp://\\([^/]+\\)/\\(.*\\)')
ftpreg = regex.compile ('\\([^:]+\\):\\(.*\\)')

regs = [urlreg, ftpreg]

def frob_args (args):
	locations = []
	for p in args:
		matched = 0
		for reg in regs:
			if reg.match (p) == len(p):
				host, path = reg.group(1), reg.group(2)
				locations.append (host, path)
				matched = 1
				break
		if not matched:
			print "Don't know what '%s' is." % p
	return locations

if __name__ == '__main__':
	import sys
	if len(sys.argv) < 2:
		print
		print 'Usage: %s [-bufsize <size>] <filespec> [...]' % sys.argv[0]
		print '  where <filespec> is a file location in one'
		print '  of the two following formats:'
		print
		print '    a) ftp://host.domain/path/to/file'
		print '    b) host.domain:/path/to/file'
	else:
		import string

		# handle buffer size argument
		i = sys.argv.index ('-bufsize')
		del sys.argv[i]
		s = string.atoi (sys.argv[i])
		del sys.argv[i]
		receive_channel.default_buffer_size = s

		grabbers = map (
			lambda x: file_grabber (x[0], x[1]),
			frob_args(sys.argv[1:])
			)
		asyncore.loop()
