#!/usr/bin/env python

import os
import ftplib
import stat
import string
import sys
import time


# Function that copies a remote directory to a local one
def DownloadDir(ftp, dir):
    # Remote directory setting
    ftp.cwd(dir)

    # Local subdir creation
    os.mkdir(dir, 0777)
    os.chdir(dir)

    subdirs = []
    listing = []
    ftp.retrlines('LIST', listing.append)
    for line in listing:
        words = string.split(line, None, 8)
        # Skip short lines
        if len(words) < 6:
            continue
        filename = string.lstrip(words[-1])
        # Skip symbolic link
        i = string.find(filename, " -> ")
        if i >= 0 or words[0][0] == 'l':
            continue
        # Check for subdirs
        if words[0][0] == 'd':
            subdirs.append(filename)
            continue
        # Copy file
        fp = open(filename, 'wb')
        ftp.retrbinary('RETR ' + filename, fp.write)
        fp.close()

    # Recursively copy subdirectories
    for subdir in subdirs:
        # Skip '.' and '..'
        if subdir == '.' or subdir == '..':
            continue
        DownloadDir(ftp,subdir)

    # Backtrack
    os.chdir('..')
    ftp.cwd('..')




# Function that copies a local directory to a remote one
def UploadDir(dir,ftp):
    # Local directory setting
    os.chdir(dir)

    # Remote subdir creation
    ftp.mkd(dir)
    ftp.cwd(dir)

    subdirs = []
    listing = os.listdir('.')
    for filename in listing:
        mode = os.stat(filename).st_mode
        # Check for subdirs
        if stat.S_ISDIR(mode):
            subdirs.append(filename)
            continue
        # Copy file
        elif stat.S_ISREG(mode):
            fp = open(filename, 'rb')
            ftp.storbinary('STOR ' + filename, fp)
            fp.close()

    # Recursively copy subdirectories
    for subdir in subdirs:
        # Skip '.' and '..'
        if subdir == '.' or subdir == '..':
            continue
        UploadDir(subdir,ftp)

    # Backtrack
    ftp.cwd('..')
    os.chdir('..')




# Delete remote directory
def DeleteRemoteDir(ftp, dir):
    # Remote dir setting
    ftp.cwd(dir)

    # First empty subdir
    subdirs = []
    listing = []
    ftp.retrlines('LIST', listing.append)
    for line in listing:
        words = string.split(line, None, 8)
        # Skip short lines
        if len(words) < 6:
            continue
        filename = string.lstrip(words[-1])
        # Skip symbolic link
        i = string.find(filename, " -> ")
        if i >= 0 or words[0][0] == 'l':
            continue
        # Check for subdirs
        if words[0][0] == 'd':
            subdirs.append(filename)
            continue
        # Delete file
        ftp.delete(filename)

    # Recursively delete subdirectories
    for subdir in subdirs:
        # Skip '.' and '..'
        if subdir == '.' or subdir == '..':
            continue
        DeleteRemoteDir(ftp,subdir)

    # Backtrack
    ftp.cwd('..')

    # Delete now empty subdir
    ftp.rmd(dir)





# To be able to use this file as a stand-alone and an importable module
if __name__ == '__main__':
    tmpdir        = '_temp'
    host          = 'www.ecoledegolfddc.com'
    username      = 'ecolde6'
    password      = '0e0b291'
    remotesitedir = 'public_html'

    def die(message):
        print message
        sys.exit(1)


    #######################
    # Open FTP connection #
    #######################
    try:
        ftp = ftplib.FTP(host)
        ftp.login(username,password)
    except:
        die('Incapable de se connecter au site')


    ###################################
    # Create a backup of the web site #
    ###################################
    try:
        os.mkdir(tmpdir)
    except:
        die('Incapable de creer le repertoire "' + tmpdir + '"')
    os.chdir(tmpdir)

    # Get the web site
    DownloadDir(ftp, remotesitedir)

    # Rename the downloaded dir
    def IntToString(integer):
        if (integer < 10):
            return '0' + repr(integer)
        else:
            return repr(integer)

    currenttime = time.localtime();
    localname = 'site_' + IntToString(currenttime.tm_year) + '_' \
                        + IntToString(currenttime.tm_mon)  + '_' \
                        + IntToString(currenttime.tm_mday) + '_' \
                        + IntToString(currenttime.tm_hour) + '_' \
                        + IntToString(currenttime.tm_min)  + '_' \
                        + IntToString(currenttime.tm_sec)
    os.chdir('..')
    os.rename(tmpdir + '/' + remotesitedir, localname)
    os.rmdir(tmpdir)

    print 'Copie effectuee avec succes!'


    #######################
    # Upload current site #
    #######################
    if len(sys.argv) == 1:
        # Nothing to upload
        sys.exit(0)

    # Delete remote site
    DeleteRemoteDir(ftp,remotesitedir)

    # Create remote temp dir
    ftp.mkd(tmpdir)
    ftp.cwd(tmpdir)

    # Upload site
    path, dirtoupload = os.path.split(sys.argv[1].rstrip().rstrip('/').rstrip('\\'))
    if not os.path.isdir(dirtoupload):
        die('L\'argument "' + sys.argv[1] + '" n\'est pas valide.' + dirtoupload)

    UploadDir(dirtoupload,ftp)
    ftp.cwd('..')
    ftp.rename(tmpdir + '/' + dirtoupload, remotesitedir)
    ftp.rmd(tmpdir)

    print 'Site mise a jour avec succes!'

    ftp.quit()
