from rhutil import *

class Fstab:

    def addMount(self, device, mntpoint, fstype, options, freq, order):
	which = len(self.mounts)
	self.mounts.append((device, mntpoint, fstype, options, freq, order))
	self.mntIndex[mntpoint] = which
	self.devIndex[device] = which

    def addSwap(self, device):
	which = len(self.mounts)
	self.mounts.append((device, "none", "swap", "sw", 0, 0))
	self.devIndex[device] = which

    def findPartByPoint(self, mntpoint):
	if (self.mntIndex.has_key(mntpoint)):
	    (device, mntpoint, fstype, options, freq, order) = (
		self.mounts[self.mntIndex[mntpoint]])
	    return device
	else:
	    return None

    def findMountByPoint(self, mntpoint):
	if (self.mntIndex.has_key(mntpoint)):
	    return self.mntIndex[mntpoint]
	else:
	    return None

    def deviceGetsMounted(self, device):
	return self.devIndex.has_key(device)

    def create(self, filename):
	mnts = {}
	mntpoints = []
	for mount in self.mounts:
	    (device, mntpoint, fstype, options, freq, order) = mount
	    mnts[mntpoint] = mount
	    mntpoints.append(mntpoint)
	
	mntpoints.sort()
	fd = open(filename, "w", 0644)
	for mntpoint in mntpoints:
	    (device, mntpoint, fstype, options, freq, order) = mnts[mntpoint]
	    fd.write("%-20s%-20s%-10s%-10s %d %d\n" % (device, mntpoint,
			fstype, options, freq, order))
	fd.write("%-20s%-20s%-10s%-10s 0 0\n" % ("/dev/fd0", "/mnt/floppy",
		    "ext2", "defaults,noauto"))
	fd.write("%-20s%-20s%-10s%-10s 0 0\n" % ("/proc", "/proc",
		    "proc", "defaults"))
	fd.close()

    def mountAll(self, prefix, linuxonly = 1, test = 0):
	mnts = {}
	mntpoints = []
	for mount in self.mounts:
	    (device, mntpoint, fstype, options, freq, order) = mount
	    mnts[mntpoint] = mount
	    mntpoints.append(mntpoint)
	
	mntpoints.sort()
	for mntpoint in mntpoints:
	    (device, mntpoint, fstype, options, freq, order) = mnts[mntpoint]
	    if (fstype != "swap"): 
		if (not test):
		    rhmkdir(prefix + mntpoint)
		else:
		    print "mkdir of ", prefix + mntpoint

		if ((not linuxonly) or fstype == "ext2" or fstype == "swap"):
		    cmd = "/bin/mount"
		    args = ( "-o", options, "-t", fstype, device, 
			    prefix + mntpoint)
		    rhsystem(cmd, args, test)

    def getList(self):
	return self.mounts

    def __init__(self):
	self.mounts = []
	self.mntIndex = {}
	self.devIndex = {}
