#!/usr/bin/python

# RHEV Manager post upgrade scripts
# Imported by rhevm-upgrade to perform configurations restore

import logging
import shutil
import os
import pwd
import common_utils as utils
import basedefs
import basedefs30

# MSGS
MSG_PKI_CERTS_RESTORED = "PKI certificates were successfully restored from previous setup"
MSG_PKI_CERTS_OWNER_RESTORED = "The ownership of the pki files was restored"
MSG_KEYS_RENAMED = "Keys from previous setup were successfully renamed"

# CONST
WEB_CONF_JS = "/etc/rhevm-old/web-conf.js"

def updateKeyAlias():

    # Rename key alias from rhevm to engine

    cmd = [
        "keytool",
        "-changealias",
        "-storepass", "mypass",
        "-alias", "rhevm",
        "-destalias", "engine",
        "-keystore", os.path.join(basedefs.DIR_OVIRT_PKI, ".keystore"),
    ]

    utils.execCmd(cmdList=cmd)

def restoreKrb():
    TEMP_KRB = "/var/krb5.conf"
    if os.path.exists(TEMP_KRB):
        logging.debug("Temporary krb5.conf file detected. Restoring.")
        shutil.copy(TEMP_KRB, "/etc/ovirt-engine")

def restoreKeysCerts():
    # Restore pki certificates and correct their ownership.
    OLD_PKI_DIR = basedefs30.DIR_RHEVM_PKI + "-old/"
    pkiFolders = ["certs", "keys", "private", "requests"]
    pkiFiles = [".keystore", ".truststore", ".rnd", "serial.txt", "ca.pem"]
    for folder in pkiFolders:
        item = os.path.join(basedefs.DIR_OVIRT_PKI, folder)
        if os.path.exists(item):
            shutil.rmtree(item, item + ".new")
            logging.debug("Copy %s to %s", OLD_PKI_DIR + folder, item)
            shutil.copytree(OLD_PKI_DIR + folder, item)
            utils.chownToEngine(item)

    for item in pkiFiles:
        pkifile = os.path.join(basedefs.DIR_OVIRT_PKI, item)
        logging.debug("Copy %s to %s", OLD_PKI_DIR + item, pkifile)
        utils.copyFile(OLD_PKI_DIR + item, pkifile)
        utils.chownToEngine(pkifile)

    logging.debug(MSG_PKI_CERTS_RESTORED)

    # Update ownership of all files from jboss to ovirt
    # Find all files that owned by jboss in the pki folder and change the
    # owner of the file from jboss to engine/ovirt.
    for f in os.walk(basedefs.DIR_OVIRT_PKI):
        if len(f[2]) > 0:
            for nf in f[2]:
                pkifile = os.path.join(f[0], nf)
                oldpkifile = pkifile.replace("ovirt-engine", "rhevm-old")
                if os.path.exists(oldpkifile):
                    owner = pwd.getpwuid(os.stat(oldpkifile).st_uid).pw_name
                    if "jboss" in owner:
                        utils.chownToEngine(pkifile)

    logging.debug(MSG_PKI_CERTS_OWNER_RESTORED)

    # rename all keys to 'engine'
    keyFiles = [
        "/requests/rhevm.req",
        "/keys/rhevm_id_rsa",
        "/keys/rhevm.ssh.key.txt",
        "/certs/rhevm.cer",
        "/certs/rhevm.der",
        ]
    for keyfile in keyFiles:
        keyfile = basedefs.DIR_OVIRT_PKI + keyfile
        newkey = keyfile.replace('rhevm', 'engine')
        logging.debug("Rename %s to %s", keyfile, newkey)
        os.rename(keyfile, newkey)

    logging.debug(MSG_KEYS_RENAMED)

def configureEngine():
    '''
    Configure ovirt-engine post upgrade
    '''
    # Get DB Pass
    dbPassword = utils.getDbPassword(basedefs.DB_USER)

    # Set DB Url
    dbUrl = "jdbc:postgresql://" + utils.getDbHostName() + ":" + utils.getDbPort() + "/" + basedefs.DB_NAME

    # Get current configuration
    fqdn, httpPort, httpsPort = utils.getHostParams(WEB_CONF_JS)

    # Get encrypted password
    masked_value_set = [dbPassword]
    encryptedPassword = utils.encryptEngineDBPass(password=dbPassword,
                                                  maskList=masked_value_set)

    # Edit sysconfig file
    utils.editEngineSysconfig(proxyEnabled=False,
                              dbUrl=dbUrl,
                              dbUser=utils.getDbUser(),
                              fqdn=fqdn,
                              http=httpPort,
                              https=httpsPort,
                              javaHome=utils.findJavaHome(),
                             )

    # Set encrypted password
    utils.configEncryptedPass(encryptedPassword)

    logging.debug("JBoss configuration was successfully restored")

def restoreNotifierConfiguration():
    """
    restoreNotifierConfiguration restores settings for notifier from 3.0
    """

    # First, move the new configuration aside, and copy the old one to the
    # new location.
    old_config = "/etc/rhevm-old/notifier/notifier.conf"
    new_config = "/etc/ovirt-engine/notifier/notifier.conf"
    if os.path.exists(old_config):
        if os.path.exists(new_config):
            shutil.move(new_config, new_config + ".orig")
        shutil.copy(old_config, new_config)
        utils.chownToEngine(new_config)

        # Now, update the new values in the old config
        config = utils.TextConfigFileHandler(new_config)
        config.open()

        # Comment out the obsolete values
        config.delParams(["AS_DATA_SOURCE", "AS_LOGIN_CONFIG"])

        # Rename the rhevmLib to engineLib
        config.renameParam("rhevmLib", "engineLib")
        # Update the value of the engineLib
        config.editParam("engineLib",
                        os.path.join(basedefs.DIR_ENGINE_EAR, "lib"))
        config.close()

def configureToolsConfFile():
    """
    add the user & host:secrue_port values to logcollector.conf, isouploader.conf, imageuploader.conf
    """
    # Get current configuration
    fqdn, httpPort, httpsPort = utils.getHostParams(WEB_CONF_JS)

    for confFile in (basedefs.IMAGE_UPLOADER_CONF, basedefs.ISO_UPLOADER_CONF, basedefs.LOG_COLLECTOR_CONF):
        if os.path.isfile(confFile):
            logging.debug("Editing %s" % confFile)
            fileHandler = utils.TextConfigFileHandler(confFile)
            fileHandler.open()

            logging.debug("Adding host & secure port")
            fileHandler.editParam("rhevm", "%s:%s" % (fqdn, httpsPort))

            logging.debug("Adding username")
            fileHandler.editParam("user", "%s@%s" % (basedefs.INTERNAL_ADMIN, basedefs.INTERNAL_DOMAIN))

            fileHandler.close()
        else:
            logging.debug("Could not find %s" % confFile)


def run():
    # Configure ovirt-engine service
    configureEngine()

    # Restore pki certificates and correct their ownership.
    restoreKeysCerts()

    # Update key alias
    updateKeyAlias()

    # Restore krb5 conf
    restoreKrb()

    # Restore notifier configuration
    restoreNotifierConfiguration()

    # Configure tools
    configureToolsConfFile()
