#!/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.
"""SSL certificates generation/installation/removal script"""

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
import getopt
import wc
# initialize i18n
wc.init_i18n()
import wc.proxy.ssl


usage = _("""Usage: webcleaner-certificates [options] <command>
Options:
-d <directory>, --configdir=<directory>
        Generate certificates in given directory instead of the
        default one for %(app)s.
        This should be the same directory as given in "%(name)s -d"

Commands:
install - generate and install %(app)s SSL certificates if not already there
remove  - remove %(app)s SSL certificates
""") % {'app': wc.AppName, 'name': wc.Name}


def print_usage (msg):
    """print short usage info and exit"""
    print msg
    print usage
    sys.exit(1)


def install_ssl_certs (configdir):
    """create SSL certificates if not already done"""
    if wc.proxy.ssl.exist_certificates(configdir):
        print _("%s SSL certificates already exist, doing nothing")%\
          wc.AppName
    else:
        wc.proxy.ssl.create_certificates(configdir)


def remove_ssl_certs (configdir):
    for f in ['client', 'server', 'CA']:
        for ext in ['pkey', 'cert']:
            fname = os.path.join(configdir, "%s.%s" % (f, ext))
            if os.path.exists(fname):
                try:
                    os.remove(fname)
                except IOError, msg:
                    print _("Could not remove %r: %s") % \
                          (fname, str(msg))


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

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


def main (sysargs):
    configdir, args = parse_options(sysargs)
    if len(args) < 1:
        print_usage(_("No command given."))
    else:
        command = args[0]
    if command=='install':
        install_ssl_certs(configdir)
    elif command=='remove':
        remove_ssl_certs(configdir)
    else:
        print_usage(_("Invalid command %r.")%command)


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