#!/usr/bin/python

import sys,os,string

def clearSMTPDb(smtpUser):
	# Remove the user from the SMTP password file
	userList = "/etc/exim/users"
	tmpUserList = "/etc/exim/users.new"
	if os.path.exists("%s" % userList):
		f = open("%s" % userList)
		p = open("%s" % tmpUserList, 'w')
		fullList = f.readline()
		while fullList:
			alreadyExist = string.find(fullList, "%s:" % smtpUser)
			if alreadyExist == 0:
				fullList = f.readline()
				continue
			p.write("%s" % fullList)
			fullList = f.readline()
		f.close()
		p.close()

		os.rename(tmpUserList, userList)
	return()

def changePassword(accountName):
	from getpass import getpass
	from crypt import crypt

	# Prompt for Password
	print 'Adding only APOP password for %s.' % accountName
	userPass = getpass("New password: ")
	userPass2 = getpass("Retype new password: ")

	# Simple check to make sure passwords match
	if userPass != userPass2:
		print 'Mismatch -- password unchanged.'
		sys.exit(1)

	clearSMTPDb(accountName)

	userList = "/etc/exim/users"

	# Add user and encrypted password
	f = open("%s" % userList, 'a')
	f.write("%s:%s\n" % (accountName,crypt(userPass,accountName)))
	f.close()

	# Run the original popauth command to change the qpopper password
	c = os.popen("/usr/sbin/popauth -user %s '%s'" % (accountName,userPass))
	return()

def deleteUser(accountName):
	clearSMTPDb(accountName)

	# Run the original popauth command to delete the user from QPopper's database
	c = os.popen("/usr/sbin/popauth -delete %s" % accountName)
	# This will remove the account from the system, but keep the home directory
	s = os.popen("userdel %s" % accountName)

	return()


# Make sure at least 2 arguments were given. Exit if not.
if len(sys.argv) > 2:
        userName = sys.argv[2]
else:
	sys.exit(1)


# Check whether a user is to be deleted or its password changed
if sys.argv[1] == "-delete":
	try:
		deleteUser(userName)
	except:
		sys.exit(1)
else:
	try:
		changePassword(userName)
	except:
		sys.exit(1)

sys.exit(0)

