#!/bin/bash

#Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
#
#Licensed under CLOUD LINUX LICENSE AGREEMENT
#http://cloudlinux.com/docs/LICENSE.TXT

if [[ -z "$1" ]]; then
    echo 'Specify action (on|off|off_fake)'
    exit 1;
fi

if [[ "$1" = "on" ]]; then
    if [  -f /usr/sbin/repquota_is_off ]; then
        echo "Fake switching on quotas..."
        mv /usr/sbin/repquota /usr/sbin/repquota_fake
        mv /usr/sbin/repquota_real /usr/sbin/repquota
        mv /usr/sbin/repquota_is_off /usr/sbin/repquota_is_on
        cl-quota -YC
        echo "Quotas is switched on"
        exit 0
    elif [[ -f /usr/sbin/repquota ]] && [[ $(repquota -nva) != "" ]]; then
        echo 'Quota have been switched on already'
        exit 0
    else
        echo 'Real switching on quotas...'
        mount -o remount,defaults,usrquota,grpquota /
        quotacheck -ugmv /
        quotaon -ugv /
        cl-quota -YC
        if [ -f /etc/init.d/psa ]; then
            /etc/init.d/psa restart
        fi
        echo "Quatas is switched on"
        exit 0
    fi
elif [[ "$1" = "off" ]]; then
    quotaoff -ugv /
    rm -f /aquota.*
    cl-quota -YC
    rm -f /usr/sbin/repquota_fake
    rm -f /usr/sbin/repquota_is_on
    rm -f /usr/sbin/repquota_is_off
    echo "Quotas is switched off...reboot..."
    reboot
elif [[ "$1" = "off_fake" ]]; then
    echo "Fake switching off quotas..."
    if [[ ! -f /usr/sbin/repquota ]] || [[ $(repquota -nva) == "" ]]; then
        echo 'Quota have been switched off already'
        exit 0
    elif [  -f /usr/sbin/repquota_is_on ]; then
        mv /usr/sbin/repquota /usr/sbin/repquota_real
        mv /usr/sbin/repquota_fake /usr/sbin/repquota
        mv /usr/sbin/repquota_is_on /usr/sbin/repquota_is_off
        echo "Quotas is switched off"
        exit 0
    else
        mv /usr/sbin/repquota /usr/sbin/repquota_real
        cat >/usr/sbin/repquota <<-EOF
#!/bin/bash

exit 0
EOF
        chmod +x /usr/sbin/repquota
        touch /usr/sbin/repquota_is_off
        echo "Quatas is switched off"
        exit 0
    fi
else
    echo 'Specify correct action (on|off|off_fake)'
fi
