#!/usr/bin/perl

# 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 $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\n";
        exit 0;
    } 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/;
    }
} else {
    print "Could not find / or /home mounting points";
    exit 1;
}

open(FD, ">/etc/fstab") or die "Could not write on /etc/fstab";
print FD @fstab;
close(FD);
system("/bin/mount -o remount $mount");
exit 0;
