#!/usr/bin/python
#
#  Copyright Contemporary Computer Concepts
#  Charles Stuart - August, 2000
#
#  ftpbak.py
#	Transfer satellite office data files
#	to a remote FTP site for later pickup
#

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

# Modifiable Variables
#    ID = Sender or Organization or Branch ID
#    USER = FTP server user name
#    PWD = FTP server password
#    SERVER = FTP server
#    DATA_PATH = Directory to back up
#    TEMP = Directory for temporary files
ID = 'Dagger'
USER = 'cstuart@stuart-techctr@ftp.netwinder.org'
PWD = '29.GXDsK@cs4567'
SERVER = 'ftp.netwinder.org'
DATA_PATH = '/root/pdf'
TEMP = '/root/ftp-test/stor'

# Global Internal Variables
local_attempt = 0
global_attempts = 3

def packit():
  today = string.split(time.ctime(time.time()))
  archive_name = ID + "-" + today[1] + "-" + today[2] + "-" + today[4] + ".tgz"
  # remove old file copies
  rmcmd = '/bin/rm ' + TEMP + '/*'
  try:
    os.system(rmcmd)
  except:
    print("Unable to remove old archive")
  # copy files to temp directory with new file names
  cpcmd = '/bin/cp ' + DATA_PATH + '/* ' + TEMP
  try:
    os.system(cpcmd)
  except:
    print("Unable to copy source data")
  # create a compressed tar archive of the files
  tarcmd = 'tar -zcvf ' + archive_name + ' ' + TEMP + '/*'
  try:
    os.system(tarcmd)
  except:
    print("Unable to create new archive")
  # encrypt the archive
  # return the archive name
  return archive_name

def sendit(file_name):
  while (1):
    try:
      connect = FTP(SERVER, USER, PWD)
      connect.set_debuglevel(1)
      local_attempt = 0
      break
    except:
      print("Connection error")
      local_attempt = local_attempt + 1
      if ( local_attempt < 2 ):
        time.sleep(45)
      else:
        if ( local_attempt < 3 ):
          time.sleep(240)
        else:
          print("Couldn't get through - Contact CCC support")
          sys.exit()

  print(`connect.getwelcome()`)

  try:
    backup = open(file_name, 'r')
  except:
    print("Unable to open archive for sending")
    return

  while (1):
    try:
      # send up the file
      connect.storbinary('STOR ' + file_name, backup, 1024)
      break
    except:
      local_attempt = local_attempt + 1
      if ( local_attempt > 3):
        return

  connect.quit()

# Start of Execution
try:
  file_name = packit()
except:
  print("Couldn't create archive")

try:
  sendit(file_name)
except:
  print("Couldn't send archive")


