#!/usr/bin/env perl
# zfs-before - Virtualmin "Command to run before making changes to a server"
# and Webmin Users and Groups "Command to run before making changes".
# Creates and renames ZFS home datasets. Quotas and deletion are done by
# zfs-after, because Virtualmin only passes new quotas after a change.
# Needs zfs-home-lib.pl in the same directory.
use strict;
use warnings;
use File::Path qw(make_path);
use FindBin ();
require "$FindBin::Bin/zfs-home-lib.pl";

########################### 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/[^/]+/?$};

    if ($action eq 'CREATE_USER') {
        make_home($home);
    }
    elsif ($action eq 'MODIFY_USER') {
        my $old = $ENV{'USERADMIN_OLD_HOME'};
        move_home($old, $home) if $old && $home && $old ne $home;
    }
}

######################## Virtualmin Server Handling ############################
if (my $action = $ENV{'VIRTUALSERVER_ACTION'}) {
    # Alias domains share the parent's home directory
    exit 0 if $ENV{'VIRTUALSERVER_ALIAS'};
    my $home = $ENV{'VIRTUALSERVER_HOME'};

    if ($action eq 'CREATE_DOMAIN') {
        make_home($home);
    }
    elsif ($action eq 'MODIFY_DOMAIN') {
        # Before a change, VIRTUALSERVER_* are the old values, NEWSERVER_* the new
        my $new = $ENV{'VIRTUALSERVER_NEWSERVER_HOME'} || $home;
        move_home($home, $new) if $home && $new ne $home;
    }
}

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

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

    # Already a dataset (or an unmounted placeholder): nothing to do
    return if dataset_exists($dset);

    fail("rpool/home is not set up for the mirrored layout; run zfs-home-convert")
        unless base_ready();

    unless (ensure_parent($dset)) {
        report("Parent of $dset is not a ZFS dataset; leaving $home as a plain directory");
        return;
    }

    # Ensure the parent directory exists, owned like the domain's top folder
    my ($parent_dir) = $home =~ m{^(.+)/[^/]+$};
    if ($parent_dir && !-d $parent_dir) {
        make_path($parent_dir);
        if ($parent_dir =~ m{^(/home/[^/]+)/}) {
            my @st = stat($1);
            chown($st[4], $st[5], $parent_dir) if @st;
        }
    }

    report("Creating $dset dataset (mounted at $home) ..");

    if (-d $home) {
        # The directory already exists (Virtualmin makes it before calling us):
        # build the dataset at a staging mountpoint, copy the files in, then
        # move the dataset onto $home.
        my $tmp = "/tmp/zfs_init_$$";
        make_path($tmp);

        zfs_run('create', '-o', "mountpoint=$tmp", $dset)
            or fail("Failed to create staging dataset $dset");

        unless (system('cp', '-a', "$home/.", "$tmp/") == 0) {
            zfs_run('destroy', $dset);
            rmdir($tmp);
            fail("Failed to copy existing files from $home (exit " . ($? >> 8) . ")");
        }

        my @st = stat($home);
        if (@st) {
            chown($st[4], $st[5], $tmp);
            chmod($st[2] & 07777, $tmp);
        }

        system('rm', '-rf', '--', $home) == 0
            or fail("Failed to remove pre-created directory $home (files are safe in $dset at $tmp)");
        zfs_run('inherit', 'mountpoint', $dset)
            or fail("Failed to mount $dset at $home (files are safe in $dset at $tmp)");
        rmdir($tmp);
    }
    else {
        zfs_run('create', $dset) or fail("Failed to create $dset");
    }

    done();
}

# Rename a home's dataset to follow a renamed or moved home. A plain directory
# is left for Webmin/Virtualmin to move.
sub move_home {
    my ($old, $new) = @_;
    s{/+$}{} for $old, $new;
    my $odset = path_to_dataset($old) // return;
    my $ndset = path_to_dataset($new) // fail("Not under /home: $new");

    unless (zfs_home($old)) {
        my @inside = grep { $_ ne $odset } zfs_lines('list', '-H', '-r', '-o', 'name', $odset);
        fail("$old is not a ZFS dataset but contains datasets (@inside); move it by hand") if @inside;
        return;
    }

    fail("Cannot move $odset: $ndset already exists") if dataset_exists($ndset);
    ensure_parent($ndset) or fail("Cannot move $odset: the parent of $ndset is not a ZFS dataset");

    report("Renaming $odset to $ndset ..");
    zfs_run('rename', $odset, $ndset)
        or fail("Failed to rename $odset (files in use? stop the services using it and retry)");

    # A local mountpoint doesn't follow a rename: reset any left under the old path
    for (zfs_lines('get', '-H', '-r', '-t', 'filesystem', '-o', 'name,value,source', 'mountpoint', $ndset)) {
        my ($name, $mnt, $src) = split /\t/;
        next unless $src eq 'local' && ($mnt eq $old || index($mnt, "$old/") == 0);
        zfs_run('inherit', 'mountpoint', $name) or fail("Failed to reset the mountpoint of $name");
    }

    done();
}
