#!/usr/bin/env ensim-python

# $Id: wpsetquota.py,v 1.4 2003/10/17 00:26:13 bdeianov Exp $
# $Author: bdeianov $

# Description: A Utility to set user/group quotas on the device on which 
#               /home/virtual/ is mounted
# Depends on: quota_linux.c, quota.py
# Usage: wpsetquota -[ug] id block_size

import sys,quota
import math

from getopt import getopt,GetoptError

def usage(errstr =None):
    if errstr:
        sys.stderr.write("%s\n" % errstr)
    sys.stderr.write(\
'''
Set user/group quotas on the /home/virtual filesystem.
 Usage:  wpsetquota -[ug] id quota
 -g      id is interpreted as a group ID
 -u      id is interpreted as a user ID (ignored if -g is set)
 id      user/group ID whose quota is to be set
 quota   user/group quota in MB (1 MB is 1048576 bytes)

''')
    sys.exit(1)

if __name__ == "__main__":
    try:
        opts,args =getopt(sys.argv[1:],"ug")
    except GetoptError,e:
        usage(str(e))

    try:
        _id =int(args[0])
    except IndexError:
        usage("Missing user/group ID")

    try:
        _quota = float(args[1])
    except IndexError:
        usage("Missing quota")

    _quotacmd =quota.Q_SETQLIM

    if "-g" in [opt for (opt,val) in opts]:
        _quotatyp =quota.GRPQUOTA
    else:
        _quotatyp =quota.USRQUOTA

    # get the device on which /home/virtual is mounted
    dev =None
    try:
        dev =quota.getqcarg("/home/virtual")
    except:
        # blech -- errmsg should read "...NFS mounted filesystems..."
        sys.stdout.write("Quotas not supported (for example: quotas are not supported on NFS servers)\n")
        sys.exit(1)

    try:
        limits ={}
        limits["curspace"] = 0 # this should be ignored
        limits["bsoftlimit"] = long(math.floor(_quota * 1048576L / 1024))
        limits["bhardlimit"] = long(math.floor(_quota * 1048576L / 1024))
        limits["btime"] = 0
        limits["curinodes"] = 0 # this should be ignored
        limits["ihardlimit"] = 0
        limits["isoftlimit"] = 0
        limits["itime"] = 0
        quota.quotactl(quota.qcmd(_quotacmd,_quotatyp),dev,_id,limits)
    except OSError,o:
        sys.stderr.write("Errors while setting quota. %s\n" % str(o))
        sys.exit(1)

    # NOTE: VHQuota.pm has a few other checks that print out warning messages
    # if the quota is being overcommitted, for instance, if the limit is more 
    # than the free space available, etc. Since this doesn't affect program 
    # execution, it has been omitted, for now ...

    sys.exit(0)

