#!/usr/bin/python
# copyright (C) 2013 FUJITSU LIMITED All Rights Reserved

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU 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.

# -*- coding: utf-8 -*-

import sys
import os
import fcntl
import json
from optparse import OptionParser

# check root
if os.geteuid() != 0:
    print "error: Because you are not root, you cannot execute this command. "
    exit(-1)

parser = OptionParser()

(options, args) = parser.parse_args(sys.argv)

argc = len(args)

# print usage


def usage():
    print "usage : lxcf resource LXCNAME Value ..."
    quit()

if (argc < 2):
    usage()

OPS = args[1]
LXCNAME = args[2]

RESOURCEFILE = "/etc/lxcf/rsc/"+LXCNAME+"/resource.val"

# load resource json file
try:
    f = open(RESOURCEFILE, "r")
except:
    print("can't open "+LXCNAME)
    quit()

try:
    data = json.load(f)
except:
    print("resource file is destroyed, restore it.")
    os.system("/usr/lib64/lxcf/lxcf-resource1 initrsc "+LXCNAME)
    quit()

f.close()


# get resource data
flg = True

try:
    name = data['name']
except:
    pass

try:
    cpun = data['cpun']
except:
    flg = False

try:
    cpurate = data['cpurate']
except:
    flg = False

try:
    numa = data['numa']
except:
    flg = False

try:
    memlimit = data['memlimit']
except:
    flg = False

try:
    memswlimit = data['memswlimit']
except:
    flg = False

try:
    blkio_r = data['blkio_r']
except:
    flg = False

try:
    blkio_w = data['blkio_w']
except:
    flg = False

try:
    blkiops_r = data['blkiops_r']
except:
    flg = False

try:
    blkiops_w = data['blkiops_w']
except:
    flg = False

try:
    net_cls = data['net_cls']
except:
    flg = False

if flg is False:
    exit(-1)

# select OPS
if (argc == 3):
    if (OPS == "show"):
        # cat resource json file
        try:
            f = open(RESOURCEFILE, "r")
        except:
            print("can't open "+LXCNAME)
            quit()
        resfile = f.read()
        print resfile
        f.close()
    else:
        usage()
elif (argc == 4):
    if (OPS == "cpun"):
        cpun = args[3]
    elif (OPS == "cpurate"):
        cpurate = args[3]
    elif (OPS == "numa"):
        numa = args[3]
    elif (OPS == "memlimit"):
        memlimit = args[3]
    elif (OPS == "memswlimit"):
        memswlimit = args[3]
    elif (OPS == "net_cls"):
        net_cls = args[3]
    else:
        usage()
elif (argc == 5):
    if (OPS == "blkio_r"):
        blkio_r.append(args[3]+" "+args[4])
    elif (OPS == "blkio_w"):
        blkio_w.append(args[3]+" "+args[4])
    elif (OPS == "blkiops_r"):
        blkiops_r.append(args[3]+" "+args[4])
    elif (OPS == "blkiops_w"):
        blkiops_w.append(args[3]+" "+args[4])
    else:
        usage()
else:
    usage()

# save json file
f = open(RESOURCEFILE, "w")
fcntl.flock(f.fileno(), fcntl.LOCK_EX)


def print_list(list):
    """print list"""
    flg = 0
    for i in list:
        if (flg == 0):
            flg = 1
        else:
            f.write(', ')
        f.write('"'+i+'"')

f.write('{"name" : "'+name+'",\n')
f.write(' "cpun" : "'+cpun+'",\n')
f.write(' "cpurate" : "'+cpurate+'",\n')
f.write(' "numa" : "'+numa+'",\n')
f.write(' "memlimit" : "'+memlimit+'",\n')
f.write(' "memswlimit" : "'+memswlimit+'",\n')
f.write(' "blkio_r" : [ ')
print_list(blkio_r)
f.write(' ], \n')
f.write(' "blkio_w" : [')
print_list(blkio_w)
f.write(' ], \n')
f.write(' "blkiops_r" : [ ')
print_list(blkiops_r)
f.write(' ], \n')
f.write(' "blkiops_w" : [ ')
print_list(blkiops_w)
f.write(' ] ,\n')
f.write(' "net_cls" : "'+net_cls+'" }\n\n')

# unlock hosts file
fcntl.flock(f.fileno(), fcntl.LOCK_UN)

f.close()

exit(0)
