#!/usr/bin/python
#
# @package      hubzero-mw-service
# @file         set_quotas
# @author       Rick Kennell <kennell@purdue.edu>
# @author       Nicholas J. Kisseberth <nkissebe@purdue.edu>
# @author       John Rosheck <jrosheck@purdue.edu>
# @copyright    Copyright (c) 2010-2013 HUBzero Foundation, LLC.
# @license      http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
#
# Copyright (c) 2010-2013 HUBzero Foundation, LLC.
#
# This file is part of: The HUBzero(R) Platform for Scientific Collaboration
#
# The HUBzero(R) Platform for Scientific Collaboration (HUBzero) 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, either version 3 of the License, or (at your option) any
# later version.
#
# HUBzero 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, see <http://www.gnu.org/licenses/>.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#

import sys
import os

classes={}
users={}
hub_homedir='/home'

#=============================================================================
# Load the configuration and override the variables above.
#=============================================================================
try:
  execfile('/etc/mw-service/mw-service.conf')
except IOError:
    pass

file=open("/etc/mw-service/quota.conf")
while 1:
  line=file.readline()
  if line == '':
    break;

  line=line.strip()
  try:
    line=line[0:line.index('#')]
  except:
    pass
  arr=line.split()

  if len(arr) == 0:
    continue

  if arr[0] == 'class':
    if len(arr) != 6:
      print "Error with line: %s" % line
      sys.exit(1)

    classes[arr[1]] = [ int(arr[2]), int(arr[3]), int(arr[4]), int(arr[5]) ]

  elif arr[0] == 'user':
    if len(arr) != 3:
      print "Error with line: %s" % line
      sys.exit(1)

    users[arr[1]] = arr[2]

  else:
    print "Error with line: %s" % line

#for c in classes:
#  print "class %s" % c

#for u in users:
#  print "user %s" % u


list = sys.argv
list.pop(0)
if len(list) == 0:
  list = os.listdir(hub_homedir)

for user in list:
  if user.startswith("."):
    continue

  user = user.lower()
  c='default'
  try:
    c=users[user]
  except:
    pass

  if c == 'ignore':
    continue

  info=[0,0,0,0]
  try:
    info=classes[c]
  except:
    print "Unknown class, %s, for user %s" % (c,user)
    continue

  status = os.system("setquota -a %s %d %d %d %d" % (user, info[0], info[1], info[2], info[3]))
  if status != 0:
    print "error: %s %d %d %d %d" % (user, info[0], info[1], info[2], info[3])

sys.exit(0)

