"""Package for GNUViech Admin main types and functions

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

import os, pwd
import gnuviech
from gnuviech import sysuser

class DomainNotExistentError(Exception): pass

class DomainFileNotExistentError(Exception): pass

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

    def __init__(self, domain, prefs):
        """Initializes the domain object"""
        self.logger = prefs.getLogger(self)
        self.prefs = prefs
        self.name = domain
        self.webaccount = None
        self.zone = None
        self.statsusers = {}
        self.mailaliases = {}
        self.pop3accounts = {}
        try:
            self.__findUser()
        except gnuviech.NoAdmDirError:
            prefs.setupDirs()
            self.__init__(domain)
        except DomainFileNotExistentError:
            self.__createDomainFile()
            self.__init__(domain, prefs)
        except DomainNotExistentError:
            self.__createUser()
        self.createWebUser()

    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(self.prefs.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(self.prefs.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(self.prefs.GVADMDIR, os.R_OK)):
            try:
                domainsfile = open(self.prefs.GVADMDIR+"domains", "r")
                for line in domainsfile.readlines():
                    (key, value) = line.split(":")
                    if (key == self.name):
                        self.username = "%s%02d" % (
                            self.prefs.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)

    def addPOP3Account(self, account):
        self.pop3accounts[account.localpart] = account

    def addMailAlias(self, alias):
        self.mailaliases[alias.localpart] = alias

    def createWebUser(self):
        try:
            self.webaccount = sysuser.SystemUser(self.prefs, self.username)
        except sysuser.UserNotInPasswdError:
            self.webaccount = sysuser.createUser(self.prefs, self.username,
                                                    "web")
        self.logger.debug(str(self.webaccount))
        
# #!/bin/sh
# . /usr/local/etc/preferences
# if [ -n $USERPREFIX ]; then
#         USERPREFIX="usr"
# fi
# if [ $1 == "" ]; then
#         echo "usage: $0 <usernum>"
#         exit
# fi

# NEWUSER="$USERPREFIX$1"
# NEWHOME="/home/www/$NEWUSER"
# LOGDIR="/home/www/logfiles/$NEWUSER"

# adduser --home "$NEWHOME" --shell /bin/true --no-create-home --firstuid 10000 --ingroup wwwusers --disabled-password --gecos "Webuser $NEWUSER" $NEWUSER

# echo "${NEWUSER}:${NEWPASS}" | chpasswd
# mkdir -p "$NEWHOME/"{html,cgi-bin}
# mkdir -p "$LOGDIR"
# chown -Rc www-data.www-data "$LOGDIR"
# chmod 0750 "$LOGDIR"
# chown -Rc $NEWUSER.wwwusers "$NEWHOME"
# mkdir -p "$NEWHOME/html/stats"
# chown modlogan.wwwusers "$NEWHOME/html/stats"
# htpasswd -bc "/home/www/${NEWUSER}stats" "${NEWUSER}" "${NEWPASS}"

# echo added new web user $NEWUSER with password $NEWPASS        

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