#!/usr/bin/env perl
# zfs-after - Virtualmin "Command to run after making changes to a server"
# and Webmin Users and Groups "Command to run after making changes".
# Sets quotas on ZFS home datasets and destroys a deleted home's dataset.
# Creating and renaming are done by zfs-before. Needs zfs-home-lib.pl in the
# same directory.
#
# Quotas are set here because Virtualmin only has the new values after the
# change: in the before command, NEWSERVER_QUOTA still holds the old quota.
use strict;
use warnings;
use FindBin ();
require "$FindBin::Bin/zfs-home-lib.pl";
our ($default_user_quota);

########################### Webmin / Virtualmin User Handling ##################
# Virtualmin leaves USERADMIN_* from its own user changes in the environment of
# its domain hooks, so only act on them when this is not a domain hook.
if (!$ENV{'VIRTUALSERVER_ACTION'} && (my $action = $ENV{'USERADMIN_ACTION'})) {
    my $home = $ENV{'USERADMIN_HOME'} // '';

    # Domain owners are handled by VIRTUALSERVER_ACTION
    exit 0 if $home =~ m{^/home/[^/]+/?$};

    # Webmin passes USERADMIN_QUOTA empty when it can't read the quota (as on
    # ZFS), so an empty value means "unknown", not "no quota"
    my $q = $ENV{'USERADMIN_QUOTA'} || $ENV{'USERADMIN_ZQUOTA'};

    if ($action eq 'CREATE_USER') {
        $q ||= $default_user_quota;
        set_quota($home, $q) if $q;
    }
    elsif ($action eq 'MODIFY_USER') {
        set_quota($home, $q) if $q;
    }
    elsif ($action eq 'DELETE_USER') {
        remove_home($home);
    }
}

######################## Virtualmin Server Handling ############################
if (my $action = $ENV{'VIRTUALSERVER_ACTION'}) {
    # Never let an alias touch the parent's dataset
    exit 0 if $ENV{'VIRTUALSERVER_ALIAS'};

    # After a change, VIRTUALSERVER_* hold the new values (OLDSERVER_* the old)
    my $home = $ENV{'VIRTUALSERVER_HOME'};

    if ($action eq 'CREATE_DOMAIN') {
        set_quota($home, $ENV{'VIRTUALSERVER_QUOTA'}) if $ENV{'VIRTUALSERVER_QUOTA'};
    }
    elsif ($action eq 'MODIFY_DOMAIN') {
        set_quota($home, $ENV{'VIRTUALSERVER_QUOTA'} || 'none');
    }
    elsif ($action eq 'DELETE_DOMAIN') {
        remove_home($home);
    }
}

############################## Functions #######################################

sub remove_home {
    my ($home) = @_;
    fail("No home path provided to remove_home") unless $home;
    $home =~ s{/+$}{};
    my $dset = path_to_dataset($home) // fail("Refusing to remove $home: not under /home");

    # Plain directory: Webmin/Virtualmin has already removed it
    unless (dataset_exists($dset)) {
        report("No dataset for $home; nothing to remove");
        return;
    }

    if (zfs_home($home)) {
        # Virtualmin empties the home before this runs. Files left behind mean
        # it was told to keep them, so keep the dataset too.
        if (has_files($home)) {
            report("Not destroying $dset: $home still contains files");
            return;
        }
        report("Destroying $dset with its child datasets and snapshots ..");
        zfs_run('destroy', '-r', $dset) or fail("Failed to destroy $dset");
    }
    else {
        my $p = zfs_props($dset, 'mounted', 'mountpoint');
        if ($p && $p->{mounted} eq 'yes') {
            report("Not destroying $dset: it is mounted at $p->{mountpoint}, not $home");
            return;
        }
        # Unmounted placeholder. Without -r, zfs refuses if it has child
        # datasets or snapshots, which is the check we want.
        report("Removing unmounted dataset $dset ..");
        unless (zfs_run('destroy', $dset)) {
            report("Left $dset in place: it still has child datasets or snapshots");
            return;
        }
    }

    rmdir($home) if -d $home;
    done();
}
