#!/usr/bin/env python

"""
invirt-quota allows an administrator to set memory, disk, and VM quotas 
for an owner.  Invoking with only an owner name returns the current quotas for
that owner.  Setting a parameter to -1 restores the default.
"""

from invirt.database import *
from sys import argv, exit, stderr, stdout
from optparse import OptionParser

def main(argv):
    parser = OptionParser(usage = '%prog <owner> [options]',
            description = __doc__.strip())
    parser.add_option('-m', '--ram-total',
            type = 'int',
            dest = 'ramtotal',
            help = 'set total concurrent RAM quota')
    parser.add_option('-n', '--ram-single',
            type = 'int',
            dest = 'ramsingle',
            help = 'set single VM RAM quota')
    parser.add_option('-d', '--disk-total',
            type = 'int',
            dest = 'disktotal',
            help = 'set total disk quota')
    parser.add_option('-e', '--disk-single',
            type = 'int',
            dest = 'disksingle',
            help = 'set single VM disk quota')
    parser.add_option('-v', '--vms-total',
            type = 'int',
            dest = 'vmstotal',
            help = 'set total VM quota')
    parser.add_option('-w', '--vms-active',
            type = 'int',
            dest = 'vmsactive',
            help = 'set active VM quota')
    opts, args = parser.parse_args()

    if len(args) != 1:
        parser.print_help(stderr)
        return 1
    owner = args[0]
    connect()
    session.begin()
    
    x = Owner.query().filter_by(owner_id=owner).first()
    if x is None:
        x = Owner(owner_id=owner)

    for resource, scope in [('ram',  'total'), ('ram',  'single'),
                            ('disk', 'total'), ('disk', 'single'),
                            ('vms',  'total'), ('vms',  'active')]:
        opt = getattr(opts, resource+scope)
        if opt is not None:
            val = int(opt)
            setattr(x, resource+'_quota_'+scope, val if val >= 0 else None)

    session.commit()
    print str(x)
    return 0

if __name__ == '__main__':
    exit(main(argv))
