#!/usr/bin/python -t
# Authors:
#     Matthew Harmsen <mharmsen@redhat.com>
#
# 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; version 2 of the License.
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2011 Red Hat, Inc.
# All rights reserved.
#

# System Imports
import sys
if not hasattr(sys, "hexversion") or sys.hexversion < 0x020700f0:
    print "Python version %s.%s.%s is too old." % sys.version_info[:3]
    print "Please upgrade to at least Python 2.7.0."
    sys.exit(1)
try:
    import argparse
    import logging
    import os
    import socket
    import struct
    import subprocess
    import time
    from time import strftime as date
    from pki.deployment import pkiconfig as config
    from pki.deployment.pkiparser import PKIConfigParser
    from pki.deployment import pkilogging
    from pki.deployment import pkimessages as log
except ImportError:
    print >> sys.stderr, """\
There was a problem importing one of the required Python modules. The
error was:

    %s
""" % sys.exc_value
    sys.exit(1)


# PKI Deployment Functions
def main(argv):
    "main entry point"

    config.pki_deployment_executable = os.path.basename(argv[0])

    # Only run this program as "root".
    if not os.geteuid() == 0:
        sys.exit("'%s' must be run as root!" % argv[0])

    # Set the umask
    os.umask(config.PKI_DEPLOYMENT_DEFAULT_UMASK)

    # Set installation time
    ticks = time.time()
    config.pki_install_time = time.asctime(time.localtime(ticks))

    # Generate a timestamp
    config.pki_timestamp = date('%Y%m%d%H%M%S', time.localtime(ticks))
    config.pki_certificate_timestamp =\
        date('%Y-%m-%d %H:%M:%S', time.localtime(ticks))

    # Obtain the architecture bit-size
    config.pki_architecture = struct.calcsize("P") * 8

    # Retrieve hostname
    config.pki_hostname = socket.getfqdn()

    # Retrieve DNS domainname
    config.pki_dns_domainname = None
    try:
        config.pki_dns_domainname = subprocess.check_output("dnsdomainname",
                                                            shell=True)
        config.pki_dns_domainname = config.pki_dns_domainname.rstrip('\n')
        if not len(config.pki_dns_domainname):
            print log.PKI_DNS_DOMAIN_NOT_SET
            sys.exit(1)
    except subprocess.CalledProcessError as exc:
        print log.PKI_SUBPROCESS_ERROR_1 % exc
        sys.exit(1)

    # Read and process command-line arguments.
    parser = PKIConfigParser(
        'PKI Instance Installation and Configuration',
        log.PKISPAWN_EPILOG)

    parser.mandatory.add_argument('-f',
        dest='user_deployment_cfg', action='store',
        nargs=1, required=True, metavar='<file>',
        help='configuration filename '
            '(MUST specify complete path)')

    parser.optional.add_argument('-u',
        dest='pki_update_flag', action='store_true',
        help='update instance of specified subsystem')

    args = parser.process_command_line_arguments(argv)

    config.default_deployment_cfg = config.PKI_DEPLOYMENT_DEFAULT_CONFIGURATION_FILE

    # -f <user deployment config>
    config.user_deployment_cfg = str(args.user_deployment_cfg).strip('[\']')

    # -u
    config.pki_update_flag = args.pki_update_flag

    parser.validate()

    if not os.path.exists(config.PKI_DEPLOYMENT_SOURCE_ROOT +\
                          "/" + config.pki_subsystem.lower()):
        print "ERROR:  " + log.PKI_SUBSYSTEM_NOT_INSTALLED_1 %\
            config.pki_subsystem.lower()
        sys.exit(1)

    # Enable 'pkispawn' logging.
    rv = 0
    if not config.pki_update_flag:
        config.pki_log_dir = config.pki_root_prefix +\
                             config.PKI_DEPLOYMENT_LOG_ROOT
        config.pki_log_name = "pki" + "-" +\
                              config.pki_subsystem.lower() +\
                              "-" + "spawn" + "." +\
                              config.pki_timestamp + "." + "log"
        rv = pkilogging.enable_pki_logger(config.pki_log_dir,
                                          config.pki_log_name,
                                          config.pki_log_level,
                                          config.pki_console_log_level,
                                          "pkispawn")
    else:
        config.pki_log_dir = config.pki_root_prefix +\
                             config.PKI_DEPLOYMENT_LOG_ROOT
        config.pki_log_name = "pki" + "-" +\
                              config.pki_subsystem.lower() +\
                              "-" + "respawn" + "." +\
                              config.pki_timestamp + "." + "log"
        rv = pkilogging.enable_pki_logger(config.pki_log_dir,
                                          config.pki_log_name,
                                          config.pki_log_level,
                                          config.pki_console_log_level,
                                          "pkirespawn")
    if rv != OSError:
        config.pki_log = rv
    else:
        print log.PKI_UNABLE_TO_CREATE_LOG_DIRECTORY_1 % config.pki_log_dir
        sys.exit(1)

    # Read the specified PKI configuration file.
    rv = parser.read_pki_configuration_file()
    if rv != 0:
        config.pki_log.error(log.PKI_UNABLE_TO_PARSE_1, rv,
                             extra=config.PKI_INDENTATION_LEVEL_0)
        sys.exit(1)

    # NEVER print out 'sensitive' name/value pairs!!!
    config.pki_log.debug(log.PKI_DICTIONARY_DEFAULT,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.format(config.pki_default_dict),
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(log.PKI_DICTIONARY_WEB_SERVER,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.format(config.pki_web_server_dict),
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(log.PKI_DICTIONARY_SUBSYSTEM,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.format(config.pki_subsystem_dict),
                         extra=config.PKI_INDENTATION_LEVEL_0)

    # Read in the PKI slots configuration file.
    parser.compose_pki_slots_dictionary()
    config.pki_log.debug(log.PKI_DICTIONARY_SLOTS,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.format(config.pki_slots_dict),
                         extra=config.PKI_INDENTATION_LEVEL_0)

    # Combine the various sectional dictionaries into a PKI master dictionary
    parser.compose_pki_master_dictionary()
    if not config.pki_update_flag:
        config.pki_master_dict['pki_spawn_log'] = config.pki_log_dir + "/" +\
                                                  config.pki_log_name
    else:
        config.pki_master_dict['pki_respawn_log'] = config.pki_log_dir + "/" +\
                                                    config.pki_log_name
    config.pki_log.debug(log.PKI_DICTIONARY_MASTER,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.format(config.pki_master_dict),
                         extra=config.PKI_INDENTATION_LEVEL_0)

    # Process the various "scriptlets" to create the specified PKI subsystem.
    pki_subsystem_scriptlets = config.pki_master_dict['spawn_scriplets'].split()
    rv = 0
    for pki_scriptlet in pki_subsystem_scriptlets:
        scriptlet = __import__("pki.deployment." +
                               pki_scriptlet,
                               fromlist = [pki_scriptlet])
        instance = scriptlet.PkiScriptlet()
        if not config.pki_update_flag:
            rv = instance.spawn()
        else:
            rv = instance.respawn()
        if rv != 0:
            sys.exit(1)
    config.pki_log.debug(log.PKI_DICTIONARY_MASTER,
                         extra=config.PKI_INDENTATION_LEVEL_0)
    config.pki_log.debug(pkilogging.format(config.pki_master_dict),
                         extra=config.PKI_INDENTATION_LEVEL_0)


# PKI Deployment Entry Point
if __name__ == "__main__":
    main(sys.argv)
