#!/usr/bin/perl

use strict;
use warnings;

use Sys::Filesystem;

# Umount fuse filesystems to enable quota
my $fs = Sys::Filesystem->new();
my @filesystems = $fs->filesystems();
foreach my $f (@filesystems) {
    my $mountPoint = $fs->mount_point($f);
    my $format = $fs->format($f);
    if ($format =~ m/fuse\.gvfs-fuse-daemon/) {
        system ("fusermount -u $mountPoint");
    }
}


# Add quota support to fstab. It's set up for "/home" if exists,
# otherwise we fall back to "/". Remount partition and turn quotas on

open (FD, "/etc/fstab") or die "Could not open /etc/fstab";
my @fstab = <FD>;
close (FD);

my $home = undef;
my $root = undef;
my $num = -1;
for my $line (@fstab) {
    $num++;
    my @fields = split(/[\t\s]+/, $line);
    next if ($fields[0] =~ /^#.*/);
    if ($fields[1] =~ /^\/$/) {
        $root = $num;
    } elsif ($fields[1] =~ /^\/home$/){
        $home = $num;
    }
}

my $line = $home ? $home : $root;
my $mount;
if ($line) {
    my @fields = split(/[\t\s]+/, $fstab[$line]);
    $mount = $fields[1];
    if ($fstab[$line] =~ /usrquota/) {
        print "Fstab already set up to use quotas, not overwriting...\n";
    } else {
        my $type = $fields[2];
        my $t = $fields[3];
        my $attrs = "usrquota,grpquota";
        unless ($type eq "xfs") {
            $attrs .= ",acl";
        }
        $fstab[$line] =~ s/$t/$t,$attrs/;

        open (FD, ">/etc/fstab") or die "Could not write on /etc/fstab";
        print FD @fstab;
        close (FD);

        system ("/bin/mount -o remount $mount");
    }
} else {
    print "Could not find / or /home mounting points";
    exit 1;
}

# Enable quota
system ("quotacheck -cum $mount");
system ("quotaon $mount");

exit 0;
