#!/bin/bash
# info: add system quota
# options: NONE
#
# The script enables filesystem quota on /home partition


#----------------------------------------------------------#
#                 Variable & Function                      #
#----------------------------------------------------------#

# Includes
source $VESTA/func/main.sh
source $VESTA/conf/vesta.conf


#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

# Checking quota package
quota=$(which --skip-alias --skip-functions quota 2>/dev/null)
if [ $? -ne 0 ]; then
    if [ -d "/etc/sysconfig" ]; then
        yum -y install quota >/dev/null 2>&1
        check_result $? "quota package installation failed" $E_UPDATE
    else
        export DEBIAN_FRONTEND=noninteractive
        apt-get -y install quota >/dev/null 2>&1
        check_result $? "quota package installation failed" $E_UPDATE
    fi
fi


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Adding group and user quota on /home partition
mnt=$(df -P /home | awk '{print $6}' | tail -n1)
lnr=$(cat -n /etc/fstab | grep -v "#" | awk '{print $1,$3}' | grep "$mnt$" | cut -f 1 -d ' ')
opt=$(sed -n ${lnr}p /etc/fstab | awk '{print $4}')
fnd='usrquota\|grpquota\|usrjquota=aquota.user\|grpjquota=aquota.group\|jqfmt=vfsv0'
if [ $(echo $opt | tr ',' '\n' | grep -x $fnd | wc -l) -ne 5 ]; then
    old=$(echo $(echo $opt | tr ',' '\n' | grep -v 'usrquota\|grpquota\|usrjquota=\|grpjquota=\|jqfmt=') | tr ' ' ',')
    new='usrquota,grpquota,usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0'
    sed -i "$lnr s/$opt/$old,$new/" /etc/fstab
    mount -o remount $mnt
fi

# Adding v2 group and user quota index
if [ ! -e "$mnt/aquota.user" ] || [ ! -e "$mnt/aquota.group" ]; then
    quotacheck -avcugm >/dev/null 2>&1
fi

# Adding quotacheck on reboot
touch /forcequotacheck

# Adding cron job
echo '#!/bin/bash' > /etc/cron.daily/quotacheck
echo 'touch /forcequotacheck' >> /etc/cron.daily/quotacheck
chmod a+x /etc/cron.daily/quotacheck

# Enabling group and user quota
if [ ! -z "$(quotaon -pa | grep " $mnt " | grep 'user\|group' | grep 'is off')" ]; then
    quotaon -v $mnt
    check_result $? "quota can't be enabled in $mnt" $E_DISK
fi

# Updating vesta.conf value
if [ -z "$(grep DISK_QUOTA $VESTA/conf/vesta.conf)" ]; then
    echo "DISK_QUOTA='yes'" >> $VESTA/conf/vesta.conf
else
    sed -i "s/DISK_QUOTA=.*/DISK_QUOTA='yes'/g" $VESTA/conf/vesta.conf
fi

# Rebuilding user quota
for user in $(ls $VESTA/data/users); do
    $BIN/v-update-user-quota $user
done


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

# Logging
log_event "$OK" "$ARGUMENTS"

exit
