#
# instdata.py - central store for all configuration data needed to install
#
# Erik Troan <ewt@redhat.com>
#
# Copyright 2001-2002 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
#
# You should have received a copy of the GNU Library Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import os
import string
import language
import network
import firewall
import security
import timezone
import desktop
import users
import fsset
import bootloader
import partitions
import partedUtils
import hdrlist
import zfcp
from flags import *
from constants import *

from rhpl.simpleconfig import SimpleConfigFile
import rhpl.keyboard as keyboard

class Boolean:
    def set(self, val):
	self.val = val

    def get(self):
	return self.val

    def __init__(self, val = 0):
	self.val = val

# Collector class for all data related to an install/upgrade.

class InstallData:

    def reset(self):
	# Reset everything except: 
	#
	#	- The mouse
	#	- The install language
	#	- The keyboard

	self.langSupport = language.Language()
	self.instClass = None
	self.network = network.Network()
	self.zfcp = zfcp.ZFCP()
	self.firewall = firewall.Firewall()
        self.security = security.Security()
	self.timezone = timezone.Timezone()
	self.accounts = users.Accounts()
        self.rootPassword = users.RootPassword ()
	self.auth = users.Authentication()
	self.desktop = desktop.Desktop()
        self.grpset = None
	self.upgrade = Boolean()
        # XXX move fsset and/or diskset into Partitions object?
	self.fsset.reset()
        self.diskset = partedUtils.DiskSet()
        self.partitions = partitions.Partitions()
        self.bootloader = bootloader.getBootloader()
        self.dependencies = []
        self.handleDeps = CHECK_DEPS
        self.dbpath = None
        self.upgradeRoot = None
        self.rootParts = None
        self.upgradeSwapInfo = None
        self.upgradeDeps = ""
        self.upgradeRemove = []
        self.upgradeInfoFound = None
        self.configFileData = self.tmpData
        self.firstboot = FIRSTBOOT_DEFAULT
        # Used to save the user's choice to upgrade or install
        self.doupgrade = None

    def setInstallProgressClass(self, c):
	self.instProgress = c

    # expects a Keyboard object
    def setKeyboard(self, keyboard):
        self.keyboard = keyboard

    # expects a Mouse object
    def setMouse(self, mouse):
        self.mouse = mouse

    # expects a VideoCardInfo object
    def setVideoCard(self, video):
        self.videocard = video

    # expects a Monitor object
    def setMonitor(self, monitor):
        self.monitor = monitor

    # expects a XF86Config object
    def setXSetup(self, xsetup):
        self.xsetup = xsetup

    # expects 0/1
    def setHeadless(self, isHeadless):
        self.isHeadless = isHeadless

    def write(self, instPath):
        self.langSupport.write (instPath)
        self.keyboard.write (instPath)
        self.timezone.write (instPath)
        self.auth.write (instPath)
	self.firewall.write (instPath)
        self.security.write (instPath)
        self.rootPassword.write (instPath, self.auth)
        self.accounts.write (instPath, self.auth)

    def writeKS(self, filename):
        # make it so only root can read, could have password
	f = open(filename, "w", 0600)

	f.write("# Kickstart file automatically generated by anaconda.\n\n")
	if self.upgrade.get():
	    f.write("upgrade\n");
	else:
	    f.write("install\n");

	# figure out the install method and write out a line
	if self.methodstr.startswith('ftp://') or self.methodstr.startswith('http://'):
	    f.write("url --url %s\n" % (self.methodstr,))
	elif self.methodstr.startswith('cdrom://'):
	    f.write("cdrom\n")
	elif self.methodstr.startswith('hd://'):
	    pidx = string.find(self.methodstr, '//') + 2
	    didx = string.find(self.methodstr[pidx:], '/')
	    partition = string.split(self.methodstr[pidx:pidx+didx], ':')[0]
	    dir = self.methodstr[pidx+didx+1:]
	    f.write("harddrive --partition=%s --dir=%s\n" % (partition, dir))
	elif self.methodstr.startswith('nfs:/') or self.methodstr.startswith('nfsiso:'):
	    (method, tmpmntpt) = string.split(self.methodstr, ':')
	    # clean up extra '/' at front
	    if tmpmntpt[1] == '/':
		rawmntpt = tmpmntpt[1:]
	    else:
		rawmntpt = tmpmntpt
	    mntpt = os.path.normpath(rawmntpt)

	    # find mntpt in /proc/mounts so we can get NFS server info
	    fproc = open("/proc/mounts", "r")
	    lines = fproc.readlines()
	    fproc.close()

	    for l in lines:
		minfo = string.split(l)
		if len(minfo) > 1 and minfo[1] == mntpt:
		    nfsinfo = minfo[0]
		    (srv, dir) = string.split(nfsinfo, ':')
		    f.write("nfs --server=%s --dir=%s\n" % (srv, dir))
		    break

	self.instLanguage.writeKS(f)
	self.langSupport.writeKS(f)
        self.keyboard.writeKS(f)
        if not self.isHeadless:
            self.xsetup.writeKS(f, self.desktop)
	self.network.writeKS(f)
	self.zfcp.writeKS(f)
	self.rootPassword.writeKS(f, self.auth)
	self.firewall.writeKS(f)
        self.security.writeKS(f)
	self.auth.writeKS(f)
	self.timezone.writeKS(f)
        self.bootloader.writeKS(f)
        self.partitions.writeKS(f)
        self.writePackagesKS(f)

	f.write("\n%post\n")
	self.accounts.writeKScommands(f, self.auth)

    def writePackagesKS(self, f):
	f.write("\n%packages")
        if self.handleDeps == IGNORE_DEPS:
            f.write(" --ignoredeps\n")
        elif self.handleDeps == RESOLVE_DEPS:
            f.write(" --resolvedeps\n")
        else:
            f.write("\n")
	packages = {}
        forcedoff = {}
        forcedon = {}
	for group in self.grpset.groups.values():
	    if group.isSelected():
		if (group.isSelected(justManual = 1) and group.id != "base"
                    and group.id != "core"):
		    f.write("@ %s\n" % group.id)

                # handle metapkgs.  this is a little weird 
                for (pkgnevra, pkg) in group.packages.items():
                    if pkg["meta"] == 0:
                        continue
                    metapkg = self.grpset.groups[pkgnevra]
                    # if it's optional and turned on, put it in the ks.cfg
                    if (metapkg.isSelected() and
                        pkg["type"] == hdrlist.PKGTYPE_OPTIONAL):
                        f.write("@ %s\n" %(metapkg.id,))
                    # if it's default and turned off, then turn off the
                    # component packages (we dont' have a -@grp syntax)
                    elif (not metapkg.isSelected() and
                          pkg["type"] == hdrlist.PKGTYPE_DEFAULT):
                        for (pkgnevra, pkg) in metapkg.packages.items():
                            name = self.grpset.hdrlist[pkgnevra].name
                            forcedoff[name] = 1

                # handle packages
                for (pkgnevra, pkg) in group.packages.items():
                    if pkg["meta"] != 0:
                        continue
                    name = self.grpset.hdrlist[pkgnevra].name
                    # if it's in base or core, it really should be installed
                    if group.id == "base" or group.id == "core":
                        packages[name] = 1
                    else:
                        if pkg["type"] == hdrlist.PKGTYPE_MANDATORY:
                            packages[name] = 1
                        else:
                            if ((pkg["type"] == hdrlist.PKGTYPE_DEFAULT) and
                                (pkg["state"] in hdrlist.ON_STATES)):
                                packages[name] = 1
                            elif ((pkg["type"] == hdrlist.PKGTYPE_DEFAULT) and
                                  (pkg["state"] in hdrlist.OFF_STATES)):
                                forcedoff[name] = 1
                            elif ((pkg["type"] == hdrlist.PKGTYPE_OPTIONAL) and
                                  (pkg["state"] in hdrlist.ON_STATES)):
                                forcedon[name] = 1
                            elif ((pkg["type"] == hdrlist.PKGTYPE_OPTIONAL) and
                                  (pkg["state"] not in hdrlist.ON_STATES)):
                                pass

	for pkg in self.grpset.hdrlist.values():
            if ((pkg.isSelected() and pkg.manual_state == 2) or
                (forcedon.has_key(pkg.name))):
		f.write("%s\n" % pkg.name)
            if ((not pkg.isSelected() and pkg.manual_state == -2) or
                forcedoff.has_key(pkg.name)):
                f.write("-%s\n" %(pkg.name))

    def __init__(self, extraModules, floppyDevice, configFileData, methodstr):
	self.instLanguage = language.InstallTimeLanguage()
	self.keyboard = keyboard.Keyboard()
        self.tmpData = configFileData

        self.configFileData = None
        self.mouse = None
        self.monitor = None
        self.videocard = None
        self.xsetup = None
        self.isHeadless = 0
	self.extraModules = extraModules
	self.floppyDevice = floppyDevice
	self.fsset = fsset.FileSystemSet()
        self.excludeDocs = 0
        try:
            f = open("/proc/cmdline")
            line = f.readline()
            if line.find(" excludedocs") != -1:
                self.excludeDocs = 1
            close(f)
        except:
            pass

        # FIXME: this is a major hack to get the comps package installed
        self.compspkg = None

        self.methodstr = methodstr
	self.reset()
