#!/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:
#
# /usr/bin/billing_info
#
# Example:
#
# billing_info

import os
import string
import sys
import copy
import string
import ensimapplpath
import be_vherrordisp
from vh3.errors.virtualhosting import *
from vh3 import virthost

meta_svcs = ['siteinfo', 'bandwidth', 'ipinfo', 'diskquota',
             'users']

class BaseBilling:

    def init(self):
        self.aggregates = {}
        self.status = []
        
    def process_all(self):
        total_domains, enabled_domains, disabled_domains = 0, 0, 0
        for siteindex in virthost.get_domain_list():
            total_domains += 1
            if virthost.domain_enabled(siteindex):
                enabled_domains += 1
            else:
                disabled_domains += 1
            details = []

            config, errs = None, None
            try:
                config,errs = virthost.get_configs_from_site(siteindex)
		self.status.extend(errs)
            except:
                import traceback
                traceback.print_exc(file=sys.stderr)
            if not config:
                continue
            
            severity = determine_action_severity(errs)
            if severity == ERROR:
                continue
            displayconfig = {}

            try:
                # these next lines of code should prolly be in agg
                # billing class
                for i in config.keys():
                    if config[i]:
                        displayconfig[i] = int(config[i]['enabled'])
                displayconfig['namebased'] = int(config['ipinfo']['namebased'])
                displayconfig['ipbased'] = 1 - displayconfig['namebased']
            except:
                # site could be in an inconsistent state...
                continue
            self.process_site(displayconfig)
        self.aggregates = {'total': total_domains,
                           'enabled': enabled_domains,
                           'disabled': disabled_domains}

    def dump_errors(self, fptr):
        virthost.cli_display_status_list(self.status)

class AggregateBilling(BaseBilling):

    def dump(self, fptr):
        output = []
        outputdict = copy.copy(self.output)
        outputdict.update(self.aggregates)
        sorted_keys = outputdict.keys()
        sorted_keys.sort()
        for i in sorted_keys:
            output.append('%s=%s' % (i, outputdict[i]))
        fptr.write('%s\n' % string.join(output, '|'))
        
    def init(self):
        self.output = {'namebased': 0,
                       'ipbased': 0}
        for i in filter(lambda x: not x in meta_svcs,
                        virthost.get_ordered_service_list()):
            self.output[i] = 0
        BaseBilling.init(self)

    def process_site(self, dict):
        for i in filter(lambda x: not x in meta_svcs,
                        dict.keys()):
            if not self.output.has_key(i):
                self.output[i] = 0
            self.output[i] += dict[i]


if __name__ == '__main__':
    try:
        b = AggregateBilling()
        b.init()
        b.process_all()
        b.dump(sys.stdout)
        b.dump_errors(sys.stderr)
    except:
        import traceback
        traceback.print_exc(file=sys.stderr)
        sys.exit(1)
