#!/bin/bash
# info: delete system quota
# options: NONE
#
# example: v-delete-sys-quota
#
# This function disables filesystem quota on /home partition

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Deleting 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=\|grpjquota=\|jqfmt='
if [ -n "$(echo $opt | grep $fnd)" ]; then
	rep=$(echo $(echo $opt | tr ',' '\n' | grep -v $fnd) | tr ' ' ',')
	sed -i "$lnr s/$opt/$rep/" /etc/fstab
	systemctl daemon-reload
	mount -o remount "$mnt"
fi

# Disabling group and user quota
if quotaon="$(type -P quotaon 2> /dev/null)" && quotaoff="$(type -P quotaoff 2> /dev/null)"; then
	if "${quotaon}" -pa | grep " $mnt " | grep 'user\|group' | grep -q 'is on' &> /dev/null; then
		"$quotaoff" "$mnt"
	fi
fi

# Deleting v1 + v2 group and user quota index
for idx in quota.user quota.group aquota.user aquota.group; do
	[ -e "$mnt/$idx" ] && rm -f "$mnt/$idx"
done

# Deleting cron job and forcequotacheck
if [[ -f "/etc/cron.daily/quotacheck" ]]; then
	rm -f "/etc/cron.daily/quotacheck"
fi
if [[ -f "/forcequotacheck" ]]; then
	rm -f "/forcequotacheck"
fi

# Updating hestia.conf value
$BIN/v-change-sys-config-value "DISK_QUOTA" "no"

# Remove quota package
apt-get -y purge quota > /dev/null 2>&1

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

# Logging
$BIN/v-log-action "system" "Info" "Plugins" "System Quota Enforcement disabled."
log_event "$OK" "$ARGUMENTS"

exit
