#!/usr/bin/env python

import os
import ftplib
import stat
import string
import sys


# Delete remote directory
def DeleteRemoteDirContent(ftp):
    # 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)




# Function that copies a local directory to a remote one
def UploadDir(dir,ftp):
    # Local directory setting
    os.chdir(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('..')




# To be able to use this file as a stand-alone and an importable module
if __name__ == '__main__':
    host          = 'pages.videotron.com'
    username      = 'vloudwiq'
    password      = 'b1a6bach'

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


    #######################
    # Open FTP connection #
    #######################
    try:
        ftp = ftplib.FTP(host)
        ftp.login(username,password)
    except:
        die('Unable to connect to FTP site')


    ######################
    # Delete remote site #
    ######################
    DeleteRemoteDirContent(ftp)
    print 'Content successfully deleted'
    

    #######################
    # Upload current site #
    #######################
    UploadDir('pool',ftp)
    print 'Website successfully updated'


    ftp.quit()
