#!/usr/bin/python
# Security Hardening upgrade script
import logging
import os
import re
import time
import sys
import syslog
import isi.hardening.util as util
import errno
from isi.app.lib import safelockfile

import isi.config as iconf
from isi.app.lib import safelockfile
import isi.sys.version as sysver

IFS_BACKUP_PATH = "/ifs/.ifsvar/tmp"
LOG_FILE = os.path.join(IFS_BACKUP_PATH, "hardening-upgrade.log")
HARD_UPGRADE_FILE = os.path.join(IFS_BACKUP_PATH, "hardening-upgraded")
MAX_RETRIES = 10
logger = logging.getLogger("hardening_upgrade")
HTTPD_CONF= "/usr/local/apache2/conf/httpd.conf"

def update_httpd_config():
    conf_fname = HTTPD_CONF

    conf_file = open(conf_fname)
    conf = conf_file.readlines()
    conf_file.close()

    lockfile = safelockfile('/tmp/apache2.py.lock', 'w')
    config = open(conf_fname + '.isi', "w")

    token_re = re.compile(r'^Listen\s+.*')
    found = False
    for line in conf:
        line = line.rstrip()
        tokens = token_re.findall(line)
        if tokens:
            if found == True:
                print "SKIP: " + line
                continue
            print "Found : " +line
            line = "Listen 80";
            found = True
        config.write('%s\n' % line)

    config.flush()
    os.fsync(config.fileno())
    config.close()

    os.chmod(conf_fname + '.isi', 0640)
    os.rename(conf_fname + '.isi', conf_fname)
    lockfile.close()

def main():
    NodeID = "Node %d" % iconf.getNode()['node id']

    need_upgrade = False
    if os.path.isfile("/ifs/.ifsvar/cluster_hardened"):
        need_upgrade = True

    if need_upgrade:
        clusterwide_command = False
        if not os.path.isfile("/etc/ifs/isi_hardening_upgrade_already_ran"):
            open("/etc/ifs/isi_hardening_upgrade_already_ran", 'a').close()
            logger.info("%s: Created /etc/ifs/isi_hardening_upgrade_already_ran" %NodeID)
        else:
            return 0

        try:
            update_httpd_config()
        except Exception, e:
            syslog.syslog(syslog.LOG_ERR,
                          "Error during updating the"
                          " httpd config file"
                          " %s:%s" % (HTTPD_CONF,str(e)))
            return 1

        retry = MAX_RETRIES
        while retry:
            try:
                logger.setLevel(logging.DEBUG)
                fh = logging.FileHandler(LOG_FILE, 'a')
                fh.setLevel(logging.DEBUG)
                logger.addHandler(fh)
                break
            except EnvironmentError, e:
                syslog.syslog(syslog.LOG_NOTICE,
                              "Error during logging "
                              "in hardening-upgrade script, %s %d" % (e, (MAX_RETRIES - retry + 1)))
                if retry == 1:
                    syslog.syslog(syslog.LOG_NOTICE, "Error: Exiting from hardening-upgrade script")
                time.sleep(5)
                retry = retry - 1

        try:
            os.chmod(LOG_FILE, 0640)
        except OSError, e:
            # log chmod errors and continue
            syslog.syslog(syslog.LOG_NOTICE,
                          "Error chmod'ing %s (errno: %d)" \
                          % (LOG_FILE, e.errno))

        # We need to block all other nodes from continuing until
        # we've finished the upgrade
        try:
            sentry = safelockfile(HARD_UPGRADE_FILE, 'w')
        except EnvironmentError, e:
            logger.error("%s: %s: Error during locking in hardening-upgrade" \
                         " script, %s" % (NodeID, time.ctime(), e))
            return 1

        logger.info("%s: Calling Hardening Engine Components now..." %NodeID)
        try:
        #If HARDENING_ENGINE_UPGRADE_FILE is not present then
        # 1) Create HARDENING_ENGINE_UPGRADE_FILE
        # 2) Call run_clusterwide_command().
        # So only one node in cluster will execute this function
            if not os.path.isfile(util.HARDENING_ENGINE_UPGRADE_FILE):

                logger.info("%s: %s: %s is not present" %
                    (NodeID, time.ctime(), util.HARDENING_ENGINE_UPGRADE_FILE ))

                util.execute_command("rm -rf /ifs/.ifsvar/CHE");

                if not os.path.exists(util.CHE_BASE_PATH):
                    os.mkdir(util.CHE_BASE_PATH)
                    logger.info("%s: %s: %s is created" %
                        (NodeID, time.ctime(), util.CHE_BASE_PATH ))
                if not os.path.isdir(util.CHE_CLI_DIR):
                    try:
                        os.makedirs(util.CHE_CLI_DIR)
                        os.chmod(util.CHE_CLI_DIR, 0777)
                    except OSError, excpt:
                        print str(excpt)
                        return 1

                open(util.HARDENING_ENGINE_UPGRADE_FILE, 'a').close()

                logger.info("%s: %s: %s is created" %
                    (NodeID, time.ctime(), util.HARDENING_ENGINE_UPGRADE_FILE ))
                clusterwide_command = True
                CHE_ces_cmd = "python " + util.CHE_BIN_PATH \
                    + "/check_expected_state.py -n " \
                    + util.H_UPGRADE_CONFIG_PATH + " -u " + " -o upgrade" + " >> /dev/null 2>&1 "
                CHE_apply_cmd = "python " + util.CHE_BIN_PATH + "/apply.py -n " \
                    + util.H_UPGRADE_CONFIG_PATH + " -u " + " >> /dev/null 2>&1 "
            else:
                CHE_ces_cmd = "python " + util.CHE_BIN_PATH + "/check_expected_state.py -n " \
                    + util.H_UPGRADE_CONFIG_PATH + " -o upgrade" + " >> /dev/null 2>&1 "
                CHE_apply_cmd = "python " + util.CHE_BIN_PATH + "/apply.py -n " \
                    + util.H_UPGRADE_CONFIG_PATH + " >> /dev/null 2>&1 "

            sentry.close()
            success = True
            try:
                if os.path.isfile("/var/log/boxend.log"):
                    os.chmod("/var/log/boxend.log", 0640)
                logger.info("%s: %s: Calling Check Expected State" %
                    (NodeID, time.ctime()))
                logger.info("%s: %s: Running check expected command: %s" %
                    (NodeID, time.ctime(), CHE_ces_cmd))
                CHE_ces_ret = util.execute_command(CHE_ces_cmd)
                if CHE_ces_ret == 0:
                    logger.info("%s: %s: Check Expected State completed successfully" %
                        (NodeID, time.ctime()))
                    success = True
                else:
                    logger.error("%s: %s: Check Expected State failed" %
                        (NodeID, time.ctime()))
                    success = False
            except Exception, e:
                success = False
                logger.error("%s: %s: Error during Check Expected State run %s (errno: %d)" %
                             NodeID, (time.ctime(), LOG_FILE, e.errno))

            # If Check Expected State succeeded with no conflicts
            # Proceed to apply

            if success:
                try:
                    if not os.path.isfile(util.NODE_INFO_PATH):
                        open(util.NODE_INFO_PATH, 'a').close()
                    logger.info("%s: %s: Calling CHE Apply" %
                        (NodeID, time.ctime()))
                    logger.info("%s: %s: Running Hardening Engine Apply command: %s" %
                        (NodeID, time.ctime(), CHE_apply_cmd))
                    CHE_apply_ret = util.execute_command(CHE_apply_cmd)
                    if CHE_apply_ret != 0:
                        logger.error("%s: %s: Error during Hardening Engine Apply run" %
                        (NodeID, time.ctime()))
                        success = False
                    else:
                        logger.info("%s: %s: Hardening Engine Apply completed successfully" %
                        (NodeID, time.ctime()))
                        success = True
                except Exception, e:
                    success = False
                    logger.error("%s: %s: Error during Hardening Engine Apply %s (errno: %d)" %
                                 (NodeID, time.ctime(), LOG_FILE, e.errno))

            # isi auth command fails due to some issue at bootime
            if success and clusterwide_command:
                util.execute_command("/usr/libdata/patchmgr/bg-hardening-upgrade &")

        except Exception, e:
            success = False
            logger.error("%s: %s: Error during Hardening Upgrade %s (errno: %d)" %
                         (NodeID, time.ctime(), LOG_FILE, e.errno))
            sentry.close()
        if success:
            logger.info("%s: %s: Hardening Upgrade completed successfully" %
                         (NodeID, time.ctime()))
            return 0
        else:
            logger.error("%s: %s: Hardening Upgrade failed" %
                         (NodeID, time.ctime()))
            return 1
    else:
        logger.info("%s: No Hardening upgrade needed." %NodeID)
        return 0

if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception, e:
        syslog.syslog(syslog.LOG_ERR,
                      "Error running hardening-upgrade script, %s" % e)



