"""Package for GNUViech Admin main types and functions

(c) Copyright 2004 Jan Dittberner, IT-Consulting & Solutions
    Germany
"""

import os
import gnuviech

class DomainNotExistentError(Exception): pass

class DomainFileNotExistentError(Exception): pass

class GNVDomain:
    """Represents a domain in the GNUViech admin tool"""

    def __init__(self, domain):
        """Initializes the domain object"""
        self.name = domain
        try:
            self.findUser()
        except gnuviech.NoAdmDirError:
            gnuviech.setupDirs()
            self.__init__(domain)
        except DomainFileNotExistentError:
            self.createDomainFile()
            self.__init__(domain)
        except DomainNotExistentError:
            self.createUser()

    def __repr__(self):
        retval = "Domain "+self.name
        if not self.username is None:
            retval += ", User "+self.username
        else:
            retval += ", new domain"
        return retval
    
    def createDomainFile(self):
        """Create the domain user id map file."""
        file = open(gnuviech.GNVPrefs.GVADMDIR+"domains", "w")
        file.close()

    def createUser(self):
        """Create a user for the domain."""
        file = open(gnuviech.GNVPrefs.GVADMDIR+"domains", "r")
        id = 0
        for line in file.readlines():
            (key, value) = line.split(":")
            if (int(value) > id): id = int(value)
        file.close()
        id += 1
        file = open(gnuviech.GNVPrefs.GVADMDIR+"domains", "a")
        file.write("%s:%d\n" % (self.name, id))
        file.close()
        self.findUser()

    def findUser(self):
        """Finds the user for the domain."""
        self.username = None
        if (os.access(gnuviech.GNVPrefs.GVADMDIR, os.R_OK)):
            try:
                domainsfile = open(gnuviech.GNVPrefs.GVADMDIR+"domains", "r")
                for line in domainsfile.readlines():
                    (key, value) = line.split(":")
                    if (key == self.name):
                        self.username = "%s%02d" % (
                            gnuviech.GNVPrefs.USERPREFIX,
                            int(value))
                domainsfile.close()
                if self.username is None:
                    raise DomainNotExistentError
            except IOError:
                raise DomainFileNotExistentError
        else:
            raise gnuviech.NoAdmDirError

    def getMaxPop3Id(self):
        maxid = 0
        try:
            passwdfile = open(gnuviech.GNVPrefs.BASEPREFIX+"/etc/passwd", "r")
            for line in passwdfile.readlines():
                (login, passwd, uid, gid, name, dir, shell) = line.split(":")
                if login.startswith(self.username + "p"):
                    id = int(login[len(self.username):])
                    print id
                    if (id > maxid): maxid = id
        except IOError:
            pass
        return maxid

    def getNextUser(self, usertype):
        """Gets the next user for the given type."""
        if (usertype == "web"):
            return self.username
        if (usertype == "pop3"):
            return "%sp%d" % (self.username, self.getMaxPop3Id()+1)

if __name__ == "__main__":
    dom = GNVDomain("dittberner.info")
    print dom