#!/usr/bin/python -tt
#
# rmvirt
# --------
# This script removes a virtual domain on a QVCS system.
#
# Copyright (c) 2001-2002 by Konstantin Riabitsev <icon@duke.edu>
# Licensed under the GNU GPL. For full terms see http://www.gnu.org/
#
# $Id: rmvirt,v 1.2 2003/06/20 20:30:49 graf25 Exp $
#
# @author Konstantin Riabitsev <icon@duke.edu> ($Author: graf25 $)
# @version $Date: 2003/06/20 20:30:49 $
#

import sys
import os
import qvcs
import pwd

VADMINDIR = '/var/lib/vadmin'

def _usage():
    print 'Usage: rmvirt domainname'
    print '    Removes a virtual domain from the system.'
    sys.exit(1)

def ask(message):
    yn = raw_input('%s [y/n] ' % message)
    if not yn: return 0
    yn = yn.lower()
    if yn == 'y' or yn == 'yes': return 1
    return 0
    
def _main(args):
    if len(args) < 1:
        print "Missing domain name"
        _usage()
    if len(args) > 1:
        print "Too many arguments"
        _usage()
    domain = args[0]
    try:
        if domain.index('-') == 0: _usage()
    except ValueError: pass
    if not qvcs.domain_exists(domain):
        print 'ERROR: domain %s does not exist in virtualdomains' % domain
        sys.exit(1)
    if not ask('This will delete domain %s. Proceed?' % domain):
        sys.exit(0)
    print "Deleting virtual domain %s" % domain
    uname = qvcs.get_uname(domain)
    try:
        udir = pwd.getpwnam(uname)[5]
        print "Deleting username %s" % uname
        cmd = "/usr/sbin/userdel %s" % uname
        os.system(cmd)
        if os.path.isdir(udir):
            if ask('Back up the home directory?'):
                bakfile = '%s-backup.tar.gz' % domain
                bakpath = os.path.join(os.path.dirname(udir), bakfile)
                cmd = '/bin/tar czf %s %s' % (bakpath, udir)
                print 'Backing up %s. This may take a while.' % udir
                os.system(cmd)
                print 'Backup placed in %s' % bakpath
            if ask('Delete the home directory?'):
                print 'Deleting %s. This may take a while.' % udir
                os.system('/bin/rm -rf %s' % udir)
    except KeyError:
        print "Odd, domain user %s was not found. Skipped deletion." % uname
    if ask('Delete vadmin preferences file?'):
        os.system('/bin/rm -f %s/%s.*' % (VADMINDIR, domain))
    qvcs.remove_domain(domain)
    print "Domain deleted successfully. You will need to restart qmail."
    sys.exit(0)

if __name__ == '__main__':
    ##
    # Check for root
    #
    _main(sys.argv[1:])
    if os.geteuid() == 0: _main(sys.argv[1:])
    else:
        print 'Please run me as root.'
        sys.exit(1)
