#! /usr/bin/env python
'''Dump statistics for all storage pools in all Catalogs.  Run it from a
host with appropriate mysql connectivity.'''

from __future__ import print_function
import bacula_tools


class FormattedResult(dict):

    '''Prints a nicely-formatted collection of statistics for a pool.
    Instantiate once per pool, use the add method for each media volume in
    the pool.

    '''
    keylist = ['Full', 'Archive', 'Append', 'Recycle', 'Purged', 'Read-Only',
               'Disabled', 'Error', 'Busy', 'Used', 'Cleaning']
    name_width = 20

    def __init__(self, name):
        '''Set up initial values.'''
        dict.__init__(self)
        self['NAME'] = name
        self.fmt = "{NAME:%d} " % self.name_width
        for key in self.keylist:
            self[key] = 0
            self.fmt += '{%s:>%d} ' % (key, max(len(key), 6))
        self.updated = False
        return

    def add(self, pair):
        '''Add an item for this pool.  Call this with a (name, value) tuple.'''
        self.updated = True
        self[pair[0]] += pair[1]

    def print(self):
        '''Print one row(pool), but only if we have some data.'''
        if not self.updated:
            return
        return print(self.fmt.format(**self))

    def print_titles(self):
        '''Prints the keys as a title string '''
        titles = dict(zip(self.keylist, self.keylist))
        titles['NAME'] = ''
        print(self.fmt.format(**titles))

    def __add__(self, other):
        '''Operator to allow (sub)totalling pools.
        '''
        self.updated = True
        for key in self.keylist:
            self[key] += other[key]
        return self

pool_sql = 'SELECT PoolId, Name FROM Pool ORDER BY Name'
media_sql = '''select VolStatus, count(MediaId) from Media
                      where PoolId=%s group by VolStatus'''
for catalog in bacula_tools.Catalog().Find():
    conn = catalog.connect()
    print('\nCatalog: ' + catalog[bacula_tools.NAME])
    width = FormattedResult.name_width
    title = "{0}\n{1:%d}" % width
    totals = FormattedResult(title.format('=' * width, 'Totals'))
    totals.print_titles()
    for pool in conn.do_sql(pool_sql):
        result = FormattedResult(pool[1])
        for row in conn.do_sql(media_sql, pool[0]):
            result.add(row)
        result.print()
        totals += result
    totals.print()
    print()
