#!/usr/bin/env python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Search for branches underneath a directory and serve them all."""

import logging
import os
import sys

from optparse import OptionParser

from paste import httpserver
from paste.httpexceptions import HTTPExceptionHandler
from paste.translogger import TransLogger

from loggerhead import __version__
from loggerhead.apps.filesystem import (
    BranchesFromFileSystemRoot, UserBranchesFromFileSystemRoot)
from loggerhead.util import Reloader
from loggerhead.apps.error import ErrorHandlerApp


def command_line_parser():
    parser = OptionParser("%prog [options] <path>")
    parser.set_defaults(
        user_dirs=False,
        show_version=False,
        log_folder=None,
        )
    parser.add_option("--user-dirs", action="store_true", dest="user_dirs",
                      help="Serve user directories as ~user.")
    parser.add_option("--trunk-dir", metavar="DIR",
                      help="The directory that contains the trunk branches.")
    parser.add_option("--port", dest="user_port",
                      help=("Port Loggerhead should listen on "
                            "(defaults to 8080)."))
    parser.add_option("--host", dest="user_host",
                      help="Host Loggerhead should listen on.")
    parser.add_option("--prefix", dest="user_prefix",
                      help="Specify host prefix.")
    parser.add_option("--profile", action="store_true", dest="profile",
                      help="Generate callgrind profile data to "
                        "%d-stats.callgrind on each request.")
    parser.add_option("--reload", action="store_true", dest="reload",
                      help="Restarts the application when changing python"
                           " files. Only used for development purposes.")
    parser.add_option('--log-folder', dest="log_folder",
                      type=str, help="The directory to place log files in.")
    parser.add_option("--version", action="store_true", dest="show_version",
                      help="Print the software version and exit")
    return parser


def main(args):
    parser = command_line_parser()
    (options, args) = parser.parse_args(sys.argv[1:])

    if options.show_version:
        print "loggerhead %s" % __version__
        sys.exit(0)

    if len(args) > 1:
        parser.print_help()
        sys.exit(1)
    elif len(args) == 1:
        [path] = args
    else:
        path = '.'

    if not os.path.isdir(path):
        print "%s is not a directory" % path
        sys.exit(1)

    if options.trunk_dir and not options.user_dirs:
        print "--trunk-dir is only valid with --user-dirs"
        sys.exit(1)

    if options.reload:
        if Reloader.is_installed():
            Reloader.install()
        else:
            return Reloader.restart_with_reloader()

    if options.user_dirs:
        if not options.trunk_dir:
            print "You didn't specify a directory for the trunk directories."
            sys.exit(1)
        app = UserBranchesFromFileSystemRoot(path, options.trunk_dir)
    else:
        app = BranchesFromFileSystemRoot(path)

    # setup_logging()
    logging.basicConfig()
    logging.getLogger('').setLevel(logging.DEBUG)
    logger = getattr(app, 'log', logging.getLogger('loggerhead'))
    if options.log_folder:
        logfile_path = os.path.join(options.log_folder, 'serve-branches.log')
    else:
        logfile_path = 'serve-branches.log'
    logfile = logging.FileHandler(logfile_path, 'a')
    formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(name)s:'
                                  ' %(message)s')
    logfile.setFormatter(formatter)
    logfile.setLevel(logging.DEBUG)
    logger.addHandler(logfile)
    # setup_logging() #end
    app = ErrorHandlerApp(app)
    app = HTTPExceptionHandler(app)
    app = TransLogger(app, logger=logger)
    if options.profile:
        from loggerhead.middleware.profile import LSProfMiddleware
        app = LSProfMiddleware(app)

    if not options.user_prefix:
        prefix = '/'
    else:
        prefix = options.user_prefix

    try:
        from paste.deploy.config import PrefixMiddleware
    except ImportError:
        pass
    else:
        app = PrefixMiddleware(app, prefix=prefix)

    if not options.user_port:
        port = '8080'
    else:
        port = options.user_port

    if not options.user_host:
        host = '0.0.0.0'
    else:
        host = options.user_host

    httpserver.serve(app, host=host, port=port)


if __name__ == "__main__":
    main(sys.argv)
