#!/usr/bin/env python
"""
    S3 generate '.done' file when a '.done' directory is detected

    @author: Jean-Lou Dupont
"""
__version__="0.1"
import os, sys, argparse
op=os.path

try:
    if os.environ.get("DEVMODE", False):
        raise
    import jldaws #@UnusedImport
except:
    ### must be in dev mode then    
    this_dir=op.dirname(__file__)
    lib_path=op.abspath(op.join(this_dir, ".."))
    sys.path.insert(0, lib_path)
    import jldaws #@UnusedImport

########################################################################

DESC="""Generate .done file in S3 bucket file upon detection of .done directory - %s

E.g.  source_path/dir1.done  ==> generate 'dir1.done' in -bn bucket ==> delete 'source_path/dir1.done' directory

Use the -d option for deleting the source .done directory when a .done file was successfully generated in the -bn bucket
Use the -extd option to specify the extension to use for the source directories
Use the -extf option to specify the extension to use for the generation of files in the -bn bucket 
Use the -mp option instead -d to move the source directory instead of deleting it

""" % __version__
DEFAULTS={
          "polling_interval": 60
          }

def main():
    try:
        import logging
        import jldaws.do_setup  #@UnusedImport
        import jldaws.do_checks #@UnusedImport
        
        parser=argparse.ArgumentParser(description=DESC, fromfile_prefix_chars='@', formatter_class=argparse.RawTextHelpFormatter)
        
        parser.add_argument('-bn',   dest='bucket_name',     type=str, help="Bucket name", required=True)
        parser.add_argument('-sp',   dest='path_source',     type=str, help="Path to monitor for .done directories",   required=True)
        parser.add_argument('-mp',   dest='path_move',       type=str, help="Path where to move .done directories",    default=None)
        
        parser.add_argument('-d',    dest='delete_source',   action="store_true", help="Delete source .done directory upon success", default=False)
        
        parser.add_argument('-extd',  dest='extd',           type=str, help="Use the specified extension for source directories", default="done")
        parser.add_argument('-extf',  dest='extf',           type=str, help="Use the specified extension for generated files",    default="done")
        
        parser.add_argument('-p',    dest="polling_interval", type=int, action="store", help="Polling interval (seconds)", default=DEFAULTS["polling_interval"])
        
        from jldaws.script_s3done import run
        from jldaws.tools_sys import process_command_line
        args=process_command_line(parser)
        run(**args)

    except KeyboardInterrupt:
        logging.info("...exiting")
        sys.exit(0)##no probs
        
    except Warning, w:
        logging.warning(str(w))
        sys.exit(1)
        
    except Exception,e:
        logging.error(str(e))
        sys.exit(1)
        
sys.exit(main())
