#!/usr/bin/python
# copyright (C) 2014 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 fcntl
import time
import sys
from optparse import OptionParser

LOGFILE = "/var/log/lxcf/lxcf-messages"

MAXJOB = 10
MULTIQUEUE_FILE="/etc/lxcf/multiqueue"

parser = OptionParser()

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

argc = len(args)

# The multiplicity is displayed when there is no argument. 
if (argc == 1):
    try:
        f = open(MULTIQUEUE_FILE, "r")
        fcntl.flock(f.fileno(), fcntl.LOCK_EX)

        multi = f.readlines()
	print multi[0]

        fcntl.flock(f.fileno(), fcntl.LOCK_UN)
        f.close()
    except:
        pass
    sys.exit(0)

if (argc != 2):
    print "usage : lxcf queue multi [NUMBER]"
    quit()

parm = args[1]

for c in parm:
    if not c.isdigit():
        print "error: The argument is not a NUMBER"
        quit()

parmnum = int(parm)

if parmnum < 0 or parmnum > MAXJOB:
    print "The multiplicity must be within ",parmnum
    quit()

try:
    f = open(MULTIQUEUE_FILE, "w")
    fcntl.flock(f.fileno(), fcntl.LOCK_EX)

    f.write(str(parmnum))

    fcntl.flock(f.fileno(), fcntl.LOCK_UN)
    f.close()
except:
    pass

t = time.asctime()

try:
    with open(LOGFILE, 'a') as fd:
        fd.write("### "+t+" Set to multiplicity : "+str(parmnum)+" ###\n")
except:
    pass

print parmnum, "is set to the multiplicity of job"

sys.exit(0)

