#!/usr/bin/python

# vim:expandtab ts=4
# in order to use the embedded vim commands "set modeline" is required in your .vimrc file

import commands
import os
import sys
import time
import glob
from phionlibs import CStdConfig
import re
from distutils.version import LooseVersion
import pickle
import shutil

from xml.dom.minidom import parse

try:
    import CudaHaHandover
except:
    CudaHaHandover = None

# hotfixrpms is local module that allows us to define particualr props for
# this particular 'type' (update, patch, etc...) of install.
import hotfixrpms

CTRLCONF='/opt/phion/config/active/control.conf'
CTRLCONFTMP='/opt/phion/config/active/control.conf.tmp'
CTRLCONFSAVE='/opt/phion/config/active/control.conf.updatesave'
STATE_FILE_WATCHDOG='/var/run/watchdog.state.service'

class Config:
    def __init__(self):
        # default values
        self.m_rebootDelay = 10
        self.m_forceReboot = False

        # -- get appliance model -----------------------------------------------
        applName = ""
        self.m_virtSubMethod = ""
        if (os.path.exists('/opt/phion/run/appliance.state')):
            conf = CStdConfig()
            conf.LoadPath('/opt/phion/run', 'appliance.state')
            applName = conf.Get('/', 'model')
            self.m_virtSubMethod = conf.Get('/', 'virtsubmethod')

        if (applName == ""):
            (_status, _output) = commands.getstatusoutput('/opt/phion/bin/hwtool -m')
            applName = _output.strip()

        if (self.m_virtSubMethod == ""):
            (_status, _output) = commands.getstatusoutput('/opt/phion/bin/hwtool -y')
            self.m_virtSubMethod = _output.strip()

        # -- set delay ---------------------------------------------------------
        if re.match(r"^F1((0[01]{,1}[a-z]{,1})|5)$", applName) or re.match(r"^NF-EDGE*", applName):
            self.m_rebootDelay = 20

    def getRebootDelay(self):
        return self.m_rebootDelay

    def getForceReboot(self):
        return self.m_forceReboot

    def setForceReboot(self, value):
        self.m_forceReboot = value

    def hasDynamicMIP(self):
        if self.m_virtSubMethod == "Azure" or self.m_virtSubMethod == "EC2":
            return True
        return False

def parseArgs():
    from optparse import OptionParser

    parser = OptionParser("""\
    %prog [options]

    Process the hotfix installation on the system.
    """);

    parser.set_defaults(mode="")

    # options from hotfixrpms
    # set them before the parser options in order to allow overrides from command line options!
    defaultIgnoreBoot=False
    defaultMustReboot=False
    if hasattr(hotfixrpms, 'bootpolicy'):
        if hotfixrpms.bootpolicy=='no':
            defaultIgnoreBoot=True
        elif hotfixrpms.bootpolicy=='force':
            defaultMustReboot=True

    parser.add_option('-f', '--force', action='store_const', dest='mode', const="--force ",
            help='This option enforces the package installation. Usage of this option is highly discouraged! This may damage your system!')
    parser.add_option('-I', '--ignorerelease', action='store_true', dest='ignorerelease', default=False,
            help='This option skips the install version range check. Do not use this option, unless you know exactly, what you are doing!')
    parser.add_option('-B', '--ignorebuildno', action='store_true', dest='ignorebuildno', default=False,
            help='This option skips the base release check for delta patches. Do not use this option, unless you know exactly, what you are doing!')
    parser.add_option('-b', '--noreboot', action='store_true', dest='ignorereboot', default=defaultIgnoreBoot,
            help='Do not reboot automatically, if required. This option has precedence to -m!')
    parser.add_option('-m', '--mustboot', action='store_true', dest='mustreboot', default=defaultMustReboot,
            help='Do reboot after successful package installation even it might not be required. This option will be ignored in case of -b!')
    parser.add_option('-t', '--test', action='store_true', dest='test', default=False,
            help='Do just a dry run of the installation.')

    (options, args) = parser.parse_args()

    if options.test:
        options.mode = '%s%s' % (options.mode, '--test ')

    return (options, args)


#---------------------------------------------------------------------------
def main():
#---------------------------------------------------------------------------

    # get the options
    (options, args)=parseArgs()

    cfg = Config()

    # Get sys info.
    system = InstalledSystem()

    # Perform a quick check that the hotfix is suitable for current patch level.
    if not options.ignorerelease and not system.ismcbox and system.version not in hotfixrpms.patchreleases:
        print "ERROR: The package can only be installed systems patched to: %s" % hotfixrpms.patchreleases
        print "ERROR: Your currently installed system is %s" % system.version
        sys.exit(1)

    if not options.ignorerelease and system.ismcbox and len(filter(lambda x:LooseVersion(system.version)>=LooseVersion(x), hotfixrpms.patchreleases))==0:
        print "ERROR: This package can only be installed on a control center of version(s) %s or higher" % hotfixrpms.patchreleases
        print "ERROR: Your currently installed system is %s" % system.version
        sys.exit(1)

    if not options.ignorebuildno and hasattr(hotfixrpms, 'base_version_critical') and hotfixrpms.base_version_critical == True and hasattr(hotfixrpms, 'base_version') and hotfixrpms.base_version != 'GWAY-%s-%s' % (system.version, system.release):
        print("ERROR: System has %s baseversion; This patch/update can only be installed on base system version : %s (base version is critical)" % (system.version,hotfixrpms.base_version))
        sys.exit(1)

    # Get info about hotfix we are about to install.
    hotfix = PhionHotfix(system)

    # Check at this point if the hotfix contains anything to install.
    if not hotfix.rpmlist:
        if system.ismcbox:
            print 'ERROR: This package does not contain any installable control center components. Your CC release is %s. The package releases are %s.' % (system.version, hotfixrpms.patchreleases)
        else:
            print 'ERROR: This package does not contain any components for this release (%s). Please verify the package and box releases' % (system.version)
        print 'No rpms to install'
        sys.exit(-1)

    preDoitRpms = []
    # Get rpms that might contain pre doit scripts
    preDoitRpmPrefixes = ["phionnet_hotfix_"]
    rpmlist = hotfix.rpmlist.split(" ")
    for rpm in rpmlist:
        for prefix in preDoitRpmPrefixes:
            if rpm.startswith(prefix):
                preDoitRpms.append(rpm)
    if len(preDoitRpms) > 0:
        containsPreDoit = []
        # Get RPMs that contain pre doit scripts
        for rpm in preDoitRpms:
            if containsPreInstallationScripts(rpm):
                containsPreDoit.append(rpm)

        if len(containsPreDoit) > 0:
            # Extract packages in temporary directory
            dirname = "predoit." + str(os.getpid())
            runpath = "/run/" + dirname
            os.mkdir(runpath)
            # Unpack rpms to runpath
            for rpm in containsPreDoit:
                _, absolutepath = commands.getstatusoutput("readlink -f %s" % rpm)
                commands.getstatusoutput("cd %s && rpm2cpio %s | cpio -idv" % (runpath, absolutepath))
            # Execute pre doit scripts
            preDoitSuccess = system.processPreCommands(runpath)
            # Clean up
            shutil.rmtree(runpath)
            if not preDoitSuccess:
                print("ERROR: Execution of pre installation scripts failed.")
                sys.exit(1)

    # from here on, it may take longer, than IDLE... timeout settings in control.conf allow.
    # disable those timeouts during the update
    hotfix.disable_ctrl_timeouts()

    # reassemble rpms if applicable
    hotfix.reassembleDeltaRPMS()

    # Save server state if requested
    boxconf = CStdConfig()
    boxconf.LoadPath('/opt/phion/config/active', 'box.conf')
    save_server_state = boxconf.Get('/', 'ha_update_auto_failover')
    override_no_ha_handover = os.path.exists('/var/phion/preserve/override_no_ha_handover')
    handover = None
    if (CudaHaHandover != None) and (save_server_state == 'y'):
        if not os.path.exists('/var/phion/preserve/update_active_servers'):
            print 'Saving server state'
            handover = CudaHaHandover.ServerHandover()
            active_server_list = handover.getServerStatusList()

            f = open('/var/phion/preserve/update_active_servers', 'wb')
            pickle.dump(active_server_list, f)
            f.close()

            if not os.path.exists('/opt/phion/hooks/control'):
                os.mkdir('/opt/phion/hooks/control')

            f = open('/opt/phion/hooks/control/update.py', 'w')
            f.write('''#!/usr/bin/python

import os
import pickle

try:
    import CudaHaHandover
except:
    CudaHaHandover = None

if os.path.exists('/var/phion/preserve/update_active_servers') and not os.path.exists('/var/phion/preserve/override_no_ha_handover'):
    f = open('/var/phion/preserve/update_active_servers', 'rb')
    active_server_list = pickle.load(f)
    f.close()

    if CudaHaHandover != None:
        handover = CudaHaHandover.ServerHandover()
        handover.fromRemoteToLocal(active_server_list)

    os.remove('/var/phion/preserve/update_active_servers')

os.remove('/opt/phion/hooks/control/update.py')
''')
            f.close()

            os.chmod('/opt/phion/hooks/control/update.py', 0755)

            # Stop active servers
            print 'Stopping active servers'
            handover.fromLocalToRemote(active_server_list)
        else:
            handover = CudaHaHandover.ServerHandover()
            try:
                f = open('/var/phion/preserve/update_active_servers', 'rb')
                active_server_list = pickle.load(f)
                f.close()
            except IOError:
                pass
    # Stop various modules that may be installed by this hotfix.
    if not options.test:
        system.stopmodules(cfg)

    # Stop certain phion processes
    os.system('killall phionRelCheck')
    os.system('killall rpmv')

    # Actually update the required rpms
    print 'updating rpms: rpm -Uvh --replacepkgs --replacefiles %s%s' % (options.mode, hotfix.rpmlist)
    update_rpm_result,output = commands.getstatusoutput('rpm -Uvh --replacepkgs --replacefiles --ignorearch %s%s' % (options.mode, hotfix.rpmlist))

    # update is almost finshed. restore control conf
    hotfix.restore_ctrl_timeouts()

    # -- set reboot delay
    rdelay = cfg.getRebootDelay()

    # if restart is required, do the restart before re-loading all modules
    if not update_rpm_result:
        if system.modules_unloaded.has_key('acpf') and not system.modules_unloaded.get('acpf'):
            print 'WARNING: package installation succeeded, but acpf kernel module could not be unloaded. Will reboot box!'
            system.processPostCommands()
            delayed_reboot(rdelay, options.ignorereboot)
            sys.exit(0)
    
    # prelink stuff
    system.processPostCommands()

    # load unloaded modules
    if commands.getstatusoutput('rpm -q --qf "%{version}-%{release}.%{arch}" kernel')[1] != commands.getstatusoutput('uname -r')[1]:
        print 'WARNING: package installation succeeded, and newer kernel has been installed. Will reboot box!'
        delayed_reboot(rdelay, options.ignorereboot)
        sys.exit(0)

    if not options.test:
        system.startmodules()

    # Start previously active servers
    if (handover != None) and (save_server_state == 'y') and not override_no_ha_handover:
        print 'Starting previously active servers'
        handover.fromRemoteToLocal(active_server_list)

    if update_rpm_result:
        print 'ERROR: installation failed:'
        print '-' * 50
        print output
        print '-' * 50
        sys.exit(1)

    if system.modules_loaded.has_key('acpf') and not system.modules_loaded.get('acpf'):
        print 'WARNING: package installation succeeded, but acpf kernel module could not be reloaded. Will reboot box!'
        delayed_reboot(rdelay, options.ignorereboot);
        sys.exit(0)

    if system.modules_unloaded.has_key('ktina') and not system.modules_unloaded.get('ktina'):
        print 'WARNING: package installation succeeded, but ktina kernel module could not be unloaded'
        sys.exit(0)

    if cfg.getForceReboot() == True or options.mustreboot:
        print 'Package installed successfully, will reboot now'
        delayed_reboot(rdelay, options.ignorereboot)
        sys.exit(0)

    # Remove server state file
    if not override_no_ha_handover:
        try:
            os.remove('/var/phion/preserve/update_active_servers')
            os.remove('/opt/phion/hooks/control/update.py')
        except:
            pass

    print 'Package installed successfully'
    sys.exit(0)


#---------------------------------------------------------------------------
def delayed_reboot(sec, noreboot):
#---------------------------------------------------------------------------
    if noreboot:
        print 'Reboot prevented by command line option. Will not boot'
        return

    # write a marker file (reboot.peding) to avoid to call reboot more than once
    # which might be the case if e.g. a soft migration script also calls triggers reboot
    # place this file to /opt/phion/run which gets emptied during startup
    if os.path.exists('/opt/phion/run/reboot.pending'):
        print 'Reboot already triggered'
        return
    open('/opt/phion/run/reboot.pending', 'a').close()

    pid=os.fork()
    if not pid:
        os.close(0)
        os.close(1)
        os.close(2)
        if (os.path.isfile('/usr/bin/reboot')):
            os.system('sleep %d && /usr/bin/reboot &' % sec)
        elif (os.path.isfile('/usr/sbin/reboot')):
            os.system('sleep %d && /usr/sbin/reboot &' % sec)
        sys.exit(0)

#---------------------------------------------------------------------------
def isPreInstallationScript(file):
#---------------------------------------------------------------------------
    fileSplit = file.split("/")[-1].split("_")
    # Check if second string is "pre" (e.g. box_pre_name.sh)
    if len(fileSplit) > 2 and fileSplit[1] == "pre":
        return True
    return False

#---------------------------------------------------------------------------
def containsPreInstallationScripts(rpm):
#---------------------------------------------------------------------------
    _, files = commands.getstatusoutput('rpm -qlp %s' % rpm)
    files = files.splitlines()
    for file in files:
        if isPreInstallationScript(file):
            return True
    return False

#---------------------------------------------------------------------------
class InstalledSystem:
#---------------------------------------------------------------------------
    """
    Class wrapper - used to provide information about the currently installed
    gateway release on this system.
    """

    def __init__(self):

        # System architecture.
        self.architecture = self.getarch()

        # Is this an MC box?
        (s,txt)=commands.getstatusoutput('rpm -q phionnet_pki_main')
        self.ismcbox = not s

        # Is this a reporter box?
        (s,txt)=commands.getstatusoutput('rpm -q phionnet_reporter')
        self.isnfrbox = not s

        # Is this a barracuda firewall box?
        (s,txt)=commands.getstatusoutput('rpm -q phionnet_webui')
        self.isbfwbox = not s

        # Version.
        (self.version, self.release) = self.getversion()

        # Base Version (eg. 4.0.1 -> 4.0, 4.1.6 -> 4.1, etc...)
        self.baseversion = self.version[0:self.version.rindex('.')]

        # Sytem stop/restarts require a number of 'flags' to indicate what is/needs to be stopped/started.
        self.torestart = {}
        self.modules_unloaded = {}
        self.modules_loaded = {}


    def getarch(self):
        """
        Return system architecture.
        """

        result = 'i686'
        (status,output) = commands.getstatusoutput('rpm -q --qf="%{arch}\n" kernel | sort| uniq')
        if output != 'i686':
            result = 'x86_64'
        print( 'found architecture %s' % result )

        # rename i686: Since some 32bit rpms are i386 rpms (instead of i686), update fails for 32bit.
        # to work around this issue, use a wildcard architecture
        if result=='i686':
            result='i?86'

        return result

    def getversion(self):
        """
        Return the base version installed on this machine. For post-4.0.0 systems
        this will always be provided by the 'phionnet_release' rpm version number
        but pre-4.0.0 systems (ie. up to 3.6.x) may have an additional phionnet_patch
        file installed giving the 'true' baseversion.
        """

        (status,version) = commands.getstatusoutput('rpm -q --qf "%{version} %{release}" phionnet_patch')

        if status != 0:
            # Obviously no 'phionnet_patch' installed : use phionnet_release instead.
            (status,version) = commands.getstatusoutput('rpm -q --qf "%{version} %{release}" phionnet_release')

        return version.split()


    def stopmodules(self, cfg):
        """
        Stop required modules according to list in 'hotfixrpms' config file.
        Record what needs to be 'restarted' in a variable for restart later.
        """

        # modules should be shut down in specific order : watchdog -> non-box -> box (same lambda is used in startup)
        moduleSort = lambda m: 30 if m == 'watchdog' else ( 10 if hotfixrpms.modulesinhf.get(m) == 'box' else 20 )

        hfnfmodulekeys = sorted(hotfixrpms.modulesinhf.keys(), key=moduleSort, reverse=True)

        if cfg.hasDynamicMIP() and ('firewall' in hfnfmodulekeys or 'boxfw' in hfnfmodulekeys):
            cfg.setForceReboot(True)
            return

        # disable service watchdog to avoid startup of updated control
        if('control' in hfnfmodulekeys):
            os.system('/bin/touch %s' % (STATE_FILE_WATCHDOG))

        #for (module,type) in hotfixrpms.modulesinhf.items():
        for module in hfnfmodulekeys:
            type=hotfixrpms.modulesinhf[module]

            if type == 'box':
                status,output = commands.getstatusoutput('/opt/phion/bin/phionctrl %s show %s' % (type,module) )
                output = output.split()
                if len(output) > 2 and output[2] == 'up':
                    self.torestart[module] = type
                    print "%s service %s now is stopped" % (type,module)
                    os.system('/opt/phion/bin/phionctrl %s block %s' % (type,module))
            elif type == 'module':
                status,output = commands.getstatusoutput('/opt/phion/bin/phionctrl %s show %s' % (type,module) )
                output = output.split()
                if len(output)>3 and output[3] == 'up':
                    self.torestart[module] = type
                    print "%s service %s now is stopped" % (type,module)
                    os.system('/opt/phion/bin/phionctrl %s block %s' % (type,module))
            elif type == 'init':
                if not module == 'sshd':
                    status,output = commands.getstatusoutput("systemctl is-active '%s'" % module )
                    if status == 0:
                        os.system("systemctl stop '%s'" % module)
                        self.torestart[module]=type
                        print "%s service %s now is stopped" % (type,module)
            elif type == 'generic':
                self.torestart[module]=type
                print "generic '%s' will be executed after package installation" % module
            else:
                print "Neither a server service nor a box service of module %s is running. Nothing must be blocked" % module

        # In certain circumstances must unload ktina/acpf
        if ('vpnserver' in self.torestart.keys()) or ('mastervpn' in self.torestart.keys()):
            self.unloadmodule('ktina')
            self.unloadmodule('ktinacrypto')
        if ('firewall' in self.torestart.keys()) or ('boxfw' in self.torestart.keys()):
            self.unloadmodule('acpf')


    def startmodules(self):
        """
        re-start required modules.
        """

        # modules should be started in specific order : box -> non-box -> watchdog
        moduleSort = lambda m: 30 if m == 'watchdog' else ( 10 if self.torestart.get(m) == 'box' else 20 )

        hfnfmodulekeys = sorted(self.torestart.keys(), key=moduleSort)

        if ('firewall' in self.torestart.keys()) or ('boxfw' in self.torestart.keys()):
            self.loadmodule('acpf')
        if ('vpnserver' in self.torestart.keys()) or ('mastervpn' in self.torestart.keys()):
            self.loadmodule('ktina')

        #for (module,type) in self.torestart.items():
        for module in hfnfmodulekeys:
            
            type=self.torestart[module]

            print "%s service '%s' now is started" % (type,module)

            if type == 'module' or type == 'box':
                os.system('/opt/phion/bin/phionctrl %s start %s' % (type,module))
            elif type == 'init':
                if not module == 'sshd':
                    os.system("systemctl start %s" % module)
                else:
                    print 'restart module %s' % module
                    os.system("systemctl restart %s" % module)
            elif type == 'generic':
                allcmds = module.split(';')
                for cmd in allcmds:
                    params = cmd.split(' ')
                    if os.path.exists(params[0]):
                        os.system(cmd)
                        print "executing '%s'" % cmd
                    else:
                        print "'%s' is not available. could not execute '%s'" % (params[0],cmd)

        # enable service watchdog again
        if('control' in hfnfmodulekeys):
            os.system('/bin/rm -f %s' % (STATE_FILE_WATCHDOG))

    def unloadmodule(self,modulename):
        """
        Sensible unload of required module.
        """

        print "INFO: check whether %s has to be unloaded" % modulename

        count = 0

        while count<5:
            unloaded = True
            status,output = commands.getstatusoutput('/sbin/lsmod')
            lines = output.split('\n')
            for line in lines:
                words = line.split()
                if words[0] == modulename:
                    unloaded = False
                    print '%s is still loaded. will unload module' % modulename
                    if modulename == 'ktina':
                        os.system('/opt/phion/bin/ktinactrl stop')
                    elif modulename == 'acpf':
                        os.system('/opt/phion/bin/acpfctrl stop')
                    else:
                        os.system('/sbin/rmmod %s' % modulename)
            if unloaded:
                break
            count=count+1
            time.sleep(1)

        self.modules_unloaded[modulename] = unloaded


    def loadmodule(self,modulename):

        print "INFO: check whether %s has to be loaded" % modulename
        
        count = 0
        
        while count < 5:

            if modulename == 'ktina':
                os.system('/opt/phion/bin/ktinactrl start')
            elif modulename == 'acpf':
                os.system('/opt/phion/bin/acpfctrl start')
            else:
                os.system('/sbin/modprobe %s' % modulename)

            loaded = False
            status,output = commands.getstatusoutput('/sbin/lsmod')
            lines = output.split('\n')
            for line in lines:
                words = line.split()
                if words[0] == modulename:
                    loaded = True
            if loaded:
                break
            print '%s is still not loaded. will load module' % modulename
            count = count + 1
            time.sleep(1)

        self.modules_loaded[modulename] = loaded

    def executeScripts(self, runpath, preInstallation):
        success = True
        whenString = "pre" if preInstallation else "post"
        hotfix_ids = getattr(hotfixrpms, 'hotfix_id', [])
        if not isinstance(hotfix_ids, list):
            hotfix_ids = [hotfix_ids]

        for hotfix_id in hotfix_ids:
            if os.path.isdir('%s/opt/phion/release/hotfixes/%s/bin' % (runpath, hotfix_id)):
                files = os.listdir('%s/opt/phion/release/hotfixes/%s/bin'
                        % (runpath, hotfix_id))

                if files:
                    print('Processing %s commands (for ID %s):' % (whenString, hotfix_id))
                    i = 0
                    for binary in files:
                        if isPreInstallationScript(binary) != preInstallation:
                            continue
                        i = i + 1
                        print('\t%d. %s' % (i, binary))
                        os.system('%s/opt/phion/release/hotfixes/%s/bin/%s'
                                % (runpath, hotfix_id, binary))

            if self.ismcbox:
                if os.path.isdir('%s/opt/phion/release/hotfixes/%s-main/bin'
                        % (runpath, hotfix_id)):
                    files = os.listdir('%s/opt/phion/release/hotfixes/%s-main/bin'
                            % (runpath, hotfix_id))
                    if files:
                        print('Processing %s commands for CC (for ID %s):'
                                % (whenString, hotfix_id))
                        i = 0
                        for binary in files:
                            if isPreInstallationScript(binary) != preInstallation:
                                continue
                            i = i + 1
                            print('\t%d. %s' % (i, binary))
                            os.system('%s/opt/phion/release/hotfixes/%s-main/bin/%s'
                                    % (rundir, hotfix_id, binary))

    def processPreCommands(self, runpath):
        print('Processing pre commands')
        return self.executeScripts(runpath, True)

    def processPostCommands(self):
        print('Processing post commands:')
        print('\t1. ldconfig')
        os.system('/sbin/ldconfig')
        print('\t2. prelink')
        os.system('/usr/sbin/prelink -a 2>/dev/null')
        print('\t3. network')
        os.system('rm -f /opt/phion/preserve/*network*')

        self.executeScripts("", False)


#---------------------------------------------------------------------------
class PhionHotfix:
#---------------------------------------------------------------------------
    """
    Class wrapper - used to provide information about the hotfix we are about
    to install.
    """

    def __init__(self,system):
        """
        system - 'InstalledSystem' upon which the hotfix will be installed.
        """

        # The version we expect to be installed upon.
        self.version = hotfixrpms.baserelease

        # The base version (eg. 4.0.1->4.0, 4.4.5->4.4, etc..)
        self.baseversion = self.version[0:self.version.rindex('.')]

        # Expected rpms for this hotfix.
        self.rpmlist = self.getrpms(system)


    def getrpms(self,system):
        """
        Return the correct rpm list for installing on given 'system'.
        """

        rpmlist = []

        # Give the person installing some indication of what we think we're going to install and return a zero
        # length install list if we don't want install to continue.
        if system.baseversion == self.baseversion:
            pass
        elif LooseVersion(system.baseversion) > LooseVersion(self.baseversion):
            print "INFO: installed base version (%s)" % system.baseversion, "is higher than package base version (%s)" % self.baseversion, "<-> installed base release version: %s." % system.version, "On a MC only main rpms will be installed. On a box the package is rejected"
        else:
            # Installed system base-version too low for this hotfix to be installed.
            print "ERROR: installed base version (%s)" % system.baseversion, "is lower than package base version (%s)" % self.baseversion, "<-> installed base release version: %s" % system.version
            return rpmlist

        # Build up the RPMs that should be installed.
        if system.baseversion == self.baseversion:

            # base rpms
            if 'baserpms' in dir(hotfixrpms):
                for rpm in hotfixrpms.baserpms:
                    try:
                        rpmlist.append(rpm % {'ARCH': system.architecture})
                    except:
                        rpmlist.append(rpm)

            # nfreporter rpms
            if system.isnfrbox and hasattr(hotfixrpms,'nfreporterrpms'):
                for rpm in hotfixrpms.nfreporterrpms:
                    try:
                        rpmlist.append(rpm % {'ARCH': system.architecture})
                    except:
                        rpmlist.append(rpm)

            # bfw rpms
            if system.isbfwbox and hasattr(hotfixrpms,'bfwrpms'):
                for rpm in hotfixrpms.bfwrpms:
                    try:
                        rpmlist.append(rpm % {'ARCH': system.architecture})
                    except:
                        rpmlist.append(rpm)

            # box-mc rpms
            if system.ismcbox and hasattr(hotfixrpms,'boxmainrpms'):
                for rpm in hotfixrpms.boxmainrpms:
                    try:
                        rpmlist.append(rpm % {'ARCH': system.architecture})
                    except:
                        rpmlist.append(rpm)

        # main rpms (for **all** mc boxes - even if baseversions don't match!)
        if system.ismcbox and hasattr(hotfixrpms,'mainrpms'):
            for rpm in hotfixrpms.mainrpms:
                try:
                    rpmlist.append(rpm % {'ARCH': system.architecture})
                except:
                    rpmlist.append(rpm)

        return ' '.join(rpmlist)

    def reassembleDeltaRPMS(self):
        for rpm in self.rpmlist.split():
            if not os.path.exists(rpm) and os.path.exists('%s.delta' % rpm):
                (ret, output)=commands.getstatusoutput('/usr/bin/applydeltarpm %s.delta %s' % (rpm, rpm))
                if ret:
                    print('ERROR: Could not recreate rpm %s: %s. package installation will fail.' % (rpm, output))
                    sys.exit(1)

    def disable_ctrl_timeouts(self):
        try:
            ctrlconf=open(CTRLCONF)
            ctrlconftmp=open(CTRLCONFTMP, 'w')
        except IOError, e:
            # update/patch doit will exit here with an error.
            # but unlike patches/updates, hotfixes may be installed along with an ISO installation, and so
            # control.conf may not yet be there => do not exit here ...
            print "INFO: control configuration not yet available. Do not disable control timeouts."
            return

        for line in ctrlconf.readlines():
            if(line[0:10]=='IDLEPHIONA'):
                ctrlconftmp.write('IDLEPHIONA = 0\n')
            elif (line[0:9]=='IDLESHELL'):
                ctrlconftmp.write('IDLESHELL = 0\n')
            else:
                ctrlconftmp.write(line)

        ctrlconf.close()
        ctrlconftmp.close()

        os.rename(CTRLCONF, CTRLCONFSAVE)
        os.rename(CTRLCONFTMP, CTRLCONF)

    def restore_ctrl_timeouts(self):
        # touch session files to shrink sessions idle time to 0, 
        # cause ctrl is re reading config immediately, and could terminate 
        # this session before the hotfix installation has been completed 

        # step 1: try to get my tty
        foundTTY=False
        (ret, out)=commands.getstatusoutput('/usr/bin/tty')
        if ret == 0 and out[0:5] == '/dev/' and out != '/dev/null':
            os.system('/bin/touch %s' % out)
            foundTTY=True
        # step 2: try to find my parents tty
        elif ret!=0:
            try:
                out=os.readlink('/proc/%d/fd/0' % os.getppid())
                if out[0:5] == '/dev/' and out!='/dev/null':
                    os.system('/bin/touch %s' % out)
                    foundTTY=True
            except Exception, e:
                pass
        # step 3: may be a phionUpdate call. phionUpdate.real is started with redirected stdin. try to find grand parents tty
        if not foundTTY:
            try:
                out=os.readlink('/proc/%s/fd/0' % os.popen("/bin/ps -p %d -oppid=" % os.getppid()).read().strip())
                if out[0:5] == '/dev/' and out!='/dev/null':
                    os.system('/bin/touch %s' % out)
                    foundTTY=True
            except Exception, e:
                pass

        # step 4: last resort. touch all /dev/tty* and /dev/pts/* sessions
        if not foundTTY:
            os.system('touch /dev/tty*')
            if os.path.isdir('/dev/pts/'):
                os.system('touch /dev/pts/*')

        # step 5: touch all ngadmin sessions
        os.system('/bin/touch /opt/phion/run/session_*')

        # step 6: restore original ctrl config
        if(os.path.exists(CTRLCONFSAVE)):
            os.remove(CTRLCONF)
            os.rename(CTRLCONFSAVE, CTRLCONF)

        

#---------------------------------------------------------------------------
#   Start script processing
#---------------------------------------------------------------------------
if __name__ == '__main__':
    main()
