#!/usr/bin/python
#
#  Copyright Contemporary Computer Concepts
#  Charles Stuart - October, 2000
#
#  ftprtr.py
#	Retrieve satellite office data files
#	from a remote FTP site
#

from ftplib import FTP
import string,sys,time,os

# Modifiable Variables
#    ID = Sender ID's to retrieve
#    USER = FTP server user name
#    PWD = FTP server password
#    SERVER = FTP server
#    DATA_PATH = Directory to back up
#    TEMP = Directory for temporary files
ID = ['IRPMain']
USER = 'cstuart'
PWD = '29.GXDsK'
SERVER = 'ftp.netwinder.org'
DATA_PATH = '/root/ftp-test'
TEMP = '/root/ftp-test/retr'

# Global Internal Variables
global_attempts = 3

def get_archive():
  local_attempt = 0
  today = string.split( time.ctime( time.time() ) )
  while ( local_attempt < 2 ):
    local_attempt = local_attempt + 1
    try:
      connect = FTP(SERVER, USER, PWD)
      print(`connect.getwelcome`)
      connect.set_debuglevel(1)
    except:
      print("Couldn't Connect")

  local_attempt = 0
  date = today[1] + "-" + today[2] + "-" + today[4]
  length = len(ID)
  while ( length ):
    archive_name = ID[length-1] + "-" + date + ".tgz"
    retrcmd = 'RETR ' + archive_name
    while ( local_attempt < 3 ):
      local_attempt = local_attempt + 1
      try:
        connect.retrbinary( retrcmd, open(archive_name, 'wb').write )
        break
      except:
        print("Failed " + archive_name + ": Try: " + `local_attempt`)
        rmcmd = "rm " + archive_name
        os.system(rmcmd)
    length = length - 1
  
#  while ( local_attempt < 2 ):
#    local_attempt = local_attempt + 1
#    # Step through ID's of archives to retrieve
#    for count in range ( (len(ID) - 1) ):
#      archive_name = ID[count] + "-" + today[1] + "-" + today[2] + "-" + today[4] + ".tgz"
#      retrcmd = 'RETR ' + archive_name
#      try:
#        connect.retrbinary( retrcmd, open(archive_name, 'wb').write )
#      except:
#        print("Unable to retrieve archive " + archive_name)
#        local_attempt = local_attempt + 1

  connect.quit()
  return archive_name

# Start of Execution

file_name = get_archive()

