#! /usr/bin/env python3
#
# Semplice script di interrogazione di LDAP per impostare i dati 
# delle quote degli utenti
#
# Copyright (C) 2011-2023 FUSS Project <info@fuss.bz.it>
# Authors: Simone Piccardi <piccardi@truelite.it>
#               Claudio Cavalli <ccavalli@fuss.bz.it>

# 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; either version 3 of the License, or (at
# your option) any later version.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.

import ldap
from os import *
from sys import *
import re
from pathlib import Path

# Verify with the "mount" command what is the partition or folder on which the quotas 
# were enabled and if necessary enter it instead of "/dev/sda2".
mount_point = "/dev/sda2"

if len(argv) != 3:
    print("Wrong parameter number")
    print("use ./setuserquota.py soft_block_limit hard_block_limit")
    exit(1)


flags  = re.IGNORECASE|re.MULTILINE

# Get LDAP parameters from standard files
try:
    regexp = r'^\s*base\s*(.*)'
    regx   = re.compile(regexp, flags)
    path   = '/etc/ldap/ldap.conf' 
    conf   = Path(path).read_text()
    base   = regx.findall(conf)[0]
    regexp = r'^\s*uri\s*(.*)'
    regx   = re.compile(regexp, flags)
    uri    = regx.findall(conf)[0]
except Exception as e:
    print("cannot read configuration from /etc/ldap/ldap.conf")
    print(e)
    
try:
    regexp = r'masterPw="(.*)"'
    path   = '/etc/smbldap-tools/smbldap_bind.conf'
    conf   = Path(path).read_text()
    regx   = re.compile(regexp, flags)
    password = regx.findall(conf)[0]
except Exception as e:
    print("cannot read password from /etc/smbldap-tools/smbldap_bind.conf")
    print(e)
    sys.exit(1)
# LDAP connection
try: 
    l = ldap.initialize(uri)
    l.protocol_version = ldap.VERSION3
    username = "cn=admin,"+base
    l.simple_bind(username, password)
except ldap.LDAPError as e:
    print("Connection error", e)


baseDN = "ou=Users,"+base
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "uid=*"
retrieveAttributes = ["uid", "uidNumber"]

try:
    ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
    result_set = []
    count = 0
    while 1:
        result_type, result_data = l.result(ldap_result_id, 0)
        if (result_data == []):
            break
        else:
            if result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)
#    print result_set
except ldap.LDAPError as e:
    print("Search error", e)
    
if len(result_set) == 0:
    print("No Results from LDAP")
    exit(1)


for i in range(len(result_set)):
    for voce in result_set[i]:
        userid = voce[1]['uidNumber'][0]
        utente = voce[1]['uid'][0]
        if (int(userid) > 1000):
            system('/usr/sbin/setquota '+utente.decode('utf-8')+' '+argv[1]+' '+argv[2]+' 0 0 '+mount_point)
