#!/usr/bin/python3
#
# Copyright (C) Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
import os
import sys
from pprint import pprint

from sm.lcache import *

if __name__ == '__main__':
    args = list(sys.argv)
    prog = args.pop(0)
    prog = os.path.basename(prog)


    def usage(stream):
        if prog == 'tapdisk-cache-stats':
            print("usage: tapdisk-cache-stats [<sr-uuid>]", file=stream)
        else:
            print("usage: %s sr.{stats|topology} [<sr-uuid>]" % prog, file=stream)


    def usage_error():
        usage(sys.stderr)
        sys.exit(1)

    if prog == 'tapdisk-cache-stats':
        cmd = 'sr.stats'
    else:
        try:
            cmd = args.pop(0)
        except IndexError:
            usage_error()

    try:
        _class, method = cmd.split('.')
    except:
        usage(sys.stderr)
        sys.exit(1)

    if _class == 'sr':
        try:
            uuid = args.pop(0)
        except IndexError:
            cache_sr = CacheSR.from_cli()
        else:
            cache_sr = CacheSR.from_uuid(uuid)

        if method == 'stats':

            d = cache_sr.xapi_stats()
            for item in d.items():
                print("%s=%s" % item)

        elif method == 'topology':
            parents = cache_sr.fast_scan_topology()

            for parent in parents:
                print(parent, "hits/miss=%s total=%s" % \
                    (parent.vdi_stats(), parent.vdi_stats_total()))
                pprint(parent.stats)

                for leaf in parent.leaves:
                    print(leaf, "hits/miss=%s" % str(leaf.vdi_stats()))
                    pprint(leaf.stats)

            print("sr.total=%s" % str(cache_sr.vdi_stats_total()))

        else:
            usage_error()
    else:
        usage_error()
