#!/usr/bin/env python
#
# Script to delete a directory recursively, taking care
# of the system load
#
# Soluciones Informaticas Codigo23 S.L.U. - http://codigo23.net

import sys, os, time, shutil

def check_sleep():
    """
    Check the load of the server, sleep for 60 seconds
    if it higher than 3.5
    
    FIXME: both the sleep time and the load value should
    be parameters passed to the function (lazy!)
    """

    while os.getloadavg()[0] >= 3.5:
        print '  ** Load too high (%s), going to sleep for 60 seconds' % os.getloadavg()[0]
        time.sleep(60)
    return True

def removedirs(parent, dirs):
    """
    Remove directories recursively, checking the load
    after each removal.
    """
    for d in dirs:
        print '  -- removing directory: ', d
        shutil.rmtree(parent + '/' + d)
        after_sleep = check_sleep()

if __name__ == '__main__':
    """
    Execute the script, first get a list of the
    contents of the directory, then pass that list
    to removedirs(), so the contents get deleted
    properly.
    """
    if len(sys.argv) < 2:
        print 'Usage: %s dir-to-delete' % (sys.argv[0]) 
        sys.exit()

    if not os.path.isdir(sys.argv[1]):
        print '%s is not a directory' % (sys.argv[1])
        sys.exit()

    dirs = os.listdir(sys.argv[1])
    print 'Directories: (%s)' % len(dirs)
    print ' - deleting directories'
    removedirs(sys.argv[1], dirs)

