#!/usr/bin/python

# RHEV Manager post upgrade scripts
# Imported dynamically from rhevm-upgrade

import logging
import os
import sys
import common_utils as utils
import jasper30_utils as jsutils30
import basedefs
import output_messages

def updateVdcPkiOptions():

    options = (
        {
            "keystoreUrl":["/etc/pki/ovirt-engine/.keystore", 'text'],
            "CertificateFileName":["/etc/pki/ovirt-engine/certs/engine.cer", 'text'],
            "CAEngineKey":["/etc/pki/ovirt-engine/private/ca.pem", 'text'],
            "TruststoreUrl":["/etc/pki/ovirt-engine/.keystore", 'text'],
            "ENGINEEARLib":["%s/engine.ear" %(basedefs.DIR_ENGINE), 'text'],
            "CACertificatePath":["/etc/pki/ovirt-engine/ca.pem", 'text'],
            "CertAlias":["engine", 'text'],
        },
        {
            "TruststorePass":[basedefs.CONST_CA_PASS, 'text'],
            "keystorePass":[basedefs.CONST_CA_PASS, 'text'],
            "SSLEnabled":[ "true", 'text'],
            "ScriptsPath":["/usr/share/ovirt-engine", 'text'],
            "SysPrepXPPath":["/etc/ovirt-engine/sysprep/sysprep.xp", 'text'],
            "SysPrep2K3Path":["/etc/ovirt-engine/sysprep/sysprep.2k3", 'text'],
            "SysPrep2K8Path":["/etc/ovirt-engine/sysprep/sysprep.2k8x86", 'text'],
            "SysPrep2K8x64Path":["/etc/ovirt-engine/sysprep/sysprep.2k8", 'text'],
            "SysPrep2K8R2Path":["/etc/ovirt-engine/sysprep/sysprep.2k8", 'text'],
            "SysPrepWindows7Path":["/etc/ovirt-engine/sysprep/sysprep.w7", 'text'],
            "SysPrepWindows7x64Path":["/etc/ovirt-engine/sysprep/sysprep.w7x64", 'text'],
            "ConfigDir":["/etc/ovirt-engine", 'text'],
            "DataDir":["/usr/share/ovirt-engine", 'text'],
        }
    )

    try:
        if os.path.exists(basedefs.FILE_ENGINE_CONFIG_BIN):
            if os.path.exists(basedefs.FILE_ENGINE_EXTENDED_CONF):
                #1st iterate on the CA related options
                for subDict in options:
                    for key in subDict:
                        value, keyType = subDict[key]
                        utils.updateVDCOption(key, value, [basedefs.CONST_CA_PASS], keyType)

                logging.debug("finished updating vdc options")
            else:
                raise Exception(output_messages.ERR_CANT_FIND_VDC_OPTION_FILE%(basedefs.FILE_ENGINE_EXTENDED_CONF))
        else:
            raise Exception(output_messages.ERR_CANT_FIND_RHEVM_CONFIG_FILE%(basedefs.FILE_ENGINE_CONFIG_BIN))

    except:
        raise Exception(output_messages.ERR_FAILED_UPD_VDC_OPTIONS%(sys.exc_info()[1]))

def startEngine():
    logging.debug("using chkconfig to enable engine service to load on system startup.")
    srv = utils.Service(basedefs.ENGINE_SERVICE_NAME)
    srv.autoStart(True)

def run():

    # Update pki locations in VDC options
    updateVdcPkiOptions()

    # Start ovirt-engine on reboot
    startEngine()

    # Raise an upgrade flag for reports
    jsutils30.setUpgraded()
