#!/usr/bin/env python
# make_qiime_py_file.py

"""
This is a script which will add headers and footers to new qcli scripts
and make them executable. 
"""

__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2013, The BiPy Project"
__credits__ = ["Greg Caporaso"]
__license__ = "GPL"
__version__ = "0.1.0"
__maintainer__ = "Greg Caporaso"
__email__ = "gregcaporaso@gmail.com"

from sys import exit
from os import popen
from os.path import exists
from time import strftime
from optparse import OptionParser
from qcli import (parse_command_line_parameters, 
                        make_option)

script_info={}
script_info['brief_description']="""Create a template qcli script.""" 
script_info['script_description']="""This script will create a template qcli script and make it executable.""" 
script_info['script_usage']=[] 
script_info['script_usage'].append(("""Example usage""","""Create a new script""","""%prog -a "Greg Caporaso" -e gregcaporaso@gmail.com -o my_script.py"""))  
script_info['script_usage_output_to_remove'] = ['my_script.py']
script_info['output_description']="""The result of this script is a qcli template script."""

script_info['required_options']=[\
    make_option('-o','--output_fp',help="The output filepath.")
] 

script_info['optional_options']=[
    make_option('-a','--author_name',
     help="The script author's (probably you) name to be included in"+\
     " the header variables. This will typically need to be enclosed "+\
     " in quotes to handle spaces. [default:%default]",default='AUTHOR_NAME'),
    make_option('-e','--author_email',
     help="The script author's (probably you) e-mail address to be included in"+\
     " the header variables. [default:%default]",default='AUTHOR_EMAIL'),
    make_option('-c','--copyright',
     help="The copyright information to be included in"+\
     " the header variables. [default:%default]",default='Copyright 2013, The BiPy project')
] 

script_info['version'] = __version__

def main():
    option_parser, opts, args = parse_command_line_parameters(**script_info)


    header_block = """#!/usr/bin/env python
# File created on %s
from __future__ import division

__author__ = "AUTHOR_NAME"
__copyright__ = "COPYRIGHT"
__credits__ = ["AUTHOR_NAME"]
__license__ = "GPL"
__version__ = "0.1.0"
__maintainer__ = "AUTHOR_NAME"
__email__ = "AUTHOR_EMAIL"
""" % strftime('%d %b %Y')

    script_block = """
from qcli import (parse_command_line_parameters, 
                  make_option)

script_info = {}
script_info['brief_description'] = ""
script_info['script_description'] = ""
script_info['script_usage'] = []
script_info['script_usage'].append(("","",""))
script_info['output_description']= ""
script_info['required_options'] = [
 # Example required option
 #make_option('-i','--input_fp',type="existing_filepath",help='the input filepath'),
]
script_info['optional_options'] = [
 # Example optional option
 #make_option('-o','--output_dir',type="new_dirpath",help='the output directory [default: %default]'),
]
script_info['version'] = __version__"""

    output_fp = opts.output_fp

    # Check to see if the file which was requested to be created
    # already exists -- if it does, print a message and exit
    if exists(output_fp):
        print '\n'.join(["The file name you requested already exists.",\
            " Delete extant file and rerun script if it should be overwritten.",\
            " Otherwise change the file name (-o).",\
            "Creating no files and exiting..."])
        exit(1) 

    # Create the header data
    header_block = header_block.replace('AUTHOR_NAME',opts.author_name)
    header_block = header_block.replace('AUTHOR_EMAIL',opts.author_email)
    header_block = header_block.replace('COPYRIGHT',opts.copyright)
    lines = [header_block]

    lines.append(script_block)
    lines += ['','','','def main():',\
     '    option_parser, opts, args =\\',\
     '       parse_command_line_parameters(**script_info)',\
     '','',\
     'if __name__ == "__main__":',\
     '    main()']


    # Open the new file for writing and write it.
    f = open(output_fp,'w')
    f.write('\n'.join(lines))
    f.close()
    
    # change mode to 755
    chmod_string = ' '.join(['chmod 755',output_fp])
    popen(chmod_string)
        




if __name__ == "__main__":
    main()