from installclass import BaseInstallClass
import rhpl
from rhpl.translate import N_,_
from constants import *
from flags import flags
import os
import iutil
import types
import rpmUtils.arch
import logging
log = logging.getLogger("anaconda")


class CERNScript:
 def __init__(self, body, interp, inChroot, logfile = None):
        self.script = body
        self.interp = interp
        self.inChroot = inChroot
        self.logfile = logfile

 def run(self, chroot, serial, intf = None):
        import tempfile
        import os.path

        if self.inChroot:
            scriptRoot = chroot
        else:
            scriptRoot = "/"

        (fd, path) = tempfile.mkstemp("", "cernpost-script-", scriptRoot + "/tmp")

        os.write(fd, self.script)
        os.close(fd)
        os.chmod(path, 0700)

        if self.logfile is not None:
            messages = self.logfile
        elif serial:
            messages = "%s.log" % path
        else:
            messages = "/dev/tty3"


        rc=iutil.execWithRedirect(self.interp, ["/tmp/%s" % os.path.basename(path)],
                                    stdin = messages, stdout = messages, stderr = messages,
                                    root = scriptRoot)

        # Always log an error.  Only fail if we have a handle on the
        # windowing system and the kickstart file included --erroronfail.
        if rc != 0:
            log.error("Error code %s encountered running a CERN %%pre/%%post script", rc)

        os.unlink(path)

        if serial or self.logfile is not None:
            os.chmod("%s" % messages, 0600)

class InstallClass(BaseInstallClass):
    hidden = 0
    pixmap = "cern-workstation.png"
    showMinimal = 1
    showLoginChoice = 1
    name = N_("CERN Recommended Setup")
    id = "sl"
    _description = N_("The default installation of %s includes a recommended set of"
                     "software applicable for desktop usage in CERN computing environment."
                     "\nNOTE: While adding other repositories, select also 'Updates'. OnlyCERN "
                     "repository is not available if your system is not at CERN."
                     "\nWhat additional tasks would you like your system to include support for?") %(productName,)
    name = N_("CERN Recommended Setup")
#    pkgstext = "some text about packages ??"
    showUpgrade = 1 
    sortPriority = 0.1
    default = 1 
    allowExtraRepos = True
    repos = {
             "Scientific Linux CERN Updates": 
	       ("http://linuxsoft.cern.ch/cern/slc5X/%s/updates/RPMS/" %(rpmUtils.arch.getBaseArch() ,), None),
	     "Scientific Linux CERN Extras" : 
	       ("http://linuxsoft.cern.ch/cern/slc5X/%s/extras/RPMS/" %(rpmUtils.arch.getBaseArch() ,), None),
	     "Scientific Linux CERN OnlyCERN" : 
	       ("http://linuxsoft.cern.ch/onlycern/slc5X/%s/RPMS/" %(rpmUtils.arch.getBaseArch() ,), None),
            }

    
    taskMap = {

               'sl' : [(N_("CERN Recommended Setup for Workstations"), 
				["gnome-desktop","kde-desktop","office", "editors", "system-tools",
				 "engineering-and-scientific","authoring-and-publishing",
				 "x-software-development","development-tools","openafs-client",
				 "cern-addons","cern-addons-x11","legacy-software-support",
				 "graphics","sound-and-video","graphical-internet", 
				 "printing","multimedia","firmware" ]),
                       (N_("Server"), ["server-cfg", "web-server", "dns-server", "ftp-server", 
                                       "smb-server", "mail-server", "network-server", "legacy-network-server", 
                                       "news-server"]),
                       (N_("Virtualization"), ["xen"]),
                       (N_("Clustering"), ["clustering"]),
                       (N_("Storage Clustering"), ["cluster-storage"]),]
                       
             }

    # install key related bits
    skipkeytext = None
    instkeyname = None
    allowinstkeyskip = True
    instkeydesc = None
    installkey = None
    skipkey = True
    instnum = None
		    
    def setGroupSelection(self, anaconda):
        grps = anaconda.backend.getDefaultGroups(anaconda)
	map(lambda x: anaconda.backend.selectGroup(x), grps)	


    def getPackagePaths(self, uri):
        rc = {}
        for (name, path) in self.repopaths.items():
            if not type(uri) == types.ListType:
                uri = [uri,]
            if not type(path) == types.ListType:
                path = [path,]

            lst = []
            for i in uri:
                for p in path:
                    lst.append("%s/%s" % (i, p))

            rc[name] = lst

        log.info("package paths is %s" %(rc,))
        return rc

    def postAction(self, anaconda, serial):
        if len(self.postScripts) == 0:
            return
	log.info("Running CERN post actions")
	if anaconda.intf is not None:
            w = anaconda.intf.waitWindow(("Running..."),
                                ("Executing post-install actions"))   

        map (lambda s: s.run(anaconda.rootPath, serial, anaconda.intf), self.postScripts)

	if anaconda.intf is not None:
            w.pop()
    	    
    def setInstallData(self, anaconda ):
        BaseInstallClass.setInstallData(self, anaconda)
        BaseInstallClass.setDefaultPartitioning(self, anaconda.id.partitions,CLEARPART_TYPE_LINUX)
        BaseInstallClass.setTimezoneInfo(self, anaconda.id ,"Europe/Zurich",1)  
	BaseInstallClass.setFirewall(self, anaconda.id,  enable = 1, trusts = [], ports = ["22:tcp", "7001:udp"])
        BaseInstallClass.setAuthentication(self, anaconda.id ,"--useshadow  --enablemd5  --enablekrb5 ")
                              
        self.postScripts = []
        postactions = [ 
#                ("/bin/ln -sf /usr/share/lcm/profile_standalone_cern.xml /usr/share/lcm/profile_standalone.xml","/bin/sh",True,"cernpost.log"), 
# temporary: until Jan fixes it ...
			("/sbin/chkconfig --del rfiod","/bin/sh",True,"cernpost.log"),
                        ("/bin/rpm -q castor-lib >& /dev/null && F=`/bin/mktemp /tmp/XXXXX` && /bin/rpm -q --qf '%{POSTIN}' castor-lib > $F && /bin/sh -x $F 1 && /bin/rm -f $F","/bin/sh",True,"cernpost.log") ]

        for (script, interp, chroot, log) in postactions:
            self.postScripts.append(CERNScript(script, interp, chroot, log))

    def setSteps(self, dispatch):
	BaseInstallClass.setSteps(self, dispatch);
	dispatch.skipStep("regkey", skip = 1)        

    def __init__(self, expert):
	BaseInstallClass.__init__(self, expert)	
        self.repopaths = { "base": "%s" %(productPath,) }
        self.tasks = self.taskMap[productPath.lower()]
