#!/usr/bin/env python
"""
    Executes a local script upon receiving a message on a specific Amazon SNS topic

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

try:
    import jldaws
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

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

DESC="Executes script based on SNS message received on a specific topic - %s" % __version__
DEFAULTS={
          "polling_interval": 30
          ,"batch_size": 10
          }

def main():
    try:
        import jldaws.do_setup
        import logging
        import jldaws.do_checks
        
        parser=argparse.ArgumentParser(description=DESC)
        parser.add_argument('-tn', dest='topic',       type=str, help="Topic to subscribe to", required=True)
        parser.add_argument('-mn', dest='module_name', type=str, help="Python module name to execute 'run' callable OR 'None'", required=True)
        parser.add_argument('-p',  type=int, dest="polling_interval", action="store", help="Polling interval in seconds", default=DEFAULTS["polling_interval"])
        parser.add_argument('-j',             dest="enable_json",    action="store_true", help="Outputs JSON object to stdout")
        parser.add_argument('-bs',          type=int, nargs=1, dest="batch_size",  action="store", help="Maximum message batch size to process per interval", default=DEFAULTS["batch_size"])
        args=parser.parse_args()
        
        from jldaws.script_exec import run
        run(args)

    except KeyboardInterrupt:
        logging.info("..Exiting")
        sys.exit(0)##no probs
        
    except Exception,e:
        logging.error(str(e))
        sys.exit(1)
        

sys.exit(main())