#!/usr/bin/ensim-python
#
# Copyright (c) Ensim Corporation 2000, 2001   All Rights Reserved.
#
# This software is furnished under a license and may be used and copied
# only  in  accordance  with  the  terms  of such  license and with the
# inclusion of the above copyright notice. This software or any other
# copies thereof may not be provided or otherwise made available to any
# other person. No title to and ownership of the software is hereby
# transferred.
#
# The information in this software is subject to change without notice
# and  should  not be  construed  as  a commitment by Ensim Corporation.
# Ensim assumes no responsibility for the use or  reliability  of its
# software on equipment which is not supplied by Ensim.
#
#
# This function lists all virtual domains on a WEBppliance
#
# Usage:
#
# ListAllVirtDomains
#
# Example:
#
# ListAllVirtDomains

import getopt
import os
import re
import string
import sys
import traceback
import types
from vh3 import virthost
import convertunits
import ensimapplpath
import dashboard

def full_format(sites):
    sites_in_db = virthost.get_domain_list2()
    for siteindex in virthost.get_domain_list():
        if sites and siteindex not in sites:
            continue
        try:
            config, errs = virthost.get_configs_from_site(siteindex)
            usage, errs = virthost.get_site_usage(siteindex)

            config['siteinfo']['suspended'] = 1 - virthost.domain_enabled(siteindex)
            config['siteinfo']['status'] = not virthost.domain_edit_complete(siteindex)
            if config['siteinfo'].has_key('domain') and \
             config['siteinfo']['domain'] not in sites_in_db:
                # Ghost sites present as a result of error in site creation.
                config['siteinfo']['status'] = 1
               
            # pre-process: remove unwanted stuff
            del config['siteinfo']['passwd1']
            del config['siteinfo']['passwd2']

            site_config = ''
            for service in config.keys():
                dict = config[service]
                dict.update(usage[service])

                site_config += ' %s' % service

                del dict['version']
                if service == 'diskquota':
                    dict['quota'] = convertunits.convert_to_B(dict['quota'], \
                                                              dict['units'])
                    del dict['units']
                
                for field in dict.keys():
                    value = dict[field]
                    if type(value) == types.ListType:
                        # lists only contain IPs or domain names, so they
                        # don't need further quoting
                        value = '[' + string.join(value, ',') + ']'
                    else:
                        value = str(value)
                        value = re.sub(r'([ ,\[\]])', r'\\\1', value)
                    site_config += ',%s=%s' % (field, value)
            print site_config[1:]
        except:
            # Fix for PR 27505 - get_site_usage or get_configs_from_site raises
            # cause either a TypeError or AtttributeError for sites in
            # inconsistent state.
            if config:
                config['siteinfo']['suspended'] = 1 - virthost.domain_enabled(siteindex)
                if config['siteinfo'].has_key('passwd1'):
                    del config['siteinfo']['passwd1']
                if config['siteinfo'].has_key('passwd2'):
                    del config['siteinfo']['passwd2']
                config['siteinfo']['status'] = 1 # We are in inconsistent state

                if config['siteinfo'].has_key('domain') and \
                config['siteinfo']['domain'] not in sites_in_db:
                    # Ghost sites present as a result of error in site creation.
                    config['siteinfo']['status'] = 1
                s = [ '%s=%s' % (k, v) for k, v in config['siteinfo'].items() ]
                s = '%s,%s' % ('siteinfo', ','.join(s))
                print "%s" % s
            
def list_all(sites):
    for siteindex in virthost.get_domain_list():
        details = [] 
        if sites and siteindex not in sites:
            continue
        config,errs = virthost.get_configs_from_site(siteindex)
        if config['siteinfo'] and config['ipinfo']:
            details.append(config['siteinfo']['domain'])
            if int(config['ipinfo']['namebased']) == int(1):
                details.append("0")
                details.append(site_ips(config['ipinfo']['nbaddrs']))
            else:
                details.append("1")
                details.append(site_ips(config['ipinfo']['ipaddrs']))
            details.append(site_enabled(siteindex))
            details.append(config['siteinfo']['admin_user'])
            details.append(config['siteinfo']['email'])
            for service in config.keys():
                if config[service]:
                    details.append("%s:%s"%(service,config[service]['enabled']))
                    if (service == 'apache'):
                        details.append("webserver:%s"%(config[service]['webserver']))
                    elif (service == 'cgi'):
                        details.append("scriptalias:%s"%(config[service]['scriptalias']))
                    elif (service == 'proftpd'):
                        details.append("ftpserver:%s"%(config[service]['ftpserver']))
                    elif (service == 'users'):
                        if (config[service]['enabled'] == '1'):
                            details.append("maxusers:%s"%(config[service]['maxusers']))
                        else:
                            details.append("maxusers:infinite")
            site_details=string.join(details, " ")
            print site_details

def site_enabled(siteindex):
    return str(virthost.domain_enabled(siteindex))

def site_ips(ipaddrs):
    ips = []
    for ip in ipaddrs:
        ips.append(ip)
    return string.join(ips," ")

if __name__=='__main__':
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'fs:')
    except getopt.GetoptError:
        sys.stderr.write("usage: %s [-f]\n" % os.path.basename(sys.argv[0]))
        sys.exit(1)
    opt_dict = {}
    sites = []
    for key,arg in optlist:
        if key in ('-f',):
            opt_dict[key] = arg
        elif key in ('-s',):
            site = virthost.get_site_from_anything(arg)
            if site:
                sites.append(site)

    if opt_dict.has_key('-f'):
        full_format(sites)
    else:
        list_all(sites)
