#!/usr/bin/perl
# realadm-updater: update this host's realadm trees file by file (realed2/realadm#6).
# A client on a1 or a dev machine runs it over ssh, through the host's channel socket when
# there is one, as root through sudo: a person under their own login, or automation as the
# remote user, whose key runs only this.  Through sudo it takes no arguments.  The request
# is one JSON document on stdin; the result is one on stdout, {"ok": ...} or {"err": "..."},
# and the exit status is 0 or 1 to match.
#
# The trees are fixed here, never named by path in a request:
#
#   realadm        /usr/local/realadm, root's, but for what realadm keeps in var/ as it
#                  runs: only var/man, var/postinstall, and var/services are the tree's
#   realadm-steps  /usr/local/realadm/lib/step, root's: a part of realadm
#   systemd        /etc/systemd/system, root's, but only realadm's units: those named in
#                  /usr/local/realadm/var/services or in the tree's expected state, and
#                  new *.service and *.timer files a request adds
#   site-steps     /home/aia/<site>/lib/step, the site's user's (<site> from this host's
#                  gsrv record, as realadm's libexec/nightly finds it)
#
# Operations (the request's op):
#
#   manifest     {files: {path: {sha256, mode, size, owner, group}}, dirs: {path: mode},
#                 other: [path...], version, realadm}
#   apply        replace, add, and delete files in one or more trees; see apply()
#   postinstall  run realadm's var/postinstall; see postinstall()
#   confirm      disarm the dead-man of an update that restarted remote-shim
#   rollback     undo the update the request's id names, or the newest one applied
#   history      the updates kept, newest first
#   verify       compare each tree with the state its last full update expected
#   selftest     check and answer
#
# An apply is journaled under /var/lib/realadm-updater/<id>: the files it replaces or deletes
# are copied there first, and an apply that stops part way is undone the next time this
# runs.  It uses only Perl's own modules and nothing from /usr/local/realadm, so it can
# replace any part of realadm, whatever state that is in.
#
# An apply that asks to restart remote-shim first arms a dead-man: a systemd timer that
# runs "realadm-updater --deadman <id>" (as root, not through sudo, so with an argument),
# which rolls the update back and restarts the shim again, unless a confirm for the update
# comes first.  The client confirms once the channel answers through the new shim.
#
# Run by a user other than root, with REALADM_UPDATER_ROOT set, every path is under that
# directory, nothing is chowned to another user, and the dead-man and shim restarts are
# files in the journal: the tests do this.

use v5.24;
use strict;
use warnings;
use Digest::SHA;
use Fcntl qw(:flock S_ISREG S_ISDIR S_IMODE);
use File::Basename;
use File::Copy ();
use File::Path ();
use Time::HiRes ();
use JSON::PP;
use MIME::Base64 ();
use POSIX ();

$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
delete @ENV{qw(PERL5LIB PERLLIB PERL5OPT)};
# Nothing it makes is group- or world-writable, whatever umask sudo or ssh gave it.
umask 022;

use constant {
    keep    => 10,      # the applied updates kept, for rollback
    progversion => '1.1',
    unitre  => qr/\A[\w@.-]+\.(?:service|timer)\z/,
};

# Under test, everything is under $test; for real, this runs only as root.
my $test = $< != 0 ? $ENV{REALADM_UPDATER_ROOT} : undef;
defined $test or $< == 0 && $> == 0 or die "realadm-updater: run as root, through sudo\n";
$test //= '';
my $vardir = "$test/var/lib/realadm-updater";
my $json = JSON::PP->new->canonical;

# The trees: name => {root, user, accept (a path a request may name), list (a path the
# manifest shows, when not every accepted one), flat (no subdirectories), noversion}.
sub trees {
    my $ra = "$test/usr/local/realadm";
    my %t = (
        realadm => {root => $ra, user => 'root',
                    accept => sub { $_[0] !~ m{\Avar/} ||
                                    $_[0] =~ m{\Avar/(?:man(?:/|\z)|postinstall\z|services\z)} }},
        'realadm-steps' => {root => "$ra/lib/step", user => 'root'},
        systemd => {root => "$test/etc/systemd/system", user => 'root', flat => 1, noversion => 1,
                    accept => sub { $_[0] =~ unitre() },
                    list => sub { $_[0] =~ unitre() && realunits()->{$_[0]} }},
    );
    my $site = site();
    $site and $t{'site-steps'} = {root => "$test/home/aia/$site/lib/step", user => "realadm-$site"};
    $t{$_}{name} = $_ for keys %t;
    return \%t;
}

# The units that are realadm's: those its var/services names, and those the systemd
# tree's expected state has.
sub realunits {
    my %u = map {($_ => 1)} split ' ', slurp("$test/usr/local/realadm/var/services") // '';
    my $e = expect('systemd');
    $e and $u{$_} = 1 for keys %{$e->{files}};
    return \%u;
}

# Return the host's RealEd site, or undef: the gsrvcode of its record when that names a
# site here, as realadm's libexec/nightly finds it.
sub site {
    $test and return $ENV{REALADM_UPDATER_SITE};
    my %g = do {
        package Aia::GsrvSite;
        our %gsrv;
        do '/usr/local/realadm/lib/Aia/GsrvSite.pm' or return undef;
        %gsrv;
    };
    my $code = $g{gsrvcode} // return undef;
    $code =~ /\A[a-z0-9][a-z0-9-]*\z/ or return undef;
    -d "/home/aia/$code/conf" && defined getpwnam("realadm-$code") or return undef;
    return $code;
}

# Tree $name, or die.
sub tree {
    my($name) = @_;
    return trees()->{$name // ''} // die "no tree " . ($name // '(none)') . " here\n";
}

# Whether roots $a and $b overlap: one is the other, or inside it.
sub overlap {
    my($a, $b) = @_;
    return $a eq $b || index("$a/", "$b/") == 0 || index("$b/", "$a/") == 0;
}

# A path in a tree: relative, and no part of it empty, "." or "..", or hidden, so a
# request can name nothing outside the tree, nor this program's own files in it.  And one
# the tree takes.
sub goodpath {
    my($t, $p) = @_;
    defined $p && $p =~ m{\A[\w+-][\w.@+-]*(?:/[\w+-][\w.@+-]*)*\z} or return 0;
    return !$t->{accept} || $t->{accept}->($p);
}

# The SHA-256 of a file's contents, hex.
sub sha {
    return Digest::SHA->new(256)->addfile($_[0], 'b')->hexdigest;
}

# The contents of $file, or undef.
sub slurp {
    open my $fh, '<:raw', $_[0] or return undef;
    local $/;
    return <$fh>;
}

# Write $data to $file, by way of a temporary.
sub spew {
    my($file, $data) = @_;
    open my $fh, '>', "$file.new" or die "$file.new: $!\n";
    print $fh $data;
    close $fh or die "close $file.new: $!\n";
    rename "$file.new", $file or die "rename $file: $!\n";
}

# The version record of tree $t: what the last apply wrote, or {}.
sub treeversion {
    my($t) = @_;
    $t->{noversion} and return {};
    my $v = slurp("$t->{root}/.update-version") // return {};
    return eval { $json->decode($v) } // {};
}

# User and group names, by id.
sub uname { scalar(getpwuid $_[0]) // $_[0] }
sub gname { scalar(getgrgid $_[0]) // $_[0] }

# The manifest of tree $t: its regular files, by path, its directories' modes, and the
# paths of anything else in it (links and the like), which an update will not replace.
sub manifest {
    my($t) = @_;
    my $show = $t->{list} // $t->{accept};
    my(%files, %dirs, @other);
    my $walk;
    $walk = sub {
        my($dir, $rel) = @_;
        opendir my $dh, $dir or return;
        for my $n (sort grep {!/\A\./} readdir $dh) {
            my $p = $rel eq '' ? $n : "$rel/$n";
            my @s = lstat "$dir/$n" or next;
            if (S_ISDIR($s[2])) {
                $t->{flat} || $show && !$show->($p) and next;
                $dirs{$p} = S_IMODE($s[2]);
                $walk->("$dir/$n", $p);
                next;
            }
            $show && !$show->($p) and next;
            if (S_ISREG($s[2])) {
                $files{$p} = {sha256 => sha("$dir/$n"), mode => S_IMODE($s[2]), size => $s[7],
                              owner => uname($s[4]), group => gname($s[5])};
            } else {
                push @other, $p;
            }
        }
    };
    -d $t->{root} and $walk->($t->{root}, '');
    return {files => \%files, dirs => \%dirs, other => \@other, version => treeversion($t)};
}

# The uid and gid files in a tree belong to, and the gid of group $group when one is given.
sub owner {
    my($user, $group) = @_;
    my($uid, $gid);
    if ($test) {
        ($uid, $gid) = ($<, (split ' ', $()[0]);
    } else {
        my @pw = getpwnam $user or die "no user $user\n";
        ($uid, $gid) = @pw[2, 3];
    }
    if (defined $group) {
        $gid = getgrnam($group) // die "no group $group\n";
    }
    return ($uid, $gid);
}

# The name of the group a tree's files have when a request names none.
sub defgroup {
    my($t) = @_;
    return gname((owner($t->{user}))[1]);
}

# Make the directories from $root down to dirname($root/$path), each owned by the tree's
# user and 0755, refusing any part that is a link or not a directory.  The directories
# above the root are the host's, made here only when missing, as under test.  Returns the
# directories it made, relative to $root.
sub mkdirs {
    my($root, $path, $uid, $gid) = @_;
    -d dirname $root or File::Path::make_path(dirname $root, {mode => 0755});
    my $d = $root;
    my $rel = '';
    my @made;
    my $dir = dirname $path;
    for my $part ('', $dir eq '.' ? () : split m{/}, $dir) {
        if (length $part) {
            $d .= "/$part";
            $rel = $rel eq '' ? $part : "$rel/$part";
        }
        if (my @s = lstat $d) {
            S_ISDIR($s[2]) or die "$d is not a directory\n";
        } else {
            mkdir $d, 0755 or die "mkdir $d: $!\n";
            $test or chown $uid, $gid, $d or die "chown $d: $!\n";
            push @made, $rel;
        }
    }
    return @made;
}

# Write $data to $path (the whole path) by way of a temporary beside it, with $mode and
# the owner, and rename it into place.
sub install {
    my($path, $data, $mode, $uid, $gid) = @_;
    my $tmp = dirname($path) . '/.' . basename($path) . ".upd-$$";
    open my $fh, '>:raw', $tmp or die "$tmp: $!\n";
    print $fh $data or die "write $tmp: $!\n";
    close $fh or die "close $tmp: $!\n";
    if (!$test || $gid != (split ' ', $()[0]) {
        chown $uid, $gid, $tmp or do { unlink $tmp; die "chown $tmp: $!\n" };
    }
    chmod $mode, $tmp or die "chmod $tmp: $!\n";
    rename $tmp, $path or do { unlink $tmp; die "rename $path: $!\n" };
}

# Record $v as the version of tree $t.
sub setversion {
    my($t, $v, $uid, $gid) = @_;
    $t->{noversion} and return;
    mkdirs($t->{root}, '.update-version', $uid, $gid);
    install("$t->{root}/.update-version", $json->encode($v), 0644, $uid, $gid);
}

# The expected state of tree $name, which its last full update recorded, or undef; and
# recording one, or removing it (undef).
sub efile { "$vardir/expect/$_[0].json" }
sub expect {
    my $e = slurp(efile($_[0])) // return undef;
    return eval { $json->decode($e) };
}
sub setexpect {
    my($name, $e) = @_;
    if (!defined $e) {
        unlink efile($name);
        return;
    }
    File::Path::make_path("$vardir/expect", {mode => 0700});
    spew(efile($name), $json->encode($e));
}

# The journal of update $id, and writing one.  A journal from 1.0, of one tree, is read as
# one of a single part.
sub jfile { "$vardir/$_[0]/journal.json" }
sub jread {
    my($id) = @_;
    my $j = eval { $json->decode(slurp(jfile($id)) // return undef) } // return undef;
    if (!$j->{parts}) {
        $j->{parts} = [{map {($_ => $j->{$_})} qw(tree root added replaced deleted oldversion)}];
        $j->{parts}[0]{backup} = "$vardir/$id/backup";
    }
    return $j;
}
sub jwrite {
    my($j) = @_;
    spew(jfile($j->{id}), $json->encode($j));
}

# The trees an update touched, as history shows them.
sub jtrees { join ',', map {$_->{tree}} @{$_[0]{parts}} }

# Apply $req.  $req has:
#
#   id       the update's id, [\w-]+, new to this host
#   parts    [{tree, base, files, delete, dirs, expect}...], one per tree, each:
#     tree     the tree's name
#     base     {path: sha256} for each path the update replaces or deletes, as the client
#              read it in this host's manifest; a path to be added must not exist
#     files    {path: {data, sha256, mode, group}}: what to add or replace, data in
#              base64; mode at most 0755; group, when not the tree's, a group's name
#     delete   [path...]
#     dirs     {path: mode}: directories to make, or give this mode
#     expect   {files: {path: {sha256, mode, group}}, dirs: {path: mode}}: the whole tree
#              as it should be after this update, which verify compares with
#   version  what to record as each tree's version (the client puts the commit in it)
#   postinstall, deadman   see postinstall()
#
# A request of one tree may instead give tree, base, files, and delete itself, as 1.0's
# clients do.  When no tree changes, and no expected state either, it returns undef.
#
# Every check comes before the first change.  Then the journal is written, each file to
# be replaced or deleted is copied into the update's backup, the files are installed, the
# deletes done, the directories' modes set, and the versions and expected states written.
# A failure part way undoes what was done.
sub apply {
    my($req) = @_;
    my $id = $req->{id} // '';
    $id =~ /\A[\w-]{1,64}\z/ or die "bad update id\n";
    -e "$vardir/$id" and die "update $id was already applied here\n";
    my @reqparts = $req->{parts} ? @{$req->{parts}} : ({map {($_ => $req->{$_})} qw(tree base files delete)});
    @reqparts or die "nothing to update\n";
    my(@parts, %seen);
    for my $rp (@reqparts) {
        my $t = tree($rp->{tree});
        $seen{$t->{name}}++ and die "tree $t->{name} given twice\n";
        my %files = %{$rp->{files} // {}};
        my @del = @{$rp->{delete} // []};
        my %base = %{$rp->{base} // {}};
        my %dirs = %{$rp->{dirs} // {}};
        my $m = manifest($t);
        my $cur = $m->{files};
        my %other = map {($_ => 1)} @{$m->{other}};
        for my $p (keys %files, @del) {
            goodpath($t, $p) or die "$t->{name}: bad path: $p\n";
            $other{$p} and die "$t->{name}: $p is not a regular file here\n";
            my $now = $cur->{$p} && $cur->{$p}{sha256};
            ($now // '') eq ($base{$p} // '') or
                die "$t->{name}: $p changed since the manifest the client read; ask for it again\n";
            # A file the manifest does not show, a unit not realadm's say, is not the tree's.
            !$cur->{$p} && lstat "$t->{root}/$p" and
                die "$t->{name}: $p is here and is not the tree's\n";
        }
        for my $p (@del) {
            $files{$p} and die "$t->{name}: $p is both replaced and deleted\n";
            $cur->{$p} or die "$t->{name}: $p is not here to delete\n";
        }
        my %data;
        for my $p (keys %files) {
            my $f = $files{$p};
            defined $f->{data} or die "$t->{name}: $p: no data\n";
            $data{$p} = MIME::Base64::decode_base64($f->{data});
            Digest::SHA::sha256_hex($data{$p}) eq ($f->{sha256} // '') or
                die "$t->{name}: $p: data does not match its sha256\n";
            okmode($f->{mode} // 0644) or die "$t->{name}: $p: bad mode\n";
            $f->{gid} = (owner($t->{user}, $f->{group}))[1];
        }
        for my $d (keys %dirs) {
            $t->{flat} and die "$t->{name} has no directories\n";
            goodpath($t, $d) && okmode($dirs{$d}) or die "$t->{name}: bad directory $d\n";
            my @s = lstat "$t->{root}/$d";
            @s && !S_ISDIR($s[2]) and die "$t->{name}: $d is not a directory here\n";
        }
        my $e = $rp->{expect};
        if ($e) {
            ref $e->{files} eq 'HASH' or die "$t->{name}: bad expect\n";
            for my $p (keys %{$e->{files}}) {
                goodpath($t, $p) && okmode($e->{files}{$p}{mode} // 0644) or
                    die "$t->{name}: bad path in expect: $p\n";
            }
        }
        # A tree whose files are as the update wants still takes its expected state, the
        # first time, or when it differs from the one recorded.
        my $estale = $e && $json->encode(estate($e)) ne $json->encode(estate(expect($t->{name}) // {}));
        @del || %files || %dirs || $estale or next;
        push @parts, {t => $t, files => \%files, data => \%data, del => \@del, dirs => \%dirs,
                      cur => $cur, curdirs => $m->{dirs}, oldversion => $m->{version}, expect => $e};
    }
    @parts or return undef;

    my $udir = "$vardir/$id";
    File::Path::make_path("$udir/backup", {mode => 0700});
    # The expected states this update changes: its trees', and any tree's it is a part of.
    my %echange;
    for my $p (@parts) {
        $p->{expect} and $echange{$p->{t}{name}} = 1;
        for my $o (values %{trees()}) {
            $o->{name} ne $p->{t}{name} && overlap($o->{root}, $p->{t}{root}) &&
                length $o->{root} < length $p->{t}{root} && expect($o->{name}) and
                $echange{$o->{name}} = 1;
        }
    }
    my %j = (id => $id, state => 'pending', time => Time::HiRes::time(), version => $req->{version} // {},
             expects => {map {($_ => defined expect($_) ? 1 : 0)} sort keys %echange});
    for my $p (@parts) {
        my($f, $cur) = @{$p}{qw(files cur)};
        push @{$j{parts}}, {
            tree => $p->{t}{name}, root => $p->{t}{root}, backup => "$udir/backup/$p->{t}{name}",
            oldversion => $p->{oldversion},
            added => [sort grep {!$cur->{$_}} keys %{$f}],
            replaced => [sort grep {$cur->{$_}} keys %{$f}], deleted => [sort @{$p->{del}}],
            old => {map {($_ => [@{$cur->{$_}}{qw(mode owner group)}])} grep {$cur->{$_}} keys %{$f}, @{$p->{del}}},
            olddirs => {map {($_ => $p->{curdirs}{$_})} keys %{$p->{dirs}}},
            installed => {map {($_ => $f->{$_}{sha256})} keys %{$f}},
        };
    }
    jwrite(\%j);
    my $ok = eval {
        File::Path::make_path("$udir/expect", {mode => 0700});
        for my $name (keys %echange) {
            my $e = slurp(efile($name)) // next;
            spew("$udir/expect/$name.json", $e);
        }
        for my $i (0 .. $#parts) {
            my($p, $jp) = ($parts[$i], $j{parts}[$i]);
            my $t = $p->{t};
            my($uid, $gid) = owner($t->{user});
            for my $f (@{$jp->{replaced}}, @{$jp->{deleted}}) {
                mkdirs($jp->{backup}, $f, owner('root'));
                File::Copy::copy("$t->{root}/$f", "$jp->{backup}/$f") or die "back up $f: $!\n";
            }
            for my $f (sort keys %{$p->{files}}) {
                push @{$jp->{madedirs}}, mkdirs($t->{root}, $f, $uid, $gid);
                install("$t->{root}/$f", $p->{data}{$f}, $p->{files}{$f}{mode} // 0644, $uid,
                        $p->{files}{$f}{gid});
            }
            for my $f (@{$p->{del}}) {
                unlink "$t->{root}/$f" or die "delete $f: $!\n";
            }
            for my $d (sort keys %{$p->{dirs}}) {
                push @{$jp->{madedirs}}, mkdirs($t->{root}, "$d/x", $uid, $gid);
                chmod $p->{dirs}{$d}, "$t->{root}/$d" or die "chmod $d: $!\n";
            }
            setversion($t, {%{$j{version}}, id => $id}, $uid, $gid);
            if ($p->{expect}) {
                setexpect($t->{name}, {files => $p->{expect}{files}, dirs => $p->{expect}{dirs} // {},
                                       id => $id});
            }
            # The trees this one is a part of keep expecting what it now has.
            for my $name (grep {!$p->{expect} || $_ ne $t->{name}} keys %echange) {
                my $o = tree($name);
                $o->{name} ne $t->{name} && overlap($o->{root}, $t->{root}) &&
                    length $o->{root} < length $t->{root} or next;
                my $e = expect($name) // next;
                my $pre = substr($t->{root}, length($o->{root}) + 1) . '/';
                delete $e->{files}{"$pre$_"} for @{$p->{del}};
                $e->{files}{"$pre$_"} = {sha256 => $p->{files}{$_}{sha256}, mode => $p->{files}{$_}{mode} // 0644,
                                         group => gname($p->{files}{$_}{gid})} for keys %{$p->{files}};
                setexpect($name, $e);
            }
        }
        1;
    };
    if (!$ok) {
        my $err = $@;
        undo(\%j);
        die "update $id failed and was undone: $err";
    }
    $j{state} = 'applied';
    jwrite(\%j);
    prune();
    return \%j;
}

# The part of an expected state that verify compares with.
sub estate {
    my($e) = @_;
    return {files => $e->{files} // {}, dirs => $e->{dirs} // {}};
}

# Whether $mode is a mode a file or directory here may have: no more than 0755.
sub okmode {
    my($mode) = @_;
    return defined $mode && $mode =~ /\A\d+\z/ && !($mode & ~0755);
}

# Undo the journaled update %j: remove what it added, put back what it replaced or
# deleted, the directories' modes, the old versions, and the expected states.  Each file is
# put back by way of a temporary.  A file that cannot be put back does not stop the rest:
# the journal then says undo-failed, with why, and this dies saying so.
sub undo {
    my($j) = @_;
    my $udir = "$vardir/$j->{id}";
    my @fail;
    for my $jp (reverse @{$j->{parts}}) {
        my $t = eval { tree($jp->{tree}) } // {name => $jp->{tree}, root => $jp->{root}, user => 'root'};
        my($uid, $gid) = owner($t->{user});
        for my $p (@{$jp->{added}}) {
            -e "$t->{root}/$p" && !unlink "$t->{root}/$p" and push @fail, "remove $p: $!";
        }
        for my $p (@{$jp->{replaced}}, @{$jp->{deleted}}) {
            my $b = "$jp->{backup}/$p";
            -e $b or next;
            eval {
                my $data = slurp($b) // die "$b: $!\n";
                my($mode, $ow, $gr) = @{$jp->{old}{$p} // [S_IMODE((stat $b)[2])]};
                my($fuid, $fgid) = ($uid, $gid);
                if (defined $gr && !$test) {
                    $fuid = getpwnam($ow) // $uid;
                    $fgid = getgrnam($gr) // $gid;
                }
                mkdirs($t->{root}, $p, $uid, $gid);
                install("$t->{root}/$p", $data, $mode, $fuid, $fgid);
                1;
            } or push @fail, "put back $p: " . ($@ =~ s/\s+\z//r);
        }
        for my $d (sort keys %{$jp->{olddirs} // {}}) {
            my $m = $jp->{olddirs}{$d} // next;
            chmod $m, "$t->{root}/$d" or push @fail, "chmod $d: $!";
        }
        for my $d (reverse sort @{$jp->{madedirs} // []}) {
            rmdir "$t->{root}/$d";
        }
        eval { setversion($t, $jp->{oldversion} // {}, $uid, $gid); 1 } or
            push @fail, 'put back the version: ' . ($@ =~ s/\s+\z//r);
    }
    for my $name (sort keys %{$j->{expects} // {}}) {
        eval {
            if ($j->{expects}{$name}) {
                my $e = slurp("$udir/expect/$name.json") // die "no saved expect\n";
                File::Path::make_path("$vardir/expect", {mode => 0700});
                spew(efile($name), $e);
            } else {
                setexpect($name, undef);
            }
            1;
        } or push @fail, "put back ${name}'s expected state: " . ($@ =~ s/\s+\z//r);
    }
    $j->{state} = @fail ? 'undo-failed' : 'undone';
    @fail and $j->{undofail} = \@fail;
    jwrite($j);
    @fail and die "couldn't undo update $j->{id}: " . join('; ', @fail) . "\n";
}

# The journals, newest first.
sub journals {
    opendir my $dh, $vardir or return ();
    return sort {$b->{time} <=> $a->{time} || $b->{id} cmp $a->{id}}
           grep {$_} map {jread($_)} grep {/\A[\w-]+\z/ && $_ ne 'expect'} readdir $dh;
}

# Keep the newest keep updates; remove the rest.
sub prune {
    my @j = journals();
    File::Path::remove_tree("$vardir/$_->{id}") for @j[keep .. $#j];
}

# An apply that never finished, from a run that died part way: undo it.
sub recover {
    undo($_) for grep {$_->{state} eq 'pending'} journals();
}

# Roll back update $id, or the newest applied one.  Only an update no newer applied update
# overlaps may be rolled back: an older one's backups would undo the newer one's changes.
# When the update restarted remote-shim, restart it again, on the code put back.  Unless
# $force, refuse when the tree is no longer as the update left it (make install-<name>
# since, say): its backups would put back files older than what is there.
sub rollback {
    my($id, $force) = @_;
    my @j = grep {$_->{state} eq 'applied'} journals();
    my $j = defined $id ? (grep {$_->{id} eq $id} @j)[0] : $j[0];
    $j or die defined $id ? "no applied update $id\n" : "no applied update to roll back\n";
    for my $n (@j) {
        $n->{id} eq $j->{id} and last;
        for my $a (@{$n->{parts}}) {
            grep {overlap($a->{root}, $_->{root})} @{$j->{parts}} and
                die "update $j->{id} is not the newest of " . jtrees($j) . ": roll back $n->{id} first\n";
        }
    }
    my @changed = $force ? () : changedsince($j);
    @changed and die "update $j->{id}'s files changed since it was applied (" .
        join(', ', @changed[0 .. ($#changed < 4 ? $#changed : 4)]) . (@changed > 5 ? ', ...' : '') .
        "): rolling it back would put back older files; force rolls back anyway\n";
    my $dm = $j->{deadman};
    if ($dm && ($dm->{state} // '') eq 'armed') {
        disarm($j->{id});
        $dm->{state} = 'rolled back';
    }
    undo($j);
    # An update that restarted remote-shim left it running the code just taken away.
    $dm and restartshim();
    return $j;
}

# The files of update %j that are not as it left them: one it installed that now differs or
# is gone, or one it deleted that is back.  A journal from 1.0 has no record of what it
# installed, so only its deletes are checked.
sub changedsince {
    my($j) = @_;
    my @c;
    for my $jp (@{$j->{parts}}) {
        my $inst = $jp->{installed} // {};
        for my $p (sort keys %{$inst}) {
            my $f = "$jp->{root}/$p";
            push @c, !-f $f ? "$p is gone" : sha($f) ne $inst->{$p} ? "$p changed" : ();
        }
        push @c, map {"$_ is back"} grep {-e "$jp->{root}/$_"} @{$jp->{deleted}};
    }
    return @c;
}

# Run realadm's var/postinstall and return {status, output}.  $pi is the request's
# postinstall: {units: [unit...], restart_shim}.  Only the units named are enabled: one
# someone disabled stays so unless an update changes it.  With restart_shim, postinstall
# also restarts remote-shim.
sub postinstall {
    my($pi, $restart) = @_;
    my $script = tree('realadm')->{root} . '/var/postinstall';
    -e $script or return {status => 1, output => "no $script\n"};
    my @units = @{$pi->{units} // []};
    $_ =~ unitre() or die "bad unit: $_\n" for @units;
    my @cmd = ('/bin/sh', $script, '--units=' . join(',', @units), $restart ? '--restart-shim' : ());
    my $pid = open(my $ph, '-|') // die "fork: $!\n";
    if (!$pid) {
        open STDERR, '>&', \*STDOUT;
        open STDIN, '<', '/dev/null';
        exec @cmd or print "exec $script: $!\n";
        POSIX::_exit(127);
    }
    my $out = do {local $/; <$ph>} // '';
    close $ph;
    return {status => $? >> 8, output => $out};
}

# The dead-man of update $id: arm it to fire in $secs, and disarm it.
sub deadunit { "realadm-updater-deadman-$_[0]" }
sub arm {
    my($id, $secs) = @_;
    if ($test) {
        spew("$vardir/$id/deadman", "$secs\n");
        return 1;
    }
    return system('systemd-run', '--quiet', '--unit=' . deadunit($id), "--on-active=$secs",
                  '--timer-property=AccuracySec=1s', '/usr/sbin/realadm-updater', '--deadman', $id) == 0;
}
sub disarm {
    my($id) = @_;
    if ($test) {
        unlink "$vardir/$id/deadman";
        return;
    }
    system('systemctl', 'stop', deadunit($id) . '.timer');
}

# Make remote-shim run realadm's code again: USR1 when it runs, else restart the channel
# that starts it.
sub restartshim {
    if ($test) {
        open my $fh, '>>', "$vardir/shim-restarts" or die "shim-restarts: $!\n";
        say $fh 'restart';
        return;
    }
    system('pkill', '-USR1', '-f', '^(/usr/bin/perl )?/usr/local/realadm/bin/remote-shim( |$)') == 0 or
        system('systemctl', 'try-restart', 'channel@*.service');
}

# The dead-man fired for update $id: unless confirmed, roll it back and restart the shim.
sub deadman {
    my($id) = @_;
    my $j = jread($id) // return "no update $id";
    my $st = $j->{deadman} && $j->{deadman}{state} // 'without a dead-man';
    $st eq 'armed' or return "update $id is $st";
    my $res = eval { undo($j); 'rolled back' } // 'rollback failed: ' . ($@ =~ s/\s+\z//r);
    $j = jread($id);
    $j->{deadman} = {%{$j->{deadman}}, state => 'fired', fired => Time::HiRes::time(), result => $res};
    jwrite($j);
    restartshim();
    return "update $id not confirmed: $res";
}

# Compare tree $t with its expected state: [issue...], or undef when it has none.
sub verify {
    my($t) = @_;
    my $e = expect($t->{name}) // return undef;
    my $m = manifest($t);
    my($have, $want) = ($m->{files}, $e->{files});
    # realadm installed another way since (make install-<name>, whose rsync leaves the
    # updater's record behind): one issue, not one for each file it changed.
    my $vf = $want->{VERSION};
    if ($vf && $have->{VERSION} && $have->{VERSION}{sha256} ne $vf->{sha256}) {
        chomp(my $v = slurp("$t->{root}/VERSION") // '?');
        return ["realadm $v was installed by other means since update $e->{id}; an update" .
                " through realadm-updater records it again"];
    }
    my $user = $test ? uname($<) : $t->{user};
    my $dg = defgroup($t);
    my @issues;
    for my $p (sort keys %{$want}) {
        my($h, $w) = ($have->{$p}, $want->{$p});
        if (!$h) {
            push @issues, "missing $p";
            next;
        }
        $h->{sha256} ne $w->{sha256} and push @issues, "changed $p";
        my $wm = $w->{mode} // 0644;
        $h->{mode} != $wm and push @issues, sprintf 'mode %s %04o, not %04o', $p, $h->{mode}, $wm;
        $h->{owner} ne $user and push @issues, "owner $p $h->{owner}, not $user";
        my $wg = $w->{group} // $dg;
        $h->{group} ne $wg and push @issues, "group $p $h->{group}, not $wg";
    }
    push @issues, map {"extra $_"} grep {!$want->{$_}} sort keys %{$have};
    push @issues, map {"not a file: $_"} @{$m->{other}};
    for my $d (sort keys %{$e->{dirs} // {}}) {
        my $hm = $m->{dirs}{$d};
        if (!defined $hm) {
            push @issues, "missing directory $d";
        } elsif ($hm != $e->{dirs}{$d}) {
            push @issues, sprintf 'mode %s/ %04o, not %04o', $d, $hm, $e->{dirs}{$d};
        }
    }
    return \@issues;
}

# Take the lock, and undo an apply that never finished.
sub takelock {
    File::Path::make_path($vardir, {mode => 0700});
    open my $lock, '>', "$vardir/.lock" or die "$vardir/.lock: $!\n";
    flock $lock, LOCK_EX or die "lock: $!\n";
    recover();
    return $lock;
}

# The dead-man's timer runs this as root with arguments; sudo runs it with none.
if (@ARGV) {
    @ARGV == 2 && $ARGV[0] eq '--deadman' && $ARGV[1] =~ /\A[\w-]{1,64}\z/ or
        die "usage: realadm-updater, with a JSON request on stdin\n";
    my $lock = takelock();
    say STDERR 'realadm-updater: dead-man: ', deadman($ARGV[1]);
    exit 0;
}

# Serve the request on stdin.
my $res = eval {
    my $in = do {local $/; binmode STDIN; <STDIN>} // '';
    length $in or die "no request on stdin\n";
    my $req = eval { $json->decode($in) };
    ref $req eq 'HASH' or die "the request is not a JSON object\n";
    my $op = $req->{op} // '';
    my $lock = takelock();
    if ($op eq 'manifest') {
        my $t = tree($req->{tree});
        # With the commit of the realadm install, so the client can tell whether a
        # steps-only update is enough: nothing else the steps use may have changed since.
        my $m = manifest($t);
        my $v = slurp("$test/usr/local/realadm/VERSION");
        defined $v and chomp($m->{realadm} = $v);
        $m->{defgroup} = defgroup($t);
        +{ok => $m};
    } elsif ($op eq 'apply') {
        my $pi = $req->{postinstall};
        my $restart = $pi && $pi->{restart_shim};
        my $secs = $req->{deadman} // 300;
        $secs =~ /\A\d+\z/ && $secs >= 30 && $secs <= 3600 or die "bad deadman: $secs\n";
        my $j = apply($req);
        # Nothing to change: postinstall still runs, as after every full update.
        $j or $pi or die "nothing to update\n";
        $j or return +{ok => {nothing => JSON::PP::true, postinstall => postinstall($pi, 0)}};
        my %r = (id => $j->{id});
        for my $k (qw(added replaced deleted)) {
            $r{$k} += @{$_->{$k}} for @{$j->{parts}};
        }
        if ($pi) {
            if ($restart && arm($j->{id}, $secs)) {
                $j->{deadman} = {state => 'armed', secs => $secs, armed => Time::HiRes::time()};
                $r{deadman} = $secs;
            } elsif ($restart) {
                $restart = 0;
                $r{shim} = "couldn't arm the dead-man; remote-shim not restarted";
            }
            $j->{postinstall} = $r{postinstall} = postinstall($pi, $restart);
            jwrite($j);
        }
        +{ok => \%r};
    } elsif ($op eq 'postinstall') {
        $req->{postinstall}{restart_shim} and die "restart remote-shim with an apply, which arms its dead-man\n";
        +{ok => postinstall($req->{postinstall} // {}, 0)};
    } elsif ($op eq 'confirm') {
        my $j = jread($req->{id} // '') // die "no update " . ($req->{id} // '(none)') . "\n";
        my $st = $j->{deadman} && $j->{deadman}{state} // die "update $j->{id} has no dead-man\n";
        if ($st eq 'armed') {
            disarm($j->{id});
            $j->{deadman}{state} = 'confirmed';
            $j->{deadman}{confirmed} = Time::HiRes::time();
            jwrite($j);
        } elsif ($st ne 'confirmed') {
            die "update $j->{id}'s dead-man is $st" .
                ($j->{deadman}{result} ? ": $j->{deadman}{result}" : '') . "\n";
        }
        +{ok => {id => $j->{id}}};
    } elsif ($op eq 'rollback') {
        +{ok => {id => rollback($req->{id}, $req->{force})->{id}}};
    } elsif ($op eq 'history') {
        +{ok => [map {+{id => $_->{id}, tree => jtrees($_), state => $_->{state}, time => $_->{time},
                        version => $_->{version},
                        $_->{deadman} ? (deadman => $_->{deadman}{state}) : (),
                        $_->{postinstall} ? (postinstall => $_->{postinstall}{status}) : ()}} journals()]};
    } elsif ($op eq 'verify') {
        my @names = defined $req->{tree} ? tree($req->{tree})->{name} : sort keys %{trees()};
        my %r;
        for my $name (@names) {
            my $v = verify(tree($name));
            $r{$name} = $v ? {issues => $v} : {noexpect => JSON::PP::true};
        }
        +{ok => {trees => \%r, clean => (grep {$_->{issues} && @{$_->{issues}}} values %r) ?
                                        JSON::PP::false : JSON::PP::true}};
    } elsif ($op eq 'selftest') {
        +{ok => {trees => [sort keys %{trees()}], version => progversion}};
    } else {
        die "unknown op: $op\n";
    }
};
my $failed = !$res;
$res //= {err => $@ =~ s/\s+\z//r};
print $json->encode($res), "\n";
exit($failed ? 1 : 0);
