#! /usr/bin/env python

import os, string
import gnuviech
from GNVAdm import GNVDomain

# if [ -n $USERPREFIX ]; then
# 	USERPREFIX="usr"
# fi

# if [ $1 == "" ]; then
# 	echo "give <UserNumber>p<pop3Account> as parameter"
# 	exit
# fi

# NEWUSER="$USERPREFIX$1"
# NEWHOME="/home/mail/$NEWUSER"
# NEWPASS=$(apg -n 1 -a 1 -CL -m 8 -x 12)
# echo $NEWHOME

# adduser --home "$NEWHOME" --shell /bin/true --no-create-home --firstuid 20000 --ingroup poponly --disabled-password --disabled-login --gecos "Popuser $NEWUSER" $NEWUSER

# mkdir -p "$NEWHOME"
# chown -Rc $NEWUSER.poponly "$NEWHOME"
# echo "${NEWUSER}:${NEWPASS}" | chpasswd

# echo "Herzlich willkommen auf dem GNU-Viech" | mail -s "Willkommen auf dem GNU-Viech" ${NEWUSER}
# echo added new pop3 user $NEWUSER with password $NEWPASS

class MailAccount:
    def __init__(self, domain):
        "Initialize a MailAccount instance for a given domain"
        if (not os.access(gnuviech.GNVPrefs.VIRTUALDOMDIR, os.R_OK & os.X_OK)):
            self.setupDirs()
        self.domain = domain

    def setupDirs(self):
        os.mkdir(gnuviech.GNVPrefs.VIRTUALDOMDIR)

class MailAlias(MailAccount):
    """This represents a mail alias"""
    
    def __init__(self, domain):
        "Initialize the POPAccount class for a given domain"
        MailAccount.__init__(self, domain)
        self.aliases = {}
        self.readAll()
        
    def readAll(self):
        """reads the aliasfile for the given domain"""
        self.aliases = {}
        if (os.access(gnuviech.GNVPrefs.VIRTUALDOMDIR, os.R_OK)):
            try:
                aliasfile = open(gnuviech.GNVPrefs.VIRTUALDOMDIR+self.domain.name , 'r')
                for line in aliasfile.readlines():
                    keyvals = string.split(line,":",1)
                    self.aliases[keyvals[0]] = keyvals[1].strip()
                aliasfile.close()
            except IOError:
                print "couldn't read the aliasfile for "+self.domain.name+"."
        else:
            print "couldn't read from "+gnuviech.GNVPrefs.VIRTUALDOMDIR+"."

    def writeAll(self):
        """writes the aliasfile for the given domain with the aliases defined
in the dictionary object aliases"""
        if (os.access(gnuviech.GNVPrefs.VIRTUALDOMDIR, os.W_OK)):
            try:
                aliasfile = open(gnuviech.GNVPrefs.VIRTUALDOMDIR+self.domain.name, 'w')
                keys = self.aliases.keys();
                keys.sort();
                for key in keys:
                    aliasfile.write("%s:%s" % (key, self.aliases[key]) + "\n")
                aliasfile.close()
            except IOError:
                print "writing to aliasfile failed."
        else:
            print "no write access to directory "+gnuviech.GNVPrefs.VIRTUALDOMDIR+"."

    def setAlias(self, alias, target):
        """sets a mail alias for given domain which directs the MTA to the
given target
"""
        self.readAll()
        self.aliases[alias]=target
        self.writeAll()

class POP3Account(MailAccount):
    """This represents a pop 3 account"""

    def create(self, address):
        """Creates a pop3/imap account for the domain"""
        print self
        print "adding address "+address
        alias = MailAlias(self.domain)
        alias.setAlias(address, self.domain.getNextUser("pop3"))
        print alias

if __name__ == "__main__":
    popacc = POP3Account(GNVDomain("dittberner.info"))
    print popacc
    popacc.create("test")

    alias = MailAlias(GNVDomain("dittberner.info"))
    print alias
    alias.setAlias("klaus", "klaus@dittberner.info")
    print alias