#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2000-2005  Bastian Kleineidam
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
"""WebCleaner - a filtering HTTP proxy"""

import sys
import os

import wc
# initialize i18n
#wc.init_i18n()

nt_usage = _("""USAGE\twebcleaner [options] <command> [command options]

OPTIONS
-h, --help
        Print this help.

-d <directory>, --configdir=<directory>
        Use given directory for configuration. It should include the
        webcleaner.conf, logging.conf and several .zap files.

--no-file-logs
        Do not add automatic .log files to the logging configuration.

COMMANDS
start [-f <config>]
        Start %(service)s service, with optional alternate configuration
        file.
stop
        Stop %(service)s service.
restart
        Restart %(service)s service.
status
        Print status info of %(appname)s service.
debug
        Start %(service)s service with debug messages.
install [options]
        Install %(service)s service.
update [options]
        Update %(service)s service.
remove
        Remove %(service)s service.

COMMAND OPTIONS (for 'install' and 'update' commands only)
--username <domain\username>
        The Username the service is to run under
--password password
        The password for the username
--startup [manual|auto|disabled]
        How the service starts, default = manual
--interactive
        Allow the service to interact with the desktop.
""")


usage = _("""USAGE\twebcleaner [options] [command]

The %(appname)s proxy is started as a foreground process.

OPTIONS
-h, --help
        Print this help.

-d <directory>, --configdir=<directory>
        Use given directory for configuration. It should include the
        webcleaner.conf, logging.conf and several .zap files.

--no-file-logs
        Log to stdout instead of *.log files.

COMMANDS
start
        Start %(appname)s.
restart
        Restart %(appname)s.
""")


def print_usage (msg):
    """print short usage info and exit"""
    print msg
    print _("execute 'webcleaner -h' for help\n")
    sys.exit(1)


def paginate (text, lines=22):
    """Print text in pages of lines size."""
    textlines = text.split("\n")
    curline = 1
    for line in textlines:
        print line
        curline = curline + 1
        if curline >= lines and sys.stdin.isatty():
            curline = 1
            print _("press return to continue...")
            sys.stdin.read(1)


def print_help ():
    """Print long usage info and exit."""
    d = {'service': service, 'appname': wc.AppName}
    if os.name=='nt':
        service = _("%(appname)s Proxy") % d
        paginate(nt_usage % d)
    else:
        print usage % d
    sys.exit(0)


def parse_options (sysargs):
    """read command line arguments

    @return: (configdir, args)
    """
    import getopt
    configdir = wc.ConfigDir
    filelogs = True
    try:
        # Note: cut out the name of the script in sys.argv
        options, args = getopt.getopt(sysargs, "hd:",
                                      ["help", "configdir=", "no-file-logs"])
    except getopt.error:
        print_usage(sys.exc_info()[1])
    for opt, arg in options:
        if opt=="-h" or opt=="--help":
            print_help()
        elif opt=="--configdir" or opt=="-d":
            configdir = arg
        elif opt=="--no-file-logs":
            filelogs = False
        else:
            print_usage(_("Unknown option %(option)r") % {'option': opt})
    return (configdir, filelogs, args)


def main_posix (configdir, filelogs, args):
    """Start (or restart) the webcleaner proxy."""
    if len(args) < 1:
        command = "start"
    else:
        command = args[0]
    import wc.start
    if command == "start":
        wc.start.wstartfunc(confdir=configdir, filelogs=filelogs)
    elif command == "restart":
        wc.start.restart()
    else:
        print_usage(_("Unknown command %r") % command)


def main_nt (configdir, filelogs, args):
    """Control webcleaner proxy NT service."""
    if len(args) < 1:
        print_usage(_("No command given."))
    else:
        command = args[0]
    import wc.win32start
    wc.win32start.ProxyService.filelogs = filelogs
    if configdir:
        wc.win32start.ProxyService.configdir = configdir
    if command=='status':
        print wc.win32start.status()
    elif command in ['start', 'stop', 'restart', 'install', 'remove']:
        import win32serviceutil
        win32serviceutil.HandleCommandLine(wc.win32start.ProxyService)
    else:
        print_usage(_("Unknown command %r") % command)


def main (sysargs):
    """Start webcleaner with given command line arguments which
       are usually sys.argv[1:].
    """
    configdir, filelogs, args = parse_options(sysargs)
    if os.name=='nt':
        return main_nt(configdir, filelogs, args)
    return main_posix(configdir, filelogs, args)


if __name__ == '__main__':
    main(sys.argv[1:])
