#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2000-2004  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"""

__version__ = "$Revision: 1.56 $"[11:-2]
__date__    = "$Date: 2004/05/31 18:34:02 $"[7:-2]
# $Source: /cvsroot/webcleaner/webcleaner2/webcleaner,v $

import sys
if not hasattr(sys, "version_info"):
    raise SystemExit, "This program requires Python 2.3.1 or later."
if sys.version_info < (2, 3, 1, 'final', 0):
    raise SystemExit, "This program requires Python 2.3.1 or later."
import os
# since webcleaner is single-threaded, increase the check interval
sys.setcheckinterval(1000)
import wc

nt_usage = wc.i18n._("""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 = wc.i18n._("""USAGE\twebcleaner [options]

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
        Do not add automatic .log files to the logging configuration.
""")


def print_usage (msg):
    """print short usage info and exit"""
    print msg
    print wc.i18n._("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 wc.i18n._("press return to continue...")
            sys.stdin.read(1)


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


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

    @return: (configdir, args)
    """
    import getopt
    configdir = wc.ConfigDir
    file_logs = 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":
            file_logs = False
        else:
            print_usage(wc.i18n._("Unknown option %(option)r")%{'option': opt})
    return (configdir, file_logs, args)


def main_posix (configdir, file_logs):
    """start the proxy"""
    wc.wstartfunc(confdir=configdir, file_logs=file_logs)


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


def main (sysargs):
    configdir, file_logs, args = parse_options(sysargs)
    if os.name=='nt':
        return main_nt(configdir, args)
    return main_posix(configdir, file_logs)


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