#!/usr/bin/env python

# wrapper script that will get installed by setup.py into the execution path

import sys, logging
from optparse import OptionParser
import os
from os.path import join, dirname, exists, realpath, abspath

# just provide the command line hook into the flashbake.commit module
if __name__ == "__main__":
    usage = "usage: %prog [options] <project_dir> [quiet_min]"

    parser = OptionParser(usage=usage, version='%prog 0.19')
    parser.add_option('-c', '--context', dest='context_only',
            action='store_true', default=False,
            help='just generate and show the commit message, don\'t check for changes')
    parser.add_option('-v', '--verbose', dest='verbose',
            action='store_true', default=False,
            help='include debug information in the output')

    (options, args) = parser.parse_args()

    level = logging.INFO
    if options.verbose:
        level = logging.DEBUG

    logging.basicConfig(level=level,
            format='%(message)s')

    ######################################################################
    # Setup path (borrowed directly from gwibber)
    LAUNCH_DIR = abspath(sys.path[0])
    logging.debug("Launched from %s", LAUNCH_DIR)
    source_tree_flashbake = join(LAUNCH_DIR, "..", "flashbake")

    # If we were invoked from a flashbake source directory add that as the
    # preferred module path ...
    if exists(join(source_tree_flashbake, "commit.py")):
        logging.info("Running from source tree; adjusting path")
        sys.path.insert(0, realpath(dirname(source_tree_flashbake)))
        try:
            from flashbake.commit import commit, parsecontrol
            from flashbake.context import buildmessagefile
        finally:
            del sys.path[0]
    else:
        logging.debug("Assuming path is correct")
        from flashbake.commit import commit, parsecontrol
        from flashbake.context import buildmessagefile
    
    # TODO look for plugin directory

    if len(args) < 1:
        parser.error('Must specify project directory.')
        sys.exit(1)

    project_dir = args[0]

    if not os.path.exists('%s/.control' % project_dir):
        parser.error('Could not find .control file in directory, "%s".' % project_dir)
        sys.exit(1)

    if options.context_only:
        (parse_results, control_config) = parsecontrol(project_dir)
        msg_filename = buildmessagefile(control_config)
        message_file = open(msg_filename, 'r')

        try:
            for line in message_file:
                print line.strip()
        finally:
            message_file.close()
            os.remove(msg_filename)            
        sys.exit(0)

    quiet_period = 0
    if len(args) == 2:
        try:
            quiet_period = int(args[1])
        except:
            parser.error('Quiet minutes, "%s", must be a valid number.' % args[1])
            sys.exit(1)

    commit(project_dir, quiet_period)
