#!/usr/bin/env perl
# zfs-home-convert - convert plain-directory homes to ZFS datasets in the
# layout used by the zfs-before and zfs-after hooks, so that a server
# set up before the hooks (or with a mix of directories and datasets) ends up
# as if the hooks had created every home. Homes that are already datasets are
# left alone, so it can be run again at any time.
#
#   zfs-home-convert                          dry run: show what would be done
#   zfs-home-convert --apply                  do it
#   --levels=owners,subservers,mailboxes      which homes (default: all)
#   --home=/home/example                      only this home and those under it
#                                             (repeatable)
#   --undo-dir=/root                          where the undo script goes
#   --check [--verbose]                       read-only: report anything that
#                                             doesn't add up (see below)
#
# Homes come from Virtualmin's domain list (not aliases) and from /etc/passwd
# (UID 1000 and up), and must be under /home:
#   owners      /home/<name>
#   subservers  /home/<owner>/domains/<domain>
#   mailboxes   /home/<owner>/homes/<user>, /home/<owner>/domains/<d>/homes/<user>
#
# First, if needed, the base dataset (rpool/home in zfs-home-lib.pl) is created
# or given mountpoint=/home. A base already mounted at /home is used as it is;
# otherwise it gets canmount=off, after setting canmount=off on any dataset
# that would otherwise start mounting.
#
# Then for each home, parents first:
#   1. create the dataset (canmount=off) and any domains/homes container
#   2. move the directory aside to .<name>.pre-zfs-<time> next to it
#   3. mount the dataset at the home and copy the files in (cp -ax)
#   4. compare the file counts, copy immutable/append-only flags across
#   5. remount any datasets that were already mounted inside
# Any failure before the copy is complete puts everything back and stops the
# run. The old directories are kept for you to check and delete; an undo
# script is written. Stop the services using the homes first (web server,
# PHP-FPM, mail, FTP): a process with files open in a home keeps writing to the
# old copy. The script refuses homes that are in use.
#
# --check changes nothing. It lists datasets with a quota that aren't mounted
# (so the quota does nothing), datasets that should be mounted and aren't,
# unmounted datasets or containers holding data, homes that are still plain
# directories, and leftover .pre-zfs- copies. It prints nothing and exits 0
# when all is well (--verbose prints a summary anyway), so it suits cron.
use strict;
use warnings;
use FindBin ();
use Getopt::Long qw(GetOptions);
use File::Find ();
use POSIX qw(strftime);
require "$FindBin::Bin/zfs-home-lib.pl";
our ($pool, $base, $zfs);

my %opt = (
    levels       => 'all',
    'undo-dir'   => '/root',
    passwd       => '/etc/passwd',
    'vm-domains' => '/etc/webmin/virtual-server/domains',
    'min-uid'    => 1000,
);
my @only;
GetOptions(\%opt, 'apply', 'check', 'verbose', 'levels=s', 'home=s' => \@only, 'undo-dir=s', 'zfs=s' => \$zfs,
           'passwd=s', 'vm-domains=s', 'min-uid=i')
    or die "Usage: $0 [--apply] [--check [--verbose]] [--levels=owners,subservers,mailboxes] [--home=/home/x ...] [--undo-dir=/root]\n";
die "--check and --apply don't go together\n" if $opt{check} && $opt{apply};
my $apply = $opt{apply};
die "Run as root\n" if $apply && $> != 0;

my %levels = map { $_ => 1 }
    $opt{levels} eq 'all' ? qw(owners subservers mailboxes) : split /,/, $opt{levels};
for (keys %levels) { die "Unknown level: $_\n" unless /^(owners|subservers|mailboxes)$/ }
s{/+$}{} for @only;

my $data_warn = 1024 * 1024;   # an unmounted dataset holding more than this is left alone
my $stamp     = strftime('%Y%m%d-%H%M%S', localtime);
my $undo_file = "$opt{'undo-dir'}/zfs-home-undo-convert-$stamp-$$.sh";
my (@undo, %planned);

exit(check() ? 0 : 1) if $opt{check};

############################## Base dataset ####################################
my @base_steps = plan_base();
if (@base_steps) {
    print "Base dataset:\n";
    print "    zfs @{ $_->[0] }\n" for @base_steps;
    print "\n";
}
my $base_pending = @base_steps && !$apply;
if ($apply && @base_steps) {
    for (@base_steps) {
        my ($cmd, $undo) = @$_;
        zfs_run(@$cmd) or die "Failed: zfs @$cmd\n";
        push @undo, $undo ? [[$zfs, @$undo]]
                          : [["# $base was created by this run; zfs destroy -r $base removes it and everything in it"]];
        write_undo();
    }
}

############################## Homes ###########################################
my @homes = find_homes();
unless (@homes) {
    print "No homes found to look at.\n";
    exit 0;
}

my (@done, @skipped, $stopped);
for my $home (@homes) {
    my ($plan, $why, $already) = evaluate($home);
    if (!$plan) {
        if ($already) { print "$home: already a dataset\n" }
        else          { print "$home: SKIPPED: $why\n"; push @skipped, $home }
        next;
    }
    print_plan($plan);
    unless ($apply) {
        $planned{$_} = 1 for $plan->{dset}, @{ $plan->{containers} };
        next;
    }

    my ($ok, $fatal) = convert($plan);
    if ($ok) { push @done, $plan }
    elsif ($fatal) { $stopped = 1; last }
    else { push @skipped, $home }
}

############################## Summary #########################################
print "\n";
unless ($apply) {
    print "Dry run: nothing changed. Stop the services using these homes, then run again with --apply.\n";
    exit 0;
}
if (@done) {
    print "Converted ", scalar(@done), " home(s). Check them, then remove the old copies:\n";
    print "    rm -rf '$_->{old}'\n" for @done;
}
print "Skipped: @skipped\n" if @skipped;
print "STOPPED after a failure (see above); everything for that home was put back.\n" if $stopped;
print "Undo script: $undo_file\n" if @undo;
exit($stopped ? 1 : 0);

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

sub plan_base {
    my %s = read_state();
    my $b = $s{$base};
    if (!$b) {
        die "Pool dataset $pool not found\n" unless dataset_exists($pool);
        return ([['create', '-o', 'canmount=off', '-o', 'mountpoint=/home', $base], undef]);
    }
    return () if $b->{mp} eq '/home';
    die "$base is mounted at $b->{mp}; expected /home or unmounted\n" if $b->{mounted} eq 'yes';

    # Datasets that inherit their mountpoint through the base would start
    # mounting under /home: keep them unmounted
    my @steps;
    for my $n (sort keys %s) {
        next if $n eq $base;
        my $d = $s{$n};
        next unless $d->{src} eq "inherited from $pool" || $d->{src} eq "inherited from $base";
        die "$n is mounted at $d->{mp} and would move; sort it out by hand first\n" if $d->{mounted} eq 'yes';
        push @steps, [['set', 'canmount=off', $n], ['set', "canmount=$d->{canmount}", $n]]
            if $d->{canmount} ne 'off';
    }
    push @steps, [['set', 'canmount=off', $base], ['set', "canmount=$b->{canmount}", $base]]
        if $b->{canmount} ne 'off';
    push @steps, [['set', 'mountpoint=/home', $base],
                  $b->{src} eq 'local' ? ['set', "mountpoint=$b->{mp}", $base] : ['inherit', 'mountpoint', $base]];
    return @steps;
}

sub read_state {
    my %s;
    for (zfs_lines('list', '-H', '-p', '-r', '-t', 'filesystem',
                   '-o', 'name,mountpoint,canmount,mounted,referenced,quota', $base)) {
        my ($n, $mp, $cm, $m, $ref, $q) = split /\t/;
        $s{$n} = { mp => $mp, canmount => $cm, mounted => $m, ref => $ref, quota => $q, src => '' };
    }
    for (zfs_lines('get', '-H', '-r', '-t', 'filesystem', '-o', 'name,source', 'mountpoint', $base)) {
        my ($n, $src) = split /\t/;
        $s{$n}{src} = $src if $s{$n};
    }
    return %s;
}

sub level_of {
    my ($h) = @_;
    return 'owners'     if $h =~ m{^/home/[^/]+$};
    return 'subservers' if $h =~ m{^/home/[^/]+/domains/[^/]+$};
    return 'mailboxes'  if $h =~ m{^/home/[^/]+(?:/domains/[^/]+)?/homes/[^/]+$};
    return undef;
}

# Homes to look at, parents before children
sub find_homes {
    my %h;
    if (opendir(my $dh, $opt{'vm-domains'})) {
        for my $f (grep { /^\d+$/ } readdir $dh) {
            open(my $fh, '<', "$opt{'vm-domains'}/$f") or next;
            my %d = map { chomp; split /=/, $_, 2 } grep { /=/ } <$fh>;
            close($fh);
            next if $d{alias} || ($d{dir} // 1) eq '0' || !$d{home};
            $h{ $d{home} } = 1;
        }
        closedir($dh);
    }
    if (open(my $fh, '<', $opt{passwd})) {
        while (<$fh>) {
            my (undef, undef, $uid, undef, undef, $home) = split /:/;
            next unless defined $home && $uid =~ /^\d+$/ && $uid >= $opt{'min-uid'};
            $h{$home} = 1;
        }
        close($fh);
    }
    my @h;
    for my $home (keys %h) {
        $home =~ s{/+$}{};
        my $level = level_of($home) or next;
        next unless $levels{$level};
        next if @only && !grep { $home eq $_ || index($home, "$_/") == 0 } @only;
        next unless -e $home;
        push @h, $home;
    }
    return sort { ($a =~ tr{/}{}) <=> ($b =~ tr{/}{}) || $a cmp $b } @h;
}

# A plan for converting one home, or (undef, reason[, already-done])
sub evaluate {
    my ($home) = @_;
    my $dset = path_to_dataset($home) // return (undef, 'not under /home');
    return (undef, '', 1) if zfs_home($home);
    return (undef, 'is a symlink') if -l $home;
    return (undef, 'is not a directory') unless -d $home;
    (my $pdir = $home) =~ s{/[^/]+$}{};
    my @hs = stat($home);
    return (undef, 'is already a mountpoint of another filesystem') if $hs[0] != (stat($pdir))[0];

    my %plan = (home => $home, dset => $dset, containers => [], kids => [], mode => \@hs);
    my $p = zfs_props($dset, 'mountpoint', 'mounted', 'canmount', 'referenced', 'available');
    if ($p) {
        return (undef, "$dset exists and is mounted at $p->{mountpoint}") if $p->{mounted} eq 'yes';
        return (undef, "$dset exists but would mount at $p->{mountpoint}")
            if $p->{mountpoint} ne $home && !$base_pending;
        return (undef, sprintf('%s exists and already holds %s; inspect it first', $dset, human($p->{referenced})))
            if $p->{referenced} > $data_warn;
        $plan{exists}   = 1;
        $plan{canmount} = $p->{canmount};
        $plan{kids} = [ grep { $_ ne $dset } map {
            my ($n, $m, $mp) = split /\t/; ($m eq 'yes' && index($mp, "$home/") == 0) ? $n : ()
        } zfs_lines('list', '-H', '-r', '-t', 'filesystem', '-o', 'name,mounted,mountpoint', $dset) ];
    }

    # The parent must be a dataset (or about to be). "domains" and "homes"
    # levels are containers, created when missing; above them must be a home
    # that is a dataset.
    my $q = parent_dataset($dset);
    while ($q ne $base) {
        my ($leaf) = $q =~ m{/([^/]+)$};
        if ($leaf eq 'domains' || $leaf eq 'homes') {
            unshift @{ $plan{containers} }, $q unless $planned{$q} || dataset_exists($q);
            $q = parent_dataset($q);
            next;
        }
        my $up = '/home' . substr($q, length $base);
        return (undef, "$up is not a ZFS dataset (convert it first, or include its level)")
            unless $planned{$q} || zfs_home($up);
        last;
    }

    # Nothing else may be mounted inside, other than our own child datasets
    my %kid_mp = map { (zfs_props($_, 'mountpoint') || {})->{mountpoint} // '' => 1 } @{ $plan{kids} };
    my @foreign = grep { !$kid_mp{$_} } mounts_under($home);
    return (undef, "other filesystems are mounted inside: @foreign") if @foreign;

    $plan{used} = du_bytes($home);
    return (undef, 'cannot measure it with du') unless defined $plan{used};
    my $avail = $p ? $p->{available} : available_near($dset);
    $plan{avail} = $avail;
    return (undef, sprintf('needs %s but only %s is available to %s', human($plan{used}), human($avail), $dset))
        if defined $avail && $plan{used} > $avail;

    $plan{busy} = [ procs_using($home) ];
    return (undef, "in use by @{ $plan{busy} }; stop those first") if $apply && @{ $plan{busy} };

    (my $name = $home) =~ s{.*/}{};
    $plan{old} = "$pdir/.$name.pre-zfs-$stamp";
    return (undef, "$plan{old} already exists") if -e $plan{old};
    return \%plan;
}

sub print_plan {
    my ($p) = @_;
    printf "%s: convert to %s (%s to copy%s)\n", $p->{home}, $p->{dset}, human($p->{used}),
        defined $p->{avail} ? ', ' . human($p->{avail}) . ' available' : '';
    print "    zfs create -o canmount=off $_\n" for @{ $p->{containers} };
    print "    zfs create -o canmount=off $p->{dset}\n" unless $p->{exists};
    print "    zfs unmount $_\n" for reverse @{ $p->{kids} };
    print "    mv $p->{home} $p->{old}\n";
    print "    zfs set canmount=on $p->{dset}   (mounts it at $p->{home})\n";
    print "    cp -ax $p->{old}/. $p->{home}/\n";
    print "    zfs mount $_\n" for @{ $p->{kids} };
    print "    NOTE: in use by @{ $p->{busy} }; stop those before --apply\n" if @{ $p->{busy} };
}

# Returns (ok, fatal). Not ok and not fatal: skipped with nothing changed.
sub convert {
    my ($p) = @_;
    my ($home, $dset, $old) = @$p{qw(home dset old)};
    my $snap = "$dset\@zfs-home-convert";
    my (@made, @down);

    my $unmake = sub { zfs_run('destroy', '-r', $_) for reverse @made };
    my $remount = sub { for (@_) { zfs_run('mount', $_) or print "    could not remount $_\n" } };
    my $skip = sub { print "    SKIPPED: $_[0]\n"; return (0, 0) };

    for my $c (@{ $p->{containers} }, $p->{exists} ? () : $dset) {
        next if dataset_exists($c);
        if (zfs_run('create', '-o', 'canmount=off', $c)) { push @made, $c; next }
        $unmake->();
        return $skip->("cannot create $c");
    }
    my $m = zfs_props($dset, 'mountpoint', 'available');
    unless ($m && $m->{mountpoint} eq $home) {
        $unmake->();
        return $skip->("$dset would mount at " . ($m ? $m->{mountpoint} : '?') . ", not $home");
    }
    if ($p->{used} > $m->{available}) {
        $unmake->();
        return $skip->(sprintf('needs %s but only %s is available', human($p->{used}), human($m->{available})));
    }

    zfs_run('snapshot', $snap) or do { $unmake->(); return $skip->("cannot snapshot $dset") };
    for my $k (reverse @{ $p->{kids} }) {
        if (zfs_run('unmount', $k)) { unshift @down, $k; next }
        $remount->(@down);
        zfs_run('destroy', $snap);
        $unmake->();
        return $skip->("cannot unmount $k (in use?)");
    }
    unless (rename($home, $old)) {
        my $err = $!;
        $remount->(@down);
        zfs_run('destroy', $snap);
        $unmake->();
        return $skip->("cannot move $home aside: $err");
    }

    # From here on, a failure puts everything back and stops the run
    my $rollback = sub {
        print "    FAILED: $_[0]; putting everything back\n";
        zfs_run('unmount', $dset) if is_mounted($dset);
        if (grep { $_ eq $dset } @made) {
            $unmake->();
        }
        else {
            zfs_run('set', "canmount=$p->{canmount}", $dset);
            zfs_run('rollback', $snap);
            zfs_run('destroy', $snap);
            $unmake->();
        }
        rmdir($home) if -d $home;
        if (-e $home)                { print "    $home could not be cleared; your files are safe in $old\n" }
        elsif (rename($old, $home)) { $remount->(@down) }
        else                         { print "    could not move $old back to $home: $!\n" }
        return (0, 1);
    };

    zfs_run('set', 'canmount=on', $dset) or return $rollback->('cannot set canmount=on');
    is_mounted($dset) or zfs_run('mount', $dset) or return $rollback->("cannot mount $dset");
    my $chk = zfs_props($dset, 'mountpoint', 'mounted');
    return $rollback->("$dset is not mounted at $home")
        unless $chk && $chk->{mounted} eq 'yes' && $chk->{mountpoint} eq $home;

    system('cp', '-ax', "$old/.", "$home/") == 0
        or return $rollback->('copy failed (exit ' . ($? >> 8) . ')');
    my @hs = @{ $p->{mode} };
    chown($hs[4], $hs[5], $home);
    chmod($hs[2] & 07777, $home);

    my ($n_old, $n_new) = (count_entries($old), count_entries($home));
    return $rollback->("copied $n_new entries but the original has $n_old") unless $n_old == $n_new;

    my @flagged = copy_flags($old, $home);

    my @failed = grep { !zfs_run('mount', $_) } @down;
    zfs_run('destroy', $snap);

    push @undo, [
        ["# $home"],
        (map { [$zfs, 'unmount', $_] } reverse @down),
        [$zfs, 'unmount', $dset],
        [$zfs, 'set', 'canmount=' . ($p->{exists} ? $p->{canmount} : 'off'), $dset],
        ['rmdir', $home],
        ['mv', $old, $home],
        (map { [$zfs, 'mount', $_] } @down),
    ];
    write_undo();

    print "    done", (@flagged ? '; immutable/append-only flags copied: ' . scalar(@flagged) : ''), "\n";
    print "    COULD NOT REMOUNT: @failed (run: zfs mount -a)\n" if @failed;
    return (1, 0);
}

# Read-only health check. Returns true if nothing needs attention.
sub check {
    my @warn;
    my $w = sub { push @warn, sprintf("%-46s %s", @_) };
    my %s = read_state();
    my $b = $s{$base};

    if (!$b) {
        $w->($base, 'does not exist; the hooks need it (run zfs-home-convert to create it)');
    }
    elsif ($b->{mp} ne '/home') {
        $w->($base, "has mountpoint $b->{mp}; the hooks need /home");
    }
    elsif ($b->{canmount} eq 'on' && $b->{mounted} ne 'yes') {
        $w->($base, 'canmount=on but not mounted at /home');
    }

    for my $n (sort keys %s) {
        next if $n eq $base;
        my $d = $s{$n};
        my ($leaf) = $n =~ m{/([^/]+)$};
        my $container = $leaf eq 'domains' || $leaf eq 'homes';
        my $mirror = '/home' . substr($n, length $base);
        next if @only && !grep { $mirror eq $_ || index($mirror, "$_/") == 0 } @only;

        if ($d->{mounted} ne 'yes') {
            $w->($n, sprintf('quota %s is not enforced: not mounted', human($d->{quota}))) if $d->{quota};
            $w->($n, "canmount=on but not mounted (should be at $d->{mp})")
                if $d->{canmount} eq 'on' && $d->{mp} ne 'none' && $d->{mp} ne 'legacy';
            $w->($n, sprintf('holds %s but is not mounted: hidden data, inspect it', human($d->{ref})))
                if $d->{ref} > $data_warn;
            if (!$container && ($d->{canmount} ne 'on' || $d->{mp} eq 'none') && !$d->{quota}) {
                $w->($n, -d $mirror ? "placeholder: not mounted, and $mirror is a plain directory"
                                    : "placeholder for $mirror, which doesn't exist (left from a deleted home?)");
            }
        }
        elsif ($d->{mp} ne $mirror) {
            push @warn, sprintf("%-46s %s", $n, "mounted at $d->{mp}, outside the layout (left alone)")
                if $opt{verbose};
        }
    }

    # Homes that are still plain directories (only when the base is usable)
    my $plain = 0;
    if ($b && $b->{mp} eq '/home') {
        for my $home (find_homes()) {
            next if zfs_home($home) || !-d $home || -l $home;
            $w->($home, 'plain directory (zfs-home-convert --home=' . $home . ' converts it)');
            $plain++;
        }
    }

    # Leftover copies from conversions
    my @left;
    File::Find::find({ no_chdir => 1, wanted => sub {
        my $depth = ($File::Find::name =~ tr{/}{}) - 1;
        if (-d $_ && m{/\.[^/]+\.pre-zfs-\d{8}-\d{6}$}) {
            push @left, $File::Find::name;
            $File::Find::prune = 1;
        }
        $File::Find::prune = 1 if $depth >= 5;
    } }, '/home') if -d '/home';
    for (sort @left) {
        (my $orig = $_) =~ s{/\.([^/]+)\.pre-zfs-\d{8}-\d{6}$}{/$1};
        next if @only && !grep { $orig eq $_ || index($orig, "$_/") == 0 } @only;
        my $size = du_bytes($_);
        $w->($_, 'old copy left by a conversion' . (defined $size ? ' (' . human($size) . ')' : '')
                 . "; rm -rf it once you've checked the new home");
    }

    if (@warn) {
        print "$_\n" for @warn;
    }
    elsif ($opt{verbose}) {
        printf "All good: %d datasets under %s, no plain homes, no leftover copies.\n",
            scalar(keys %s), $base;
    }
    return !grep { !/outside the layout/ } @warn;
}

sub is_mounted { my $p = zfs_props($_[0], 'mounted'); return $p && $p->{mounted} eq 'yes' }

# Space available to a dataset that doesn't exist yet: that of its nearest existing ancestor
sub available_near {
    my ($d) = @_;
    while ($d =~ m{/}) {
        $d = parent_dataset($d);
        my $p = zfs_props($d, 'available');
        return $p->{available} if $p;
    }
    return undef;
}

sub du_bytes {
    my ($dir) = @_;
    open(my $fh, '-|', 'du', '-sxB1', '--', $dir) or return undef;
    my $line = <$fh>;
    close($fh);
    return (defined $line && $line =~ /^(\d+)/) ? $1 : undef;
}

sub count_entries {
    my ($dir) = @_;
    my $n = 0;
    File::Find::find({ no_chdir => 1, wanted => sub { $n++ } }, $dir);
    return $n;
}

# Filesystems mounted below $dir
sub mounts_under {
    my ($dir) = @_;
    open(my $fh, '<', '/proc/self/mounts') or return ();
    my @m;
    while (<$fh>) {
        my (undef, $mp) = split ' ';
        $mp =~ s/\\(\d{3})/chr(oct($1))/ge;
        push @m, $mp if index($mp, "$dir/") == 0;
    }
    close($fh);
    return @m;
}

# Processes with their working directory or an open file under $dir
sub procs_using {
    my ($dir) = @_;
    my %p;
    opendir(my $dh, '/proc') or return ();
    for my $pid (grep { /^\d+$/ && $_ != $$ } readdir $dh) {
        my @links = ("/proc/$pid/cwd");
        if (opendir(my $fd, "/proc/$pid/fd")) {
            push @links, map { "/proc/$pid/fd/$_" } grep { /^\d+$/ } readdir $fd;
            closedir($fd);
        }
        for (@links) {
            my $t = readlink($_) // next;
            next unless $t eq $dir || index($t, "$dir/") == 0;
            my $comm = '?';
            if (open(my $c, '<', "/proc/$pid/comm")) { chomp($comm = <$c> // '?'); close($c) }
            $p{$pid} = $comm;
            last;
        }
    }
    closedir($dh);
    return map { "$p{$_}($_)" } sort { $a <=> $b } keys %p;
}

# Copy immutable (i) and append-only (a) flags from the old tree to the new
# one, and clear them on the old copy so it can be deleted
sub copy_flags {
    my ($old, $new) = @_;
    my @flagged;
    open(my $fh, '-|', 'lsattr', '-Ra', '--', $old) or return ();
    while (<$fh>) {
        chomp;
        next unless m{^([-a-zA-Z]+) (/.*)$};
        my ($flags, $path) = ($1, $2);
        next if $path =~ m{/\.\.?$} || $flags !~ /[ia]/;
        push @flagged, [$flags, $path];
    }
    close($fh);
    for (@flagged) {
        my ($flags, $path) = @$_;
        my $target = $new . substr($path, length $old);
        my @set = (($flags =~ /i/ ? '+i' : ()), ($flags =~ /a/ ? '+a' : ()));
        system('chattr', @set, '--', $target) == 0 or print "    could not set @set on $target\n";
        system('chattr', '-i', '-a', '--', $path);
    }
    return @flagged;
}

sub sh_quote { my ($s) = @_; $s =~ s/'/'\\''/g; return "'$s'" }

sub write_undo {
    open(my $fh, '>', $undo_file) or do { warn "Cannot write $undo_file: $!\n"; return };
    print $fh "#!/bin/sh\n# Reverses zfs-home-convert, newest step first. Datasets it created are\n",
              "# left in place, unmounted; remove them with zfs destroy -r if not wanted.\nset -e\n";
    # Blocks newest first; the steps inside a block in order
    for my $block (reverse @undo) {
        for (@$block) {
            my @c = @$_;
            print $fh @c == 1 && $c[0] =~ /^#/ ? "$c[0]\n" : join(' ', map { sh_quote($_) } @c) . "\n";
        }
    }
    close($fh);
    chmod(0700, $undo_file);
}

sub human {
    my ($n) = @_;
    for my $u ('B', 'K', 'M', 'G', 'T') {
        return sprintf($u eq 'B' ? '%d%s' : '%.1f%s', $n, $u) if $n < 1024;
        $n /= 1024;
    }
    return sprintf('%.1fP', $n);
}
