#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script generation

:author:       Michael Mulich
:copyright:    2010 by Penn State University
:organization: WebLion Group, Penn State University
:license:      GPL, see LICENSE for more detail
"""
import os
import sys
import stat
from optparse import OptionParser

assert sys.version_info >= (2, 7), "Python >= 2.7 is required"

__version__ = '0.1.0'
script_template = """\

%(initialization)s
import %(module_name)s

if __name__ == '__main__':
    %(module_name)s.%(callable)s(%(arguments)s)
"""

usage = "%prog [options] module callable script_name"

parser = OptionParser(usage=usage)
parser.add_option('-a', '--default-arguments', dest='arguments',
                  default='',
                  help="Arguments to call the callble with.",
                  metavar='ARGS')
parser.add_option('-i', '--init-code', dest='initialization',
                  default='',
                  help="Code that initializes the script or arguments",
                  metavar='CODE')
parser.add_option('-e', '--executable', dest='executable',
                  default='/usr/bin/env python',
                  help="An executable to call the script with... used in the "
                       "script's shabang line.",
                  metavar='EXEC')
parser.add_option('-d', '--directory', dest='directory',
                  default=os.curdir,
                  help="The directory where the output should go, defaults to "
                       "the current directory.",
                  metavar='DIR')

def main():
    (options, args) = parser.parse_args()

    try:
        (module, callable, script_name) = args
    except ValueError, err:
        print('\n'.join([parser.get_usage(), repr(err)]))
        sys.exit(1)

    # Generate the contents of the script
    shabang_line = '#!' + options.executable
    script_body = script_template % dict(module_name=module,
                                         callable=callable,
                                         initialization=options.initialization,
                                         arguments=options.arguments,
                                         )
    script_body = shabang_line + script_body

    # Create and write to the script file
    script_path = os.path.join(options.directory, script_name)
    with open(script_path, 'w') as f:
        f.write(script_body)
    mode = (stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)
    os.chmod(script_path, mode)

if __name__ == '__main__':
    main()
