#!/usr/bin/perl
# mtmon-admin-center - central dashboard for several mtmon installations
#
# Each mtmon (9.0+) with [central] enabled sends its status after every check (HTTPS POST to
# /api/v1/ingest, its own site key). The centre keeps the latest status and the history per
# site, shows all sites with their problems on one page and each site's own dashboard, and
# mails when a site stops reporting.
#
# Parts shared with mtmon (web server, TLS, sign-in, history, mail) are copied from mtmon when
# the package is built - see build-center-deb.sh / assemble.pl.

use strict;
use warnings;
use utf8;

use Getopt::Long qw(:config no_ignore_case bundling);
use IO::Socket::INET;
use Socket qw(MSG_PEEK);
use JSON::PP;
use Net::SMTP;
use Digest::MD5 qw(md5_hex);
use Encode qw(encode decode);
use MIME::QuotedPrint qw(encode_qp);
use POSIX qw(strftime :sys_wait_h);
use Fcntl qw(:flock);
use File::Basename qw(dirname);
use File::Temp qw(tempfile);
use File::Path qw(make_path);
use File::Copy ();
use File::Spec;
use Sys::Hostname qw(hostname);
use IO::Select;
use MIME::Base64 qw(decode_base64 encode_base64);
use Digest::SHA qw(hmac_sha256_hex hmac_sha256 sha256_hex);
use Time::Local ();

our $VERSION = '7.21.0';
our $MTMON_VERSION = '13.13.0';     # mtmon this centre is built with
# which mtmon the centre works with: every mtmon from MTMON_MIN sends its status; what the
# centre shows beyond that needs the versions below (--version, --list-sites and the site
# page name what an older site is missing). Keep in step with the table in README.md.
our $MTMON_MIN = '9.0.0';
our @MTMON_FEATURES = (
    [ '10.1.0', 'reports in parts, compressed' ],
    [ '11.0.0', 'maintenance windows set on the centre' ],
    [ '11.2.1', 'Wi-Fi clients per access point' ],
    [ '12.0.0', 'switch statistics (device report), VLANs on ports' ],
    [ '13.3.0', 'the server of the site (memory, CPU, disk)' ],
    [ '13.4.0', 'ports and VLANs of the access points' ],
    [ '13.4.1', 'names of the devices in maintenance' ],
    [ '13.4.2', 'push from the centre without delay' ],
    [ '13.5.0', 'maintenance reaches the centre within seconds' ],
    [ '13.6.0', 'one alert for an outage and all that is behind it' ],
    [ '13.7.0', 'the topology of the site drawn' ],
);
$0 = 'mtmon-center';

binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';
$| = 1;
STDERR->autoflush(1);

my %opt = (config => '/etc/mtmon-admin-center/center.conf');
GetOptions(\%opt,
    'config|c=s', 'debug|d', 'web', 'add-site=s', 'list-sites', 'fingerprint', 'hash-password', 'new-api-key=s',
    'check', 'version|V', 'help|h', 'changelog:s', 'group=s', 'mail=s', 'period-report=s', 'dry-run|n',
    'push-list', 'push-remove=s', 'server', 'config-upgrade', 'template=s', 'agent', 'agent-config=s',
    'backup:s', 'backup-list', 'restore=s', 'apply-restore',
) or usage(1);
usage(0) if $opt{help};
if ($opt{version}) {
    print "mtmon-admin-center $VERSION\n",
          "built with mtmon $MTMON_VERSION; works with mtmon $MTMON_MIN or newer\n",
          map { sprintf("  needs mtmon %-7s %s\n", @$_) } @MTMON_FEATURES;
    exit 0;
}
exit show_changelog($opt{changelog}) if defined $opt{changelog};
exit hash_password_cli() if $opt{'hash-password'};
# after a package upgrade (run by the package as root): new settings into the active config
exit config_upgrade_cli($opt{config}, $opt{template} // '/usr/share/mtmon-admin-center/center.conf.template', 'mtmon-admin-center', $VERSION,
                        $opt{'dry-run'}, { 'web users' => [], 'api keys' => [], sites => [] })
    if $opt{'config-upgrade'};

my $DEBUG   = $opt{debug};
my $running = 1;
my $reload  = 0;

# globals of the shared web server / history code
my ($WEB_PID, $WEB_NEXT, $WEB_STARTED, $WEB_RUNS);
my $WEB_RESULT;
BEGIN { ($WEB_PID, $WEB_NEXT, $WEB_STARTED, $WEB_RUNS) = (0, 0, 0, 0) }
my %TRIMMED;
my ($BK_PID, $BK_RESTART) = (0, 0);           # backup child, exit for a restore (7.20)
my @BK_WD = qw(sun mon tue wed thu fri sat);
my $CLIENTS_CHECKED;

exit add_site_cli($opt{config}, $opt{'add-site'}, $opt{group}, $opt{mail}, $opt{agent}) if defined $opt{'add-site'};
exit new_api_key_cli($opt{'new-api-key'}) if defined $opt{'new-api-key'};
# 7.20: backup and restore - before the switch to user mtmon-center (a restore writes the config folder)
exit bk_restore_cli($opt{config}, $opt{restore}) if defined $opt{restore};
if ($opt{'apply-restore'}) { eval { bk_apply_pending($opt{config}); 1 } or logmsg('error', "Restore: $@"); exit 0 }
if (defined $opt{backup}) { exit bk_backup_cli(load_config($opt{config}), $opt{backup}) }
my $DAEMON = !grep { defined $opt{$_} } qw(fingerprint agent-config list-sites push-list server push-remove check web period-report backup-list);
# a restore staged by the web page: as root (container) it is applied here; without root it is reported
eval { bk_apply_pending($opt{config}); 1 } or logmsg('error', "Restore: $@") if $DAEMON;
drop_privileges();
my $cfg = load_config($opt{config});

if ($opt{fingerprint}) { exit fingerprint_cli($cfg) }
if (defined $opt{'agent-config'}) { exit agent_conf_cli($cfg, $opt{'agent-config'}) }
if ($opt{'list-sites'}) { exit list_sites($cfg) }
if ($opt{'backup-list'}) { exit bk_list_cli($cfg) }
if ($opt{'push-list'})  { exit push_list_cli($cfg) }
if ($opt{server}) {
    my $f = "$cfg->{general}{data_dir}/server.json";
    my $ss = jread($f);
    $ss = (server_sample($f, $cfg->{general}{data_dir}, 0, time, 'mtmon-admin-center'))[0] if !$ss || !$ss->{du_t};
    my $i = server_info($ss, $cfg->{general}{data_dir}, $cfg->{general}{disk_warn}, 'mtmon-admin-center', $VERSION);
    server_print($i);
    my $sz = (($ss->{du} || {})->{sub} || {})->{sites} || {};
    if (%$sz) {
        print "  Sites (data in the centre):\n";
        printf "    %-34s %10s\n", $_, fmt_bytes($sz->{$_}) for sort { $sz->{$b} <=> $sz->{$a} } keys %$sz;
    }
    exit 0;
}
if (defined $opt{'push-remove'}) { exit push_remove_cli($cfg, $opt{'push-remove'}) }
if ($opt{check})        { print "Configuration OK: " . scalar(keys %{ $cfg->{sites} }) . " site(s), web on port $cfg->{web}{port}\n"; exit 0 }
if ($opt{web})          { web_main($cfg); exit 0 }
if (defined $opt{'period-report'}) { exit center_report_cli($cfg, $opt{'period-report'}) }

# ---- daemon -------------------------------------------------------------
$SIG{TERM} = $SIG{INT} = sub { $running = 0 };
$SIG{PIPE} = 'IGNORE';
$SIG{HUP}  = sub { $reload = 1 };
logmsg('info', "mtmon-admin-center $VERSION started: " . scalar(keys %{ $cfg->{sites} }) . " site(s)");
web_start($cfg);
my $PIDF = "$cfg->{general}{data_dir}/center.pid";        # 7.20: --restore sees that this centre runs
if (open(my $pf, '>', $PIDF)) { print {$pf} "$$\n"; close $pf }
while ($running) {
    if ($reload) {
        logmsg('info', $reload eq 'file' ? "$opt{config} changed, reading it again" : 'Reload requested, reading the configuration again');
        $reload = 0;
        my $new = eval { load_config($opt{config}) };
        if ($new) {
            my @add = grep { !$cfg->{sites}{$_} } sort keys %{ $new->{sites} };
            my @del = grep { !$new->{sites}{$_} } sort keys %{ $cfg->{sites} };
            my @key = grep { $cfg->{sites}{$_} && $cfg->{sites}{$_}{hash} ne $new->{sites}{$_}{hash} } sort keys %{ $new->{sites} };
            $cfg = $new;
            logmsg('info', 'Configuration reloaded: ' . scalar(keys %{ $cfg->{sites} }) . ' site(s)'
                . (@add ? '; new: ' . join(', ', @add) : '') . (@del ? '; removed: ' . join(', ', @del) : '')
                . (@key ? '; new key: ' . join(', ', @key) : ''));
            web_stop(); web_start($cfg);
        } else {
            $cfg->{_mtime} = (stat $opt{config})[9] // 0;      # do not try again until the file changes again
            logmsg('error', "Reload failed, keeping the old configuration: $@");
        }
    }
    eval { check_sites($cfg); 1 } or logmsg('warn', "Checking the sites failed: $@");
    eval { center_dev_changes($cfg); 1 } or logmsg('warn', "Looking for new devices failed: $@");
    eval { center_cert_check($cfg); 1 } or logmsg('warn', "Checking the centre's certificate failed: $@");
    eval { center_report_check($cfg, time); 1 } or logmsg('warn', "Report: $@");
    eval { center_server_check($cfg, time); 1 } or logmsg('warn', "Server sample: $@");
    for (1 .. 30) {
        last if !$running || $reload;
        if (((stat $opt{config})[9] // 0) != $cfg->{_mtime}) { $reload = 'file'; last }
        web_check($cfg);
        if ((eval { bk_check($cfg, time) } // '') eq 'restart') { $running = 0; last }
        sleep 2;
    }
}
web_stop();
unlink $PIDF;
logmsg('info', 'mtmon-admin-center stopped' . ($BK_RESTART ? ' for the restore (exit 75: systemd / the container start it again)' : ''));
exit($BK_RESTART ? 75 : 0);

# ==========================================================================
sub usage {
    my ($rc) = @_;
    print <<"EOT";
mtmon-admin-center $VERSION - central dashboard for several mtmon installations

Usage: mtmon-admin-center [-c config] [options]

  -c, --config FILE   configuration (default /etc/mtmon-admin-center/center.conf)
  -d, --debug         verbose output
      --add-site ID [--group NAME] [--mail a\@x,b\@y]
                      create a site: adds its key to [sites] and prints the [central] lines for that mtmon;
                      --group puts it into a group, --mail adds recipients for this site's mails;
                      --agent: a site with mtmon --agent (MikroTik container without a disk) - prints
                      the container's variables and creates its configuration on the centre
      --agent-config ID
                      the configuration of an agent site (creates it from the template when missing)
                      and whether the agent runs it
      --period-report week|month|7d
                      mail the report of all sites for the last complete week / month (or N days) now
      --list-sites    list the sites with their last report
      --fingerprint   print the fingerprint of the web certificate (for [central] fingerprint in mtmon)
      --hash-password ask for a password and print its hash for [web users]
      --new-api-key NAME
                      create an API key for apps / scripts and print the line for [api keys]
      --push-list     list the phones that get push notifications (MT-Mon app)
      --push-remove NAME|all
                      stop push notifications to a phone (name from --push-list) or to all
      --backup [FILE|DIR]
                      back up the whole centre now (center.conf, certificate, all data) into one .tar.gz -
                      into the backup folder ([backup] dir) or to FILE / into DIR
      --backup-list   list the backups, the schedule and the last result
      --restore FILE  restore a backup (as root): while the centre runs it restarts and applies it,
                      when it is stopped it is applied at once; a copy of the present state is made first
      --apply-restore apply a restore staged by the web page (systemd runs it as root before each start)
      --check         check the configuration
      --server        what the centre uses on this server, free disk space, data of each site
      --config-upgrade [--template FILE] [-n]
                      add the settings that are new in this version to the config, commented out
                      with their explanation (the package does it on upgrade); -n only shows them
      --web           run only the web server in the foreground
      --changelog [V] print the change history
  -V, --version       print the version
  -h, --help          this help

Without options it runs as a daemon; SIGHUP reloads the configuration.
EOT
    exit $rc;
}

sub drop_privileges {
    return if $> != 0 || $ENV{MTMON_RUN_AS_ROOT};
    my @pw = getpwnam('mtmon-center') or return;
    my ($uid, $gid, $home) = @pw[2, 3, 7];
    $ENV{HOME} = $home;
    POSIX::setgid($gid) or die "setgid($gid): $!\n";
    $) = "$gid $gid";
    POSIX::setuid($uid) or die "setuid($uid): $!\n";
    die "Switching to user mtmon-center failed\n" if $< != $uid || $> != $uid;
    chdir '/';
}

# read a request body of $len bytes within $secs seconds; returns (body, why it stopped early).
# TLS sockets are read with sysread (no Perl buffer in between); plain ones with read, because the
# headers before were read through Perl's buffer
sub read_body {
    my ($c, $len, $secs) = @_;
    my ($body, $err) = ('', '');
    my $end = time + $secs;
    my $tls = ref($c) =~ /SSL/;
    my $sel = IO::Select->new($c);
    eval {
        local $SIG{ALRM} = sub { die "timeout after $secs s\n" };
        alarm $secs + 5;
        while (length($body) < $len) {
            my $want = $len - length($body);
            $want = 262144 if $want > 262144;
            my $r;
            if ($tls) {
                if (!$c->pending && !$sel->can_read($end - time > 0 ? $end - time : 0)) { $err = "nothing more within $secs s"; last }
                $r = sysread($c, $body, $want, length $body);
                if (!defined $r) {
                    next if $!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}
                         || ($IO::Socket::SSL::SSL_ERROR && ($IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_WANT_READ()
                                                          || $IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_WANT_WRITE()));
                    $err = "read error: " . ($! || IO::Socket::SSL::errstr());
                    last;
                }
            } else {
                $r = read($c, $body, $want, length $body);
                if (!defined $r) { $err = "read error: $!"; last }
            }
            if (!$r) { $err = 'the sender closed the connection'; last }
        }
        alarm 0;
        1;
    } or $err = $@ =~ s/\s+$//r;
    alarm 0;
    return ($body, $err);
}

# read and drop a request body (at most 16 MB, 30 s), so the answer reaches the client
sub drain_body {
    my ($c, $len) = @_;
    return unless defined $len && $len =~ /^\d+$/ && $len > 0 && $len <= 16_000_000;
    eval {
        local $SIG{ALRM} = sub { die "client timeout\n" };
        alarm 30;
        my ($left, $buf) = ($len, '');
        while ($left > 0) { my $r = read($c, $buf, $left > 65536 ? 65536 : $left); last unless $r; $left -= $r }
        alarm 0;
        1;
    };
    alarm 0;
}

# stop the web process and make sure it is gone before a new one starts (reload)
sub web_stop {
    return unless $WEB_PID;
    kill 'TERM', $WEB_PID;
    my $gone = 0;
    for (1 .. 50) {
        my $r = waitpid($WEB_PID, WNOHANG);
        if ($r == $WEB_PID || $r == -1) { $gone = 1; last }
        select(undef, undef, undef, 0.1);
    }
    unless ($gone) {
        logmsg('warn', "Web process $WEB_PID did not stop, killing it");
        kill 'KILL', $WEB_PID;
        waitpid($WEB_PID, 0);
    }
    $WEB_PID = 0;
}

sub web_procname { 'mtmon-centerweb' }

sub show_changelog {
    my ($since) = @_;
    my ($file) = grep { -r } '/usr/share/mtmon-admin-center/CHANGELOG.md', '/usr/share/doc/mtmon-admin-center/CHANGELOG.md',
                             dirname(__FILE__) . '/CHANGELOG.md';
    open(my $fh, '<:encoding(UTF-8)', $file // '') or do { print STDERR "CHANGELOG.md not found\n"; return 1 };
    my $show = !length($since // '');
    while (my $l = <$fh>) {
        if (!$show && $l =~ /^## (\S+)/) { $show = vcmp($1, $since) > 0 }
        elsif ($show && length($since // '') && $l =~ /^## (\S+)/) { $show = vcmp($1, $since) > 0 }
        print $l if $show;
    }
    return 0;
}
sub vcmp {
    my @a = split /[.\-]/, $_[0]; my @b = split /[.\-]/, $_[1];
    for my $i (0 .. ($#a > $#b ? $#a : $#b)) { my $c = ($a[$i] // 0) <=> ($b[$i] // 0); return $c if $c }
    return 0;
}

# ==========================================================================
# configuration
# ==========================================================================
sub load_config {
    my ($file) = @_;
    open(my $fh, '<:encoding(UTF-8)', $file) or die "Cannot open $file: $!\n";
    my %c = (
        general => { title => 'MT-Mon Admin Center', data_dir => '/var/lib/mtmon-admin-center',
                     offline_after => 0, notify_offline => 'yes', notify_devices => 'yes', cert_warn_days => '30,14,7,3,1', disk_warn => 10 },
        report => { enabled => 'yes', weekly => 'yes', monthly => 'yes', time => '07:00', to => '' },
        backup => { auto => 'daily', time => '03:15', weekday => 'sun', keep => 7, dir => '', mail => 'yes' },
        mail => {
            method => 'smtp', smtp_host => 'localhost', smtp_port => 25, ssl => 0, starttls => 0,
            ssl_verify => 1, ssl_verify_name => '', smtp_user => '', smtp_password => '',
            from => 'mtmon-admin-center@' . hostname(), to => '', subject_prefix => '[MT-Mon Center]',
            format => 'text', sendmail => '/usr/sbin/sendmail',
        },
        web => {
            listen => '0.0.0.0', port => 443, allow => '', tls => 'yes',
            cert_file => '/etc/mtmon-admin-center/center.crt', key_file => '/etc/mtmon-admin-center/center.key',
            session_hours => 12, max_per_ip => 24, refresh => 30, history_days => 30, history_hourly_days => 400,
            html => '/usr/share/mtmon-admin-center', user => '', password => '',
        },
        sites => {},
    );
    my ($sec, %users, %keys);
    while (my $l = <$fh>) {
        $l =~ s/^\s+//; $l =~ s/\s+$//;
        next if $l eq '' || $l =~ /^[#;]/;
        if ($l =~ /^\[\s*(.+?)\s*\]$/) {
            $sec = lc $1;
            $sec =~ s/\s+/_/g;
            die "$file:$.: unknown section [$1]\n" unless $sec =~ /^(general|mail|web|web_users|api_keys|sites|report|backup)$/;
            next;
        }
        die "$file:$.: line outside of any section\n" unless defined $sec;
        my ($k, $v) = $l =~ /^([^=]+?)\s*=\s*(.*)$/ or die "$file:$.: expected key = value\n";
        $v =~ s/^"(.*)"$/$1/;
        if ($sec eq 'sites') {
            die "$file:$.: site id '$k': use letters, digits, - and _ only\n" unless $k =~ /^[A-Za-z0-9_-]+$/;
            die "$file:$.: site '$k': expected {SHA256}... (mtmon-admin-center --add-site $k)\n" unless $v =~ s/^\{SHA256\}([0-9a-f]{64})//i;
            my $hash = lc $1;
            die "$file:$.: site '$k' defined twice\n" if $c{sites}{$k};
            # options after the hash:  group=Coast  mail=a@x.si,b@y.si  (a value with spaces in "quotes")
            my %o;
            while ($v =~ /\G\s*(\w+)\s*=\s*("[^"]*"|\S+)/gc) { my ($k2, $x) = ($1, $2); $x =~ s/^"|"$//g; $o{ lc $k2 } = $x }
            die "$file:$.: site '$k': cannot read '" . ($v =~ /\G\s*(.*)$/ ? $1 : $v) . "' (expected group=... mail=...)\n" if $v =~ /\G\s*\S/gc;
            for (keys %o) { die "$file:$.: site '$k': unknown option '$_' (group, mail, lat, lon)\n" unless /^(group|mail|lat|lon)$/ }
            # where the site is, for the globe of the wall view (7.0): lat=45.548 lon=13.730 (degrees, WGS84)
            for ([ lat => 90 ], [ lon => 180 ]) { my ($n, $m) = @$_; next unless defined $o{$n};
                die "$file:$.: site '$k': $n must be degrees (-$m to $m), e.g. lat=45.548 lon=13.730\n" unless $o{$n} =~ /^-?\d{1,3}(?:\.\d+)?$/ && abs($o{$n}) <= $m }
            die "$file:$.: site '$k': give both lat= and lon=\n" if defined($o{lat}) != defined($o{lon});
            for (grep { length } split /\s*[,;]\s*/, $o{mail} // '') { die "$file:$.: site '$k': '$_' is not a mail address\n" unless /^[^@\s]+@[^@\s]+$|<[^@\s]+@[^@\s]+>/ }
            $c{sites}{$k} = { id => $k, hash => $hash, group => $o{group} // '', mail => $o{mail} // '', (defined $o{lat} ? (lat => $o{lat} + 0, lon => $o{lon} + 0) : ()) };
        }
        elsif ($sec eq 'web_users') { die "$file:$.: user '$k' defined twice\n" if $users{ lc $k }; $users{ lc $k } = [ $k, $v, $. ] }
        elsif ($sec eq 'api_keys')  { die "$file:$.: API key '$k' defined twice\n" if $keys{ lc $k }; $keys{ lc $k } = [ $k, $v, $. ] }
        else { $c{$sec}{ lc $k } = $v }
    }
    close $fh;

    my $g = $c{general};
    $g->{location} = $g->{title};
    die "[general] offline_after must be minutes (0 = automatic)\n" unless $g->{offline_after} =~ /^\d+$/;
    $g->{notify_offline} = $g->{notify_offline} =~ /^(0|no|ne|false|off)$/i ? 0 : 1;
    $g->{notify_devices} = $g->{notify_devices} =~ /^(0|no|ne|false|off)$/i ? 0 : 1;
    $g->{state_file} = "$g->{data_dir}/center.json";      # data_file() of the shared code -> data_dir
    $g->{interval} = 60;
    my $w = $c{web};
    $w->{enabled} = 1;
    $w->{tls} = $w->{tls} =~ /^(0|no|ne|false|off)$/i ? 0 : 1;
    for my $k (qw(port session_hours max_per_ip refresh history_days history_hourly_days)) {
        die "[web] $k must be a positive integer\n" unless $w->{$k} =~ /^\d+$/ && $w->{$k} > 0;
    }
    $w->{_allow} = [ map { parse_cidr($_) // die "[web] allow: invalid network '$_'\n" } grep { length } split /\s*,\s*/, $w->{allow} ];
    $g->{_history_days} = $w->{history_days};
    $g->{_history_hourly_days} = $w->{history_hourly_days};

    # [report]
    my $rp = $c{report};
    for my $k (qw(enabled weekly monthly)) { die "[report] $k must be yes or no\n" unless $rp->{$k} =~ /^(1|yes|da|true|on|0|no|ne|false|off)$/i; $rp->{$k} = $rp->{$k} =~ /^(1|yes|da|true|on)$/i ? 1 : 0 }
    die "[report] time must be HH:MM\n" unless $rp->{time} =~ /^([01]?\d|2[0-3]):([0-5]\d)$/;
    $rp->{_hm} = [ $1 + 0, $2 + 0 ];
    # [backup] (7.20)
    my $bk = $c{backup};
    my $ba = lc($bk->{auto} =~ s/\s+//gr);
    if    ($ba =~ /^(off|no|ne|0|false|none)$/) { $bk->{_auto} = 'off' }
    elsif ($ba =~ /^(daily|weekly)$/)           { $bk->{_auto} = $ba }
    elsif ($ba =~ /^(\d+)h$/ && $1 >= 1 && $1 <= 720) { $bk->{_auto} = 'hours'; $bk->{_hours} = $1 + 0 }
    else { die "[backup] auto: off, daily, weekly or every N hours (6h, 12h)\n" }
    die "[backup] time must be HH:MM\n" unless $bk->{time} =~ /^([01]?\d|2[0-3]):([0-5]\d)$/;
    $bk->{_hm} = [ $1 + 0, $2 + 0 ];
    my %bwd = (sun => 0, mon => 1, tue => 2, wed => 3, thu => 4, fri => 5, sat => 6, ned => 0, pon => 1, tor => 2, sre => 3, 'čet' => 4, cet => 4, pet => 5, sob => 6);
    my $bw = lc substr($bk->{weekday}, 0, 3);
    die "[backup] weekday: mon, tue, wed, thu, fri, sat or sun\n" unless exists $bwd{$bw};
    $bk->{_wd} = $bwd{$bw};
    die "[backup] keep: how many automatic backups stay, 1 to 1000\n" unless $bk->{keep} =~ /^\d+$/ && $bk->{keep} >= 1 && $bk->{keep} <= 1000;
    die "[backup] mail must be yes or no\n" unless $bk->{mail} =~ /^(1|yes|da|true|on|0|no|ne|false|off)$/i;
    $bk->{mail} = $bk->{mail} =~ /^(1|yes|da|true|on)$/i ? 1 : 0;
    $bk->{dir} = "$g->{data_dir}/backups" unless length $bk->{dir};
    $bk->{dir} =~ s{/+$}{};
    die "[backup] dir must be an absolute path\n" unless $bk->{dir} =~ m{^/};
    die "[backup] dir cannot be data_dir itself (use a folder in it, e.g. $g->{data_dir}/backups)\n" if $bk->{dir} eq ($g->{data_dir} =~ s{/+$}{}r);
    die "[general] disk_warn: percent of free disk space, 0 to 90\n" unless $g->{disk_warn} =~ /^\d+$/ && $g->{disk_warn} <= 90;
    die "[general] cert_warn_days: days, comma separated\n" unless $g->{cert_warn_days} =~ /^\s*\d+(\s*,\s*\d+)*\s*$/;
    $g->{_cert_warn} = [ sort { $b <=> $a } split /\s*,\s*/, $g->{cert_warn_days} =~ s/^\s+|\s+$//gr ];
    my %groups = map { ($_->{group} => 1) } grep { length $_->{group} } values %{ $c{sites} };

    # users: name = password [role=full|operator|summary] [sites=a,b,!c] [groups=g1,!g2]
    # 7.20: operator = full without the administration of the centre (backup and restore)
    my %u;
    for my $e (values %users) {
        my ($name, $v, $line) = @$e;
        my %o = (role => 'full', sites => '', groups => '');
        $o{ lc $1 } = $2 while $v =~ s/\s+(role|sites|groups)\s*=\s*(\S+)\s*$//i;
        die "$file:$line: [web users] $name: role must be full, operator or summary\n" unless $o{role} =~ /^(full|operator|summary)$/i;
        my $op = lc $o{role} eq 'operator' ? 1 : 0;
        $o{role} = 'full' if $op;
        die "$file:$line: [web users] $name: no password\n" unless length $v;
        die "$file:$line: [web users] $name: unknown password hash (use --hash-password)\n"
            if $v =~ /^\{/ && $v !~ /^\{PBKDF2\}\d+\$[A-Za-z0-9+\/]+\$[A-Za-z0-9+\/]+$/;
        # 7.9.3: !name leaves a site (or a group) out: sites=!test,!lab - every site but these two;
        # sites=a,b,!c or groups=Obala,!koper-test - the ones listed, without those
        my (@s, @gr, %no);
        for (grep { length } split /\s*,\s*/, $o{sites}) {
            my ($neg, $id) = /^!(.*)$/ ? (1, $1) : (0, $_);
            die "$file:$line: [web users] $name: unknown site '$id'\n" unless $c{sites}{$id};
            if ($neg) { $no{$id} = 1 } else { push @s, $id }
        }
        my ($any_pos, %nog) = (scalar @s);
        for (grep { length } split /\s*,\s*/, $o{groups}) {
            my ($neg, $gname) = /^!(.*)$/ ? (1, $1) : (0, $_);
            die "$file:$line: [web users] $name: no site is in group '$gname'\n" unless $groups{$gname};
            if ($neg) { $nog{$gname} = 1 } else { push @gr, $gname; $any_pos = 1 }
        }
        if (@gr) { my %gg = map { $_ => 1 } @gr; push @s, grep { $gg{ $c{sites}{$_}{group} // '' } } keys %{ $c{sites} } }
        if (%no || %nog) {
            @s = keys %{ $c{sites} } unless $any_pos;                     # only exclusions: every site but those
            @s = grep { !$no{$_} && !$nog{ $c{sites}{$_}{group} // '' } } @s;
        }
        @s = ('-none-') if !@s && ($any_pos || %no || %nog);
        $u{ lc $name } = { name => $name, secret => $v, role => lc $o{role}, sites => (@s ? { map { $_ => 1 } @s } : undef), ($op ? (operator => 1) : ()) };
    }
    $w->{_users} = \%u;
    my %ak;
    for my $e (values %keys) {
        my ($name, $v, $line) = @$e;
        my %o = (role => 'full', allow => '', sites => '');
        $o{ lc $1 } = $2 while $v =~ s/\s+(role|allow|sites)\s*=\s*(\S+)\s*$//i;
        die "$file:$line: [api keys] $name: role must be full, operator or summary\n" unless $o{role} =~ /^(full|operator|summary)$/i;
        my $op = lc $o{role} eq 'operator' ? 1 : 0;
        $o{role} = 'full' if $op;
        die "$file:$line: [api keys] $name: expected {SHA256}... (--new-api-key $name)\n" unless $v =~ /^\{SHA256\}([0-9a-f]{64})$/i;
        my @s = grep { length } split /\s*,\s*/, $o{sites};
        $ak{ lc $1 } = { name => "key:$name", role => lc $o{role},
                         _allow => [ map { parse_cidr($_) // die "$file:$line: invalid allow '$_'\n" } grep { length } split /\s*,\s*/, $o{allow} ],
                         sites => (@s ? { map { $_ => 1 } @s } : undef), ($op ? (operator => 1) : ()) };
    }
    $c{_api_keys} = \%ak;
    die "[general] data_dir $g->{data_dir} does not exist\n" unless -d $g->{data_dir} || $opt{check};
    $c{_file} = $file;
    $c{_mtime} = (stat $file)[9] // 0;
    return \%c;
}

sub web_cert_files {
    my ($cfg) = @_;
    my $w = $cfg->{web};
    my ($crt, $key) = @$w{qw(cert_file key_file)};
    return ($crt, $key) if -r $crt && -r $key;
    logmsg('error', "Web: cannot read the certificate $crt / key $key ([web] cert_file / key_file)");
    return;
}

# --add-site ID: random key, its hash into [sites], the [central] lines for the mtmon
sub add_site_cli {
    my ($file, $id, $group, $mail, $agent) = @_;
    die "Site id: letters, digits, - and _ only (e.g. hotel-delfin)\n" unless $id =~ /^[A-Za-z0-9_-]+$/;
    $group = decode('UTF-8', $group // '');
    die "--group: no \" in the name\n" if $group =~ /"/;
    for (grep { length } split /\s*[,;]\s*/, $mail // '') { die "--mail: '$_' is not a mail address\n" unless /^[^@\s]+@[^@\s]+$/ }
    open(my $fh, '<:encoding(UTF-8)', $file) or die "Cannot open $file: $!\n";
    my @lines = <$fh>;
    close $fh;
    my ($in, $at) = (0, undef);
    for my $i (0 .. $#lines) {
        if ($lines[$i] =~ /^\s*\[\s*(.+?)\s*\]/) { $in = lc($1) eq 'sites'; $at = $i + 1 if $in; next }
        die "Site '$id' already exists in $file\n" if $in && $lines[$i] =~ /^\s*\Q$id\E\s*=/;
        $at = $i + 1 if $in && $lines[$i] =~ /\S/;
    }
    my $key = $id . '.' . random_token(32);
    my $line = "$id = {SHA256}" . sha256_hex($key) . (length $group ? '  group=' . ($group =~ /\s/ ? qq{"$group"} : $group) : '')
             . (length($mail // '') ? "  mail=$mail" : '') . "\n";
    if (defined $at) { splice @lines, $at, 0, $line } else { push @lines, "\n[sites]\n", $line }
    open(my $out, '>:encoding(UTF-8)', "$file.new") or die "Cannot write $file.new: $!\n";
    print {$out} @lines;
    close $out or die "Writing $file.new failed: $!\n";
    my @st = stat $file;
    chmod $st[2] & 07777, "$file.new";
    chown $st[4], $st[5], "$file.new";
    rename "$file.new", $file or die "Cannot replace $file: $!\n";
    my $fp = eval { my $c = load_config($file); cert_fingerprint($c->{web}{cert_file}) } // '';
    my $host = hostname();
    print "Site '$id' added to $file. The running centre takes it over by itself within a few seconds.\n\n";
    if ($agent) {
        # 7.13: an agent - its configuration lives here, the container gets only the address and the key
        my $c = load_config($file);
        my $f = agent_conf_file($c, $id);
        agent_conf_write($c, $id, agent_template($id)) unless -e $f;
        if ($> == 0 && (my @pw = getpwnam('mtmon-center'))) { chown $pw[2], $pw[3], dirname($f), $f }
        print "Its configuration: $f - edit it (or on the centre's page: the site card -> Agent config).\n\n";
        print "The variables of the container (RouterOS: /container/envs; the key is shown only now):\n\n";
        print "MTMON_CENTRAL     = https://$host/\nMTMON_KEY         = $key\n";
        print "MTMON_FINGERPRINT = $fp\n" if $fp;
        (my $rfp = $fp) =~ s/\$/\\\$/g;                              # RouterOS: \$ in a string, else it is a variable
        print "\nRouterOS, e.g.:\n/container/envs/add list=mtmon-agent key=MTMON_CENTRAL value=\"https://$host/\"\n"
            . "/container/envs/add list=mtmon-agent key=MTMON_KEY value=\"$key\"\n"
            . ($fp ? "/container/envs/add list=mtmon-agent key=MTMON_FINGERPRINT value=\"$rfp\"\n" : '');
        print "(the fingerprint pins this self-signed certificate; leave it out when the centre has a purchased certificate)\n" if $fp;
        return 0;
    }
    print "Put this into /etc/mtmon/mtmon.conf on that mtmon (the key is shown only now):\n\n";
    print "[central]\nenabled     = yes\nurl         = https://$host/\nkey         = $key\n";
    print "fingerprint = $fp\n" if $fp;
    print "\nthen: systemctl reload mtmon && mtmon --test-central\n";
    print "(fingerprint pins this self-signed certificate; remove it when the centre has a purchased certificate)\n" if $fp;
    return 0;
}

sub cert_fingerprint {
    my ($crt) = @_;
    return '' unless -r $crt;
    my $out = `openssl x509 -in '$crt' -noout -fingerprint -sha256 2>/dev/null`;
    return '' unless $out =~ /=([0-9A-Fa-f:]+)/;
    (my $hex = lc $1) =~ s/://g;
    return "sha256\$$hex";
}

sub fingerprint_cli {
    my ($cfg) = @_;
    my $fp = cert_fingerprint($cfg->{web}{cert_file});
    die "Cannot read $cfg->{web}{cert_file}\n" unless $fp;
    print "$fp\n";
    print STDERR "Use it in mtmon: [central] fingerprint = $fp\n" if -t STDOUT;
    return 0;
}

# ==========================================================================
# sites: storage
# ==========================================================================
sub site_dir { "$_[0]{general}{data_dir}/sites/$_[1]" }

# the "general" hash the shared history code works with, for one site
# access points of a site (remote CAPs, HP / cnPilot APs) as its last status lists them; ctl = one controller
sub site_ap_count {
    my ($lt, $ctl) = @_;
    my $n = 0;
    $n += scalar @{ $_->{aps} || [] } for grep { !length $ctl || $_->{name} eq $ctl } @{ ($lt->{status} || {})->{controllers} || [] };
    return $n;
}

sub site_g {
    my ($cfg, $id, $interval) = @_;
    return { state_file => site_dir($cfg, $id) . '/site.json', interval => $interval || 300,
             _history_days => $cfg->{general}{_history_days}, _history_hourly_days => $cfg->{general}{_history_hourly_days} };
}

sub read_json {
    my ($f) = @_;
    open(my $fh, '<:raw', $f) or return undef;
    local $/;
    my $d = eval { JSON::PP->new->utf8->decode(<$fh>) };
    close $fh;
    return $d;
}
sub write_json {
    my ($f, $d) = @_;
    my ($fh, $tmp) = tempfile('.tmp-XXXXXX', DIR => dirname($f));
    binmode $fh;
    print {$fh} JSON::PP->new->utf8->canonical->encode($d);
    close $fh or die "Writing $f failed: $!\n";
    rename($tmp, $f) or die "Cannot rename $tmp to $f: $!\n";
}

sub site_latest { read_json(site_dir($_[0], $_[1]) . '/latest.json') }

# POST /api/v1/ingest from an mtmon
sub ingest {
    my ($cfg, $site, $body, $peer) = @_;
    my $p = eval { JSON::PP->new->utf8->decode($body) };
    return (400, { error => 'invalid JSON' }) unless ref $p eq 'HASH' && ref $p->{status} eq 'HASH';
    my $dir = site_dir($cfg, $site->{id});
    make_path($dir) unless -d $dir;
    open(my $lk, '>', "$dir/.lock") or return (500, { error => "cannot lock: $!" });
    flock($lk, LOCK_EX);
    my $g = site_g($cfg, $site->{id}, $p->{status}{interval});
    # history and client records: only newer than what is stored (a resend after a timeout is ignored)
    my %last = map { ($_ => last_t(data_file($g, "$_.jsonl")) // 0) } qw(history clients clientsap devstats);
    my %n;
    for my $r (sort { ($a->{rec}{t} // 0) <=> ($b->{rec}{t} // 0) } grep { ref $_->{rec} eq 'HASH' } @{ $p->{records} || [] }) {
        my $k = ($r->{kind} // '') =~ /^(clients|clientsap|devstats|history)$/ ? $1 : next;
        next unless ($r->{rec}{t} // 0) > $last{$k};
        append_jsonl($g, "$k.jsonl", $r->{rec});
        $last{$k} = $r->{rec}{t};
        $n{$k}++;
    }
    # 7.8: the newest event that came FROM this mtmon (not one the centre wrote itself - "not reporting",
    # "new device" - those have the centre's time and would hide the mtmon's events that come in later)
    my $last_ev = last_mtmon_t(data_file($g, 'events.jsonl')) // 0;
    my $rt = time + 0;
    # rt: when the centre got it - the push to the phones goes by this, the event keeps the time mtmon saw it
    my @ev = map { +{ %$_, rt => $rt } } grep { ref $_ eq 'HASH' && ($_->{t} // 0) > $last_ev } @{ $p->{events} || [] };
    # 7.10: many outages in one report (a site cut off, a switch without the topology yet): one push, not one each
    my @dn = grep { ($_->{type} // '') =~ /^(ap_missing|dev_down|ctl_down)$/ && !$_->{maint} && !$_->{behind} } @ev;
    if (@dn > 5) {
        $_->{quiet} = 1 for @dn;
        my %n; $n{ $_->{type} }++ for @dn;
        push @ev, { t => $dn[-1]{t}, rt => $rt, type => 'many_down', name => ($p->{status} || {})->{location} // $site->{id},
                    text => join(', ', ($n{dev_down} ? "$n{dev_down} not responding" : ()), ($n{ap_missing} ? "$n{ap_missing} access points missing" : ()),
                                       ($n{ctl_down} ? "$n{ctl_down} controllers unreachable" : ())) };
    }
    append_jsonl($g, 'events.jsonl', @ev) if @ev;
    # parts of a large backlog come without the Wi-Fi clients: keep the ones of the last report
    my $clients = exists $p->{clients} ? $p->{clients} : (read_json("$dir/latest.json") || {})->{clients};
    write_json("$dir/latest.json", { received => time + 0, from => $peer, sent => $p->{sent},
                                     status => $p->{status}, clients => $clients,
                                     (ref $p->{agent} eq 'HASH' ? (agent => $p->{agent}) : ()) });
    # 7.13 agent: its mails are sent from here, its state is kept for its restart
    my %ag;
    if (ref $p->{mails} eq 'ARRAY' && @{ $p->{mails} }) {
        my ($ok, $fail) = agent_mails($cfg, $site, $dir, $p->{mails});
        $ag{mails_ok} = $ok;
        $ag{mails_failed} = $fail if %$fail;
    }
    if (ref $p->{backup} eq 'HASH' && ref $p->{backup}{files} eq 'HASH') {
        write_json("$dir/agent-backup.json", { t => time + 0, files => $p->{backup}{files} });
        $ag{backup_ok} = JSON::PP::true;
    }
    if (defined(my $md5 = agent_conf_md5($cfg, $site->{id}))) { $ag{agent_config_md5} = $md5 }
    # maintenance windows set in the centre: confirmed ones are done, the others go with this answer
    my $cmds = cmd_load($cfg, $site->{id});
    if (ref $p->{ack} eq 'ARRAY' && @{ $p->{ack} }) {
        my %a = map { $_ => 1 } grep { defined && !ref } @{ $p->{ack} };
        my @left = grep { !$a{ $_->{id} } } @$cmds;
        logmsg('info', "Site $site->{id}: mtmon confirmed " . (@$cmds - @left) . " maintenance command(s)") if @left < @$cmds;
        cmd_save($cfg, $site->{id}, $cmds = \@left);
    }
    eval { hist_maintain($g, $_, time) for qw(history clients clientsap devstats); 1 }
        or logmsg('warn', "Site $site->{id}: history: $@");
    close $lk;
    logmsg('debug', "Site $site->{id}: report from $peer (" . length($body) . " bytes), " . ($n{history} // 0) . " history, "
                  . ($n{clients} // 0) . " client record(s), " . scalar(@ev) . " event(s)");
    return (200, { ok => JSON::PP::true, site => $site->{id}, stored => { %n, events => scalar @ev },
                   version => $VERSION, mtmon_min => $MTMON_MIN, mtmon_current => $MTMON_VERSION, %ag,
                   (@$cmds ? (commands => [ map { my %c = %$_; delete $c{t}; \%c } @$cmds ]) : ()) });
}

# ==========================================================================
# 7.21: the whole local history of a site (mtmon 13.13+: by itself on its first contact, and with
# mtmon --central-resend) - POST /api/v1/history, one file in parts: { file, start, end, lines }.
# The parts gather in sites/ID/.resend-FILE; with the last one they are merged into FILE: what the
# centre has stays, the hours and days of the mtmon replace its own (the centre may have only a part
# of an hour or a day), an event is kept once. No push or mail comes from what is merged.
# ==========================================================================
sub history_in {
    my ($cfg, $site, $body, $peer) = @_;
    my $p = eval { json_fast()->decode($body) };
    return (400, { error => 'invalid JSON' }) unless ref $p eq 'HASH' && ref $p->{lines} eq 'ARRAY';
    my $f = $p->{file} // '';
    return (400, { error => "unknown history file '$f'" }) unless $f =~ /^(?:(?:history|clients|clientsap|devstats)(?:-1h|-1d)?|events)\.jsonl$/;
    my $dir = site_dir($cfg, $site->{id});
    make_path($dir) unless -d $dir;
    open(my $lk, '>', "$dir/.lock") or return (500, { error => "cannot lock: $!" });
    flock($lk, LOCK_EX);
    my $stage = "$dir/.resend-$f";
    open(my $fh, ($p->{start} ? '>' : '>>') . ':raw', $stage) or return (500, { error => "cannot write $stage: $!" });
    my $js = json_fast();
    my $out = JSON::PP->new->utf8->canonical;
    my $n = 0;
    for my $l (@{ $p->{lines} }) {
        next if ref $l || !defined $l;
        my $r = eval { $js->decode(encode('UTF-8', $l)) };       # the lines came as text inside the request
        next unless ref $r eq 'HASH' && ($r->{t} // '') =~ /^\d{9,11}$/;
        delete @$r{qw(rt quiet)};
        print {$fh} $out->encode($r), "\n";
        $n++;
    }
    close $fh or return (500, { error => "writing $stage failed: $!" });
    my %res = (ok => JSON::PP::true, received => $n);
    if ($p->{end}) {
        my ($add, $rep, $total) = resend_merge("$dir/$f", $stage);
        unlink $stage;
        File::Path::remove_tree("$dir/report-cache") if -d "$dir/report-cache";   # reports of finished months: computed again
        logmsg('info', "Site $site->{id}: history from $peer merged into $f: $add new, $rep replaced, $total in all");
        %res = (%res, merged => JSON::PP::true, added => $add, replaced => $rep, total => $total);
    }
    close $lk;
    return (200, \%res);
}

# merge the gathered parts into the file -> (added, replaced, records in all)
sub resend_merge {
    my ($target, $stage) = @_;
    my $ev = $target =~ m{/events\.jsonl$};
    my $roll = $target =~ m{-1[hd]\.jsonl$};
    my $js = JSON::PP->new->utf8->canonical;
    my $key = sub {
        my ($l) = @_;
        if (!$ev) { return $l =~ /"t":\s*(\d+)/ ? $1 : undef }
        my $r = eval { $js->decode($l) } or return undef;
        delete @$r{qw(rt quiet)};
        return $js->encode($r);
    };
    my (%at, @out);
    for my $l (read_lines($target)) {
        $l =~ s/\s+$//;
        next unless length $l;
        my $k = $key->($l) // next;
        next if exists $at{$k};
        my ($t) = $l =~ /"t":\s*(\d+)/;
        $at{$k} = scalar @out;
        push @out, [ $t // 0, $l ];
    }
    my ($add, $rep) = (0, 0);
    for my $l (read_lines($stage)) {
        $l =~ s/\s+$//;
        next unless length $l;
        my $k = $key->($l) // next;
        if (exists $at{$k}) {
            if ($roll && $out[ $at{$k} ][1] ne $l) {
                # the same hour / day: the mtmon's (complete) one, when it says something else
                my ($x, $y) = map { my $r = eval { $js->decode($_) }; $r ? $js->encode($r) : $_ } $out[ $at{$k} ][1], $l;
                if ($x ne $y) { $out[ $at{$k} ][1] = $l; $rep++ }
            }
            next;
        }
        my ($t) = $l =~ /"t":\s*(\d+)/;
        $at{$k} = scalar @out;
        push @out, [ $t // 0, $l ];
        $add++;
    }
    return (0, 0, scalar @out) unless $add || $rep;
    my $i = 0;
    @out = map { $_->[1] } sort { $a->[0] <=> $b->[0] || $a->[2] <=> $b->[2] } map { [ @$_, $i++ ] } @out;
    my ($fh, $tmp) = tempfile('.merge-XXXXXX', DIR => dirname($target));
    binmode $fh;
    print {$fh} map { "$_\n" } @out;
    close $fh or die "Writing $target failed: $!\n";
    chmod((stat $target)[2] & 07777, $tmp) if -e $target;
    rename($tmp, $target) or die "Cannot rename $tmp to $target: $!\n";
    return ($add, $rep, scalar @out);
}

# ==========================================================================
# 7.13: agents - an mtmon without a disk (mtmon --agent, a MikroTik container). Its configuration is
# sites/ID/agent.conf here, its mails are sent from here, its state for a restart is kept here.
# ==========================================================================
sub agent_conf_file { site_dir($_[0], $_[1]) . '/agent.conf' }
sub agent_conf_read {
    my ($cfg, $id) = @_;
    open(my $fh, '<:raw', agent_conf_file($cfg, $id)) or return undef;
    local $/;
    my $t = <$fh>;
    close $fh;
    return decode('UTF-8', $t, Encode::FB_DEFAULT);
}
sub agent_conf_md5 { my $t = agent_conf_read(@_); return defined $t ? md5_hex(encode('UTF-8', $t)) : undef }
sub agent_conf_write {
    my ($cfg, $id, $text) = @_;
    my $f = agent_conf_file($cfg, $id);
    make_path(dirname($f)) unless -d dirname($f);
    $text =~ s/\r\n?/\n/g;
    $text .= "\n" unless $text =~ /\n\z/;
    my $old = -e $f ? agent_conf_read($cfg, $id) : undef;
    if (defined $old && $old ne $text) {                                   # the previous one stays as agent.conf.prev
        my $o;
        if (open($o, '>:raw', "$f.prev")) { print {$o} encode('UTF-8', $old); close $o; chmod 0600, "$f.prev" }
    }
    my ($fh, $tmp) = tempfile('.agent-XXXXXX', DIR => dirname($f));
    binmode $fh;
    print {$fh} encode('UTF-8', $text);
    close $fh or die "Writing $f failed: $!\n";
    chmod 0600, $tmp;
    rename $tmp, $f or die "Cannot write $f: $!\n";
    return md5_hex(encode('UTF-8', $text));
}

# what a new agent starts with: the sections an agent usually needs (everything of mtmon.conf works)
sub agent_template {
    my ($id) = @_;
    return <<"EOT";
# mtmon agent of site '$id' - the configuration of mtmon (see the mtmon manual, the same settings).
# The agent fetches it from the centre: a change here reaches it with its next report (one interval).
# Not needed here: [central] (the container's MTMON_CENTRAL / MTMON_KEY), state_file (RAM disk of the
# container), [mail] (the centre sends the mails of this site to mail= of the site in [sites] of the
# centre, or to [mail] to below), [report] (the centre sends the reports).

[general]
location = $id
interval = 300

# recipients of this site's mails (empty: mail= of the site on the centre, else the centre's [mail] to)
[mail]
# to = noc\@example.com
subject_prefix = [mtmon $id]
format = html

# the CAPsMAN of this router: the container reaches the router at the address of its veth gateway
# (e.g. 172.17.0.1); RouterOS API user with read rights: /user add name=mtmon group=read password=...
#[capsman CAPsMAN]
#host     = 172.17.0.1
#method   = api
#user     = mtmon
#password = secret

# switches and other devices: pinged; with snmp = yes also ports, PoE, temperature, VLANs, LLDP
[switches]
#snmp      = yes
#community = public
#10.0.0.11 = SW-core | uplinks=49,50
EOT
}

sub agent_conf_cli {
    my ($cfg, $id) = @_;
    die "--agent-config: site '$id' is not in [sites] of $cfg->{_file} (mtmon-admin-center --add-site $id --agent)\n" unless $cfg->{sites}{$id};
    my $f = agent_conf_file($cfg, $id);
    if (!-e $f) { agent_conf_write($cfg, $id, agent_template($id)); print "Created $f from the agent template.\n" }
    else { print "$f\n" }
    my $lt = site_latest($cfg, $id);
    my $a = $lt && $lt->{agent};
    print "Edit it (or on the centre's page: the site card -> Agent config); the agent takes it with its next report.\n";
    if ($a) {
        my $md5 = agent_conf_md5($cfg, $id) // '';
        print "Agent: mtmon $a->{version}, last report " . fmt_time($lt->{received}) . ", configuration "
            . (($a->{config_md5} // '') eq $md5 ? 'applied' : 'not applied yet') . "\n";
        print "  error in the configuration: $a->{config_error}\n" if $a->{config_error};
    } else { print "No report from the agent yet.\n" }
    return 0;
}

# a first check of an agent configuration on saving (the agent checks it completely and reports errors)
sub agent_conf_lint {
    my ($text) = @_;
    my ($n, $sec) = (0);
    for my $l (split /\r?\n/, $text) {
        $n++;
        $l =~ s/^\s+|\s+$//g;
        next if $l eq '' || $l =~ /^[#;]/;
        if ($l =~ /^\[\s*(.+?)\s*\]$/) {
            $sec = lc $1;
            return "Line $n: unknown section [$1] (general, mail, ssh, switches, web, report, certificates, capsman NAME, msm NAME, cnpilot NAME, web users, api keys)"
                unless $sec =~ /^(general|mail|ssh|switches|web|central|report|certificates|web[\s_]+users|api[\s_]+keys)$/ || $sec =~ /^(capsman|msm|cnpilot)([\s:]+.+)?$/;
            next;
        }
        return "Line $n: outside of any section (the first line must be a section, e.g. [general])" unless defined $sec;
        return "Line $n: expected key = value" unless $l =~ /^[^=]+?\s*=/;
    }
    return undef;
}

# the mails of an agent: sent from here, each once (the agent sends one again until it is confirmed)
sub agent_mails {
    my ($cfg, $site, $dir, $mails) = @_;
    my (@ok, %fail);
    my $f = "$dir/agent-mails.json";
    my $seen = read_json($f) || { ids => [] };
    my %done = map { $_ => 1 } @{ $seen->{ids} || [] };
    for my $m (grep { ref $_ eq 'HASH' && ($_->{id} // '') =~ /^[0-9a-f]{32}$/ } @$mails) {
        if ($done{ $m->{id} }) { push @ok, $m->{id}; next }
        my $to = length($m->{to} // '') ? $m->{to} : length($site->{mail} // '') ? $site->{mail} : $cfg->{mail}{to};
        if (!length($to // '')) { $fail{ $m->{id} } = 'no recipient: set mail= of the site on the centre, [mail] to of the centre or [mail] to in the agent configuration'; next }
        my $mc = { %$cfg, mail => { %{ $cfg->{mail} }, to => $to, subject_prefix => substr($m->{prefix} // '[mtmon]', 0, 100) } };
        my $subj = substr($m->{subject} // 'Status change', 0, 400);
        if (eval { send_mail($mc, $subj, $m->{text} // '', (defined $m->{html} && length $m->{html} < 2_000_000 ? $m->{html} : undef)); 1 }) {
            push @ok, $m->{id};
            push @{ $seen->{ids} }, $m->{id};
            logmsg('info', "Site $site->{id}: mail of the agent sent to $to: $subj");
        } else {
            ($fail{ $m->{id} } = "$@") =~ s/\s+$//;
            logmsg('error', "Site $site->{id}: mail of the agent to $to not sent: $fail{ $m->{id} }");
        }
    }
    splice @{ $seen->{ids} }, 0, @{ $seen->{ids} } - 500 if @{ $seen->{ids} } > 500;
    write_json($f, $seen) if @ok;
    return (\@ok, \%fail);
}

# the events the centre writes into a site's events.jsonl itself
# ==========================================================================
# backup and restore of the whole centre (7.20)
#
# A backup is one .tar.gz (mode 0600 - it holds the passwords, site keys and the private key):
#   mtmon-backup.json  what it is: version, server, time, config folder, data_dir, sites
#   config/            center.conf and the certificate files of its folder (*.crt, *.key, *.pem)
#   certs/             cert_file / key_file kept outside that folder (written back only by --restore)
#   data/              everything in data_dir except the backup folder and restore/
# It is made in a child of the daemon (on schedule, or when the web page asks - a file .request.json
# in the backup folder), or by --backup. A restore is staged as data_dir/restore/pending.tar.gz;
# the daemon then exits with 75 and the start after it applies it as root - systemd runs
# "--apply-restore" as ExecStartPre=+, the container starts the centre as root - before the
# centre reads its configuration. Before anything is replaced a copy of the state is made
# (kind before-restore); a step that fails puts everything back.
# ==========================================================================

sub bk_dir     { $_[0]{backup}{dir} }
sub bk_rdir    { "$_[0]{general}{data_dir}/restore" }
sub bk_state_f { "$_[0]{general}{data_dir}/backup-state.json" }      # in data_dir: writable also when the backup folder is not
sub bk_req_f   { "$_[0]{general}{data_dir}/backup-request.json" }
sub bk_name_ok { my $n = $_[0] // ''; return $n =~ /^[A-Za-z0-9][A-Za-z0-9._-]{0,150}\.tar\.gz$/ && $n !~ /\.\./ }
sub bk_host    { my $h = (split /\./, hostname())[0] // 'centre'; $h =~ s/[^A-Za-z0-9-]+/-/g; return $h }
# who may make, download and restore backups: role full (not operator) and every site
sub bk_admin {
    my ($who, $cfg) = @_;
    return ($who->{role} // '') eq 'full' && !$who->{operator} && !$who->{sites} && !$who->{_push} ? 1 : 0;
}
sub bk_user    { my @pw = getpwnam('mtmon-center'); return @pw ? @pw[2, 3] : () }

# files and folders made as root belong to the service user (as data_dir does)
sub bk_own {
    my (@p) = @_;
    return unless $> == 0;
    my ($uid, $gid) = bk_user() or return;
    chown $uid, $gid, grep { -e } @p;
}

# run a command; its errors go to the file $err, its output to $out -> exit code (-1: did not run)
sub bk_run {
    my ($cmd, $err, $out) = @_;
    local $SIG{CHLD} = 'DEFAULT';
    my $pid = fork;
    die "fork: $!\n" unless defined $pid;
    if (!$pid) {
        open(STDIN, '<', '/dev/null');
        open(STDOUT, '>', $out // '/dev/null');
        open(STDERR, '>', $err // '/dev/null');
        { no warnings 'exec'; exec { $cmd->[0] } @$cmd; }
        POSIX::_exit(127);
    }
    waitpid($pid, 0) == $pid or return -1;
    return $? & 127 ? -1 : $? >> 8;
}
sub bk_text { my ($f) = @_; open(my $fh, '<:encoding(UTF-8)', $f) or return ''; local $/; my $t = <$fh> // ''; close $fh; $t =~ s/\s+$//; return $t }
sub bk_lines { my ($f) = @_; open(my $fh, '<:encoding(UTF-8)', $f) or return (); chomp(my @l = <$fh>); close $fh; return @l }
sub bk_tmp { my ($dir, $tag) = @_; return "$dir/.$tag-$$-" . int(rand 1e9) }
sub bk_firsterr { my $t = bk_text($_[0]); my @l = grep { length } split /\n/, $t; return join(' / ', @l[0 .. ($#l < 2 ? $#l : 2)]) }

sub bk_mv {                                      # rename, or mv across file systems
    my ($a, $b) = @_;
    return 1 if rename $a, $b;
    die "Cannot move $a to $b: $!\n" unless bk_run([ 'mv', $a, $b ]) == 0;
    return 1;
}

# ---- what a backup is ---------------------------------------------------------------------
sub bk_manifest {
    my ($file) = @_;
    my $tmp = bk_tmp(dirname($file) =~ m{^/} && -w dirname($file) ? dirname($file) : '/tmp', 'mf');
    my $rc = bk_run([ 'tar', '-x', '-z', '-O', '-f', $file, 'mtmon-backup.json' ], "$tmp.err", "$tmp.out");
    my $raw = '';
    if (open(my $fh, '<:raw', "$tmp.out")) { local $/; $raw = <$fh> // ''; close $fh }
    my $err = bk_firsterr("$tmp.err");
    unlink "$tmp.out", "$tmp.err";
    my $m = length $raw ? eval { JSON::PP->new->utf8->decode($raw) } : undef;
    die "Not a backup of mtmon-admin-center (no mtmon-backup.json" . (length $err ? ": $err" : '') . ")\n"
        unless ref $m eq 'HASH' && ($m->{product} // '') eq 'mtmon-admin-center';
    die "This backup has format $m->{format}; this centre reads format 1\n" unless ($m->{format} // 0) == 1;
    return $m;
}

# the whole file read through: only plain files and folders, only the parts a backup has, nothing
# that leaves the folder it is unpacked into -> manifest (with the number of files)
sub bk_inspect {
    my ($file) = @_;
    die "$file: no such file\n" unless -f $file;
    my $dir = dirname($file);
    my $tmp = bk_tmp(-w $dir ? $dir : '/tmp', 'ls');
    my $rc = bk_run([ 'tar', '-t', '-z', '-f', $file ], "$tmp.err", "$tmp.out");
    my @names = bk_lines("$tmp.out");
    my $err = bk_firsterr("$tmp.err");
    if ($rc != 0) { unlink "$tmp.out", "$tmp.err"; die "Cannot read the file as .tar.gz (damaged or not complete)" . (length $err ? ": $err" : '') . "\n" }
    $rc = bk_run([ 'tar', '-t', '-v', '-z', '-f', $file ], "$tmp.err", "$tmp.out");
    my @long = bk_lines("$tmp.out");
    unlink "$tmp.out", "$tmp.err";
    die "Cannot read the file as .tar.gz\n" if $rc != 0;
    my %has;
    for my $n (@names) {
        (my $x = $n) =~ s{^\./}{};
        $x =~ s{/+$}{};
        next if $x eq '' || $x eq '.';
        die "The backup holds an unsafe name: $n\n" if $x =~ m{^/} || grep { $_ eq '..' || $_ eq '.' || $_ eq '' } split m{/}, $x;
        die "The backup holds a file that is not part of a centre backup: $n\n" unless $x eq 'mtmon-backup.json' || $x =~ m{^(?:config|certs|data)(?:/|$)};
        $has{$x} = 1;
    }
    for my $l (@long) {
        my $t = substr($l, 0, 1);
        die "The backup holds a link or a special file (only plain files and folders are restored): $l\n" unless $t eq '-' || $t eq 'd';
    }
    die "The backup has no mtmon-backup.json\n" unless $has{'mtmon-backup.json'};
    my $m = bk_manifest($file);
    my $cn = $m->{config_name} // '';
    die "The backup names an invalid configuration file '$cn'\n" unless $cn =~ /^[A-Za-z0-9][\w.-]*$/;
    die "The backup has no config/$cn\n" unless $has{"config/$cn"};
    for my $ce (@{ $m->{certs} || [] }) {
        die "The backup names an invalid certificate file\n" unless ($ce->{file} // '') =~ m{^certs/[A-Za-z0-9][\w.-]*$} && $has{ $ce->{file} }
                                                               && ($ce->{path} // '') =~ m{^/} && ($ce->{key} // '') =~ /^(cert_file|key_file)$/;
    }
    die "The backup names no data_dir\n" unless ($m->{data_dir} // '') =~ m{^/};
    $m->{files} = scalar grep { !m{/$} } @names;
    return $m;
}

sub bk_newer_check {
    my ($m) = @_;
    die "This backup is from mtmon-admin-center $m->{version}, newer than this centre ($VERSION). Install $m->{version} or newer here first, then restore.\n"
        if vcmp($m->{version} // '0', $VERSION) > 0;
}

# ---- making one ---------------------------------------------------------------------------
# -> the note kept next to it (name, size, created, kind, by, version, host, title, sites); dies on failure
sub bk_create {
    my ($cfg, $kind, $by, $out) = @_;
    my $g = $cfg->{general};
    my $cfile = File::Spec->rel2abs($cfg->{_file});
    my $cdir = dirname($cfile);
    my $dir = bk_dir($cfg);
    my $name = sprintf('mtmon-center-backup-%s-%s.tar.gz', bk_host(), strftime('%Y%m%d-%H%M%S', localtime));
    if (defined $out && length $out) {
        if (-d $out) { $dir = $out =~ s{/+$}{}r }
        else {
            ($dir, $name) = (dirname($out), File::Basename::basename($out));
            $name .= '.tar.gz' unless $name =~ /\.tar\.gz$|\.tgz$/;
        }
    }
    if (!-d $dir) { make_path($dir, { mode => 0700, error => \my $e }); die "Cannot make the folder $dir\n" unless -d $dir; bk_own($dir) if $dir eq bk_dir($cfg) }
    die "The folder $dir is not writable for " . (getpwuid($>))[0] . "\n" unless -w $dir;
    if (!(defined $out && length $out && !-d $out)) {       # two in the same second: -2, -3 …
        my ($b, $i) = ($name =~ s/\.tar\.gz$//r, 2);
        $name = "$b-" . $i++ . '.tar.gz' while -e "$dir/$name";
    }
    my $file = "$dir/$name";
    die "$file exists already\n" if -e $file;
    my $dd = File::Spec->rel2abs($g->{data_dir});

    # room: the packed data is about a third of data_dir (history, events and the reports pack well)
    my $ss = jread("$dd/server.json");
    my $top = (($ss || {})->{du} || {})->{top} || {};
    my %skip = (restore => 1, 'lost+found' => 1, 'backup-request.json' => 1, 'backup-state.json' => 1, 'center.pid' => 1);
    if (index("$dir/", "$dd/") == 0) { my ($t) = substr($dir, length($dd) + 1) =~ m{^([^/]+)}; $skip{$t} = 1 if defined $t }
    my $est = 0; $est += $top->{$_} // 0 for grep { !$skip{$_} } keys %$top;
    my $df = sys_df($dir);
    die sprintf("Not enough free space in %s: %s free, the backup needs about %s\n", $dir, fmt_bytes($df->{avail}), fmt_bytes(int($est * 0.4) + 50e6))
        if $df && defined $df->{avail} && $est && $df->{avail} < $est * 0.4 + 50e6;

    my $work = bk_tmp($dir, 'work');
    make_path("$work/config", "$work/data", { mode => 0700 });
    my $ok = eval {
        my (%seen, @certs);
        my $conf = sub { my ($p) = @_; my $b = File::Basename::basename($p); return if $seen{$b}++; symlink($p, "$work/config/$b") or die "symlink $p: $!\n" };
        die "$cfile is not readable\n" unless -r $cfile;
        $conf->($cfile);
        for my $k (qw(cert_file key_file)) {
            my $p = $cfg->{web}{$k} // '';
            next unless length $p && -f $p;
            $p = File::Spec->rel2abs($p);
            die "$p is not readable for " . (getpwuid($>))[0] . "\n" unless -r $p;
            if (dirname($p) eq $cdir) { $conf->($p); next }
            make_path("$work/certs");
            my $b = (scalar(@certs) + 1) . '-' . File::Basename::basename($p);
            symlink($p, "$work/certs/$b") or die "symlink $p: $!\n";
            push @certs, { key => $k, path => $p, file => "certs/$b" };
        }
        if (opendir(my $dh, $cdir)) {
            for (sort grep { !/^\./ && /\.(?:crt|key|pem)$/ } readdir $dh) { my $p = "$cdir/$_"; $conf->($p) if -f $p && -r _ }
            closedir $dh;
        }
        opendir(my $dh, $dd) or die "Cannot read $dd: $!\n";
        for my $f (sort readdir $dh) {
            next if $f eq '.' || $f eq '..' || $skip{$f} || $f =~ /^\.(?:work|tmp|mf|ls|upload)-/;
            symlink("$dd/$f", "$work/data/$f") or die "symlink $dd/$f: $!\n";
        }
        closedir $dh;
        my @sites = sort keys %{ $cfg->{sites} };
        my $m = { format => 1, product => 'mtmon-admin-center', version => $VERSION, mtmon_version => $MTMON_VERSION, created => time + 0,
                  host => hostname(), title => $g->{title}, kind => $kind, by => $by // '', config_dir => $cdir,
                  config_name => File::Basename::basename($cfile), data_dir => $dd, certs => \@certs, sites => \@sites };
        write_json("$work/mtmon-backup.json", $m);
        # -h: the symbolic links above are followed, so the archive holds the files themselves
        my $rc = bk_run([ 'tar', '-c', '-z', '-h', '-f', "$file.part", '-C', $work, 'mtmon-backup.json', 'config', 'data', (@certs ? 'certs' : ()) ], "$work/.err");
        # 1 = a file changed while it was read (GNU tar; the centre keeps writing) - usable when it reads back
        die "tar failed (exit $rc): " . bk_firsterr("$work/.err") . "\n" if $rc != 0 && $rc != 1;
        my $chk = eval { bk_inspect("$file.part") };
        die "The new backup does not read back: " . ("$@" =~ s/\s+$//r) . (-s "$work/.err" ? ' (tar: ' . bk_firsterr("$work/.err") . ')' : '') . "\n" unless $chk;
        chmod 0600, "$file.part";
        rename("$file.part", $file) or die "rename: $!\n";
        my $note = { name => $name, size => (-s $file) + 0, created => $m->{created}, kind => $kind, by => $by // '', version => $VERSION,
                     host => $m->{host}, title => $m->{title}, sites => scalar(@sites), files => $chk->{files} };
        write_json("$file.json", $note);
        bk_own($file, "$file.json") if $dir eq bk_dir($cfg);
        $note;
    };
    my $err = $@;
    File::Path::remove_tree($work);
    unlink "$file.part";
    die $err unless $ok;
    return $ok;
}

# the backups in the backup folder, newest first
sub bk_list {
    my ($cfg) = @_;
    my $dir = bk_dir($cfg);
    opendir(my $dh, $dir) or return ();
    my @r;
    for my $f (grep { bk_name_ok($_) } readdir $dh) {
        my $p = "$dir/$f";
        next unless -f $p;
        my $size = (-s _) + 0;
        my $s = read_json("$p.json");
        if (!$s || ($s->{size} // -1) != $size) {
            # copied here by hand (or its note is gone): what it is comes from the backup itself
            my $m = eval { bk_manifest($p) };
            $s = { name => $f, size => $size, kind => ($s && $s->{kind}) || ($m ? 'copied' : 'unknown'), by => ($s && $s->{by}) // '',
                   created => $m ? $m->{created} : (stat $p)[9], ($m ? (version => $m->{version}, host => $m->{host}, title => $m->{title}, sites => scalar @{ $m->{sites} || [] }) : (error => 'not a centre backup')) };
            eval { write_json("$p.json", $s) } if $m && -w $dir;
        }
        $s->{name} = $f;
        $s->{size} = $size;
        push @r, $s;
    }
    closedir $dh;
    return sort { ($b->{created} // 0) <=> ($a->{created} // 0) || $b->{name} cmp $a->{name} } @r;
}

# automatic ones: keep = N; copies before a restore: the last 3; the others stay until deleted
sub bk_prune {
    my ($cfg) = @_;
    my %lim = (auto => $cfg->{backup}{keep}, 'before-restore' => 3);
    my %n;
    for my $b (bk_list($cfg)) {
        my $k = $b->{kind} // '';
        next unless exists $lim{$k};
        next if ++$n{$k} <= $lim{$k};
        unlink map { bk_dir($cfg) . "/$b->{name}$_" } '', '.json';
        logmsg('info', "Backup $b->{name} removed ($k: the newest $lim{$k} stay)");
    }
}

# ---- schedule -----------------------------------------------------------------------------
sub bk_slot {                                    # the slot (daily / weekly at time) at or before $t (dir < 0) or after it
    my ($b, $t, $dir) = @_;
    my @n = localtime $t;
    my $noon = Time::Local::timelocal(0, 0, 12, @n[3, 4, 5]);
    for my $d (0 .. 8) {
        my @l = localtime($noon + ($dir < 0 ? -$d : $d) * 86400);
        next if $b->{_auto} eq 'weekly' && $l[6] != $b->{_wd};
        my $s = Time::Local::timelocal(0, $b->{_hm}[1], $b->{_hm}[0], @l[3, 4, 5]);
        return $s if $dir < 0 ? $s <= $t : $s > $t;
    }
    return undef;
}
# when the next automatic backup is due (<= now: due now); undef: none
sub bk_next {
    my ($cfg, $last, $now) = @_;
    my $b = $cfg->{backup};
    return undef if $b->{_auto} eq 'off';
    return $last ? $last + $b->{_hours} * 3600 : $now if $b->{_auto} eq 'hours';
    my $s = bk_slot($b, $now, -1);
    return $now if defined $s && ($last // 0) < $s;
    return bk_slot($b, $now, 1);
}

# the last automatic or manual backup failed, or the last restore did (within a day) -> the menu shows "!"
sub bk_alert {
    my ($cfg) = @_;
    my $st = read_json(bk_state_f($cfg)) || {};
    return 1 if $st->{last} && !$st->{last}{ok};
    my $rl = read_json(bk_rdir($cfg) . '/last.json');
    return $rl && !$rl->{ok} && time - ($rl->{t} // 0) < 86400 ? 1 : 0;
}
sub bk_state { my $s = read_json(bk_state_f($_[0])) || {}; delete $s->{running} if $s->{running} && !($s->{running}{pid} && kill(0, $s->{running}{pid})); return $s }

# start one in a child of the daemon
sub bk_start {
    my ($cfg, $kind, $by) = @_;
    my $dir = bk_dir($cfg);
    if (!-d $dir) { make_path($dir, { mode => 0700, error => \my $e }) }
    my $st = read_json(bk_state_f($cfg)) || {};
    $st->{last_auto} = time + 0 if $kind eq 'auto';
    $st->{running} = { kind => $kind, by => $by // '', started => time + 0 };
    eval { write_json(bk_state_f($cfg), $st); 1 } or do { logmsg('error', "Backup: cannot write " . bk_state_f($cfg) . ": $@"); return };
    my $pid = fork;
    if (!defined $pid) { logmsg('error', "Backup: fork failed: $!"); delete $st->{running}; eval { write_json(bk_state_f($cfg), $st) }; return }
    if ($pid) { $BK_PID = $pid; return }
    $0 = 'mtmon-center-backup';
    $SIG{$_} = 'DEFAULT' for qw(TERM INT HUP);
    my $s = read_json(bk_state_f($cfg)) || {};
    $s->{running}{pid} = $$;
    eval { write_json(bk_state_f($cfg), $s) };
    my $t0 = time;
    my $r = eval { bk_create($cfg, $kind, $by) };
    my $err = $r ? '' : ("$@" =~ s/\s+$//r);
    $s = read_json(bk_state_f($cfg)) || {};
    delete $s->{running};
    $s->{last} = { t => time + 0, kind => $kind, by => $by // '', ok => ($r ? JSON::PP::true : JSON::PP::false), took => time - $t0,
                   ($r ? (name => $r->{name}, size => $r->{size}) : (error => $err)) };
    $s->{ $r ? 'last_ok' : 'last_fail' } = time + 0;
    $s->{fail_kind} = $kind unless $r;
    eval { write_json(bk_state_f($cfg), $s) };
    if ($r) {
        logmsg('info', sprintf('Backup %s made (%s, %s, %d s)', $r->{name}, $kind, fmt_bytes($r->{size}), time - $t0));
        eval { bk_prune($cfg) };
    } else {
        logmsg('error', "Backup ($kind) failed: $err");
        if ($kind eq 'auto' && $cfg->{backup}{mail} && length $cfg->{mail}{to}) {
            my $body = "$cfg->{general}{title}\n\nThe automatic backup of the centre failed at " . fmt_time(time) . ":\n\n  $err\n\n"
                     . "Folder: " . bk_dir($cfg) . "\nThe previous backups are kept. Make one by hand in the web (Backup) or with\n"
                     . "  mtmon-admin-center --backup\nonce the cause is fixed.\n";
            eval { send_mail($cfg, 'Backup of the centre FAILED', $body, undef); 1 } or logmsg('error', "Sending mail failed: $@");
        }
    }
    POSIX::_exit(0);
}

# every 2 s in the daemon: the child done? a request from the web page? one due? a restore staged?
sub bk_check {
    my ($cfg, $now) = @_;
    if ($BK_PID && waitpid($BK_PID, WNOHANG) != 0) { $BK_PID = 0 }
    my $pj = bk_rdir($cfg) . '/pending.json';
    if (-e $pj && ((stat _)[9] // 0) >= $^T) {
        logmsg('warn', 'A restore from a backup is waiting - stopping, the next start applies it');
        waitpid($BK_PID, 0) if $BK_PID;
        $BK_RESTART = 1;
        return 'restart';
    }
    return '' if $BK_PID;
    my $rq = bk_req_f($cfg);
    if (-e $rq) { my $r = read_json($rq) || {}; unlink $rq; bk_start($cfg, 'manual', $r->{by} // ''); return '' }
    my $st = read_json(bk_state_f($cfg)) || {};
    my $n = bk_next($cfg, $st->{last_auto}, $now);
    bk_start($cfg, 'auto', '') if defined $n && $n <= $now;
    return '';
}

# ---- restoring ----------------------------------------------------------------------------
# the daemon of this configuration (its pid file in data_dir) -> pid, or 0
sub bk_daemon_running {
    my ($cfgfile) = @_;
    my $cfg = eval { load_config($cfgfile) } or return 0;
    open(my $fh, '<', "$cfg->{general}{data_dir}/center.pid") or return 0;
    my $p = <$fh> // ''; close $fh;
    ($p) = $p =~ /^(\d+)/ or return 0;
    return 0 if $p == $$;
    open(my $ch, '<:raw', "/proc/$p/cmdline") or return 0;
    my $c = <$ch> // ''; close $ch;
    return $c =~ /^mtmon-center[\0 ]*$/ ? $p : 0;
}

# put a backup in place for the next start (the web page, --restore while the centre runs)
sub bk_stage {
    my ($cfg, $file, $by, $name) = @_;
    my $m = bk_inspect($file);
    bk_newer_check($m);
    die "The backup keeps its data in $m->{data_dir}, this centre in $cfg->{general}{data_dir}. Restore it with "
      . "mtmon-admin-center --restore FILE (as root), or set the same data_dir first.\n" if $m->{data_dir} ne $cfg->{general}{data_dir};
    my $rd = bk_rdir($cfg);
    make_path($rd, { mode => 0700 }) unless -d $rd;
    my $p = "$rd/pending.tar.gz";
    unlink $p;
    link($file, $p) or File::Copy::copy($file, $p) or die "Cannot copy the backup to $rd: $!\n";
    write_json("$rd/pending.json", { name => $name // File::Basename::basename($file), by => $by // '', t => time + 0,
                                     host => $m->{host}, title => $m->{title}, created => $m->{created}, version => $m->{version} });
    return $m;
}

# put a backup in place - as root, while the centre does not run. $trusted (--restore by root):
# also the certificate files kept outside the config folder and another data_dir. -> notes
sub bk_apply {
    my ($cfgfile, $file, $trusted, $info) = @_;
    die "A restore must run as root\n" if $> != 0;
    $cfgfile = File::Spec->rel2abs($cfgfile);
    my $cur = eval { load_config($cfgfile) };
    my $dd_cur = $cur ? $cur->{general}{data_dir} : '/var/lib/mtmon-admin-center';
    my $m = bk_inspect($file);
    bk_newer_check($m);
    my @notes;
    make_path("$dd_cur/restore", { mode => 0700 }) unless -d "$dd_cur/restore";
    my $work = "$dd_cur/restore/work-$$";
    File::Path::remove_tree($work);
    make_path($work, { mode => 0700 });
    my ($old, @conf_new, @conf_old, @moved_out, @moved_in, $dd);
    my $ok = eval {
        my $rc = bk_run([ 'tar', '-x', '-z', '-o', '-f', $file, '-C', $work ], "$work.err");
        die "Unpacking failed: " . bk_firsterr("$work.err") . "\n" if $rc != 0;
        unlink "$work.err";
        my $nconf = "$work/config/$m->{config_name}";
        my $nc = eval { load_config($nconf) } or die "center.conf of the backup cannot be used: $@";
        $dd = $nc->{general}{data_dir};
        die "The backup keeps its data in $dd, this centre in $dd_cur (restore it with mtmon-admin-center --restore FILE as root)\n" if $dd ne $dd_cur && !$trusted;

        # a copy of what is here now, to go back to
        if ($cur) {
            my $safe = eval { bk_create($cur, 'before-restore', ($info && $info->{by}) // 'restore') };
            die "The copy of the present state failed, nothing was changed: $@" unless $safe;
            push @notes, "The state before the restore: backup $safe->{name}";
            eval { bk_prune($cur) };
        }
        make_path($dd, { mode => 0750 }) unless -d $dd;
        make_path("$dd/restore", { mode => 0700 }) unless -d "$dd/restore";
        $old = "$dd/restore/replaced-" . time;
        make_path("$old/config", "$old/data", { mode => 0700 });

        # the config folder
        my $cdir = dirname($cfgfile);
        my $cname = File::Basename::basename($cfgfile);
        opendir(my $ch, "$work/config") or die "$work/config: $!\n";
        for my $f (sort grep { !/^\.\.?$/ } readdir $ch) {
            my $t = $f eq $m->{config_name} ? "$cdir/$cname" : "$cdir/$f";
            if (-e $t) { File::Copy::copy($t, "$old/config/" . File::Basename::basename($t)) or die "Cannot keep $t: $!\n"; push @conf_old, $t } else { push @conf_new, $t }
            File::Copy::copy("$work/config/$f", "$t.restore") or die "Cannot write $t: $!\n";
            rename("$t.restore", $t) or die "Cannot write $t: $!\n";
        }
        closedir $ch;
        my ($uid, $gid) = bk_user();
        for my $t (@conf_old, @conf_new) {
            my $isconf = File::Basename::basename($t) eq $cname;
            chmod($isconf ? 0640 : 0600, $t);
            chown($isconf ? 0 : $uid, $gid, $t) if defined $uid;
        }
        # certificate files kept outside the config folder
        for my $ce (@{ $m->{certs} || [] }) {
            my $want = $nc->{web}{ $ce->{key} } // '';
            if ($trusted && $want eq $ce->{path}) {
                make_path(dirname($want)) unless -d dirname($want);
                if (-e $want) { File::Copy::copy($want, "$old/config/outside-" . File::Basename::basename($want)); push @conf_old, $want } else { push @conf_new, $want }
                File::Copy::copy("$work/$ce->{file}", $want) or die "Cannot write $want: $!\n";
                chmod 0600, $want; chown $uid, $gid, $want if defined $uid;
                push @notes, "$ce->{key} written to $want";
            } else {
                my $t = "$cdir/restored-" . File::Basename::basename($ce->{path});
                File::Copy::copy("$work/$ce->{file}", $t) or die "Cannot write $t: $!\n";
                chmod 0600, $t; chown $uid, $gid, $t if defined $uid;
                push @conf_new, $t;
                push @notes, "$ce->{key} of the backup was outside the config folder ($ce->{path}); a restore from the web does not write there - it is in $t (copy it there, or point $ce->{key} to it)";
            }
        }

        # the data: what is in data_dir goes aside, the data of the backup takes its place
        my %keep = (restore => 1, 'lost+found' => 1, 'backup-state.json' => 1, 'center.pid' => 1);   # this server's own
        for my $bd (grep { defined } ($cur ? bk_dir($cur) : undef), bk_dir($nc)) {
            next unless index("$bd/", "$dd/") == 0;
            my ($t) = substr($bd, length($dd) + 1) =~ m{^([^/]+)};
            $keep{$t} = 1 if defined $t;
        }
        opendir(my $dh, $dd) or die "$dd: $!\n";
        my @here = grep { $_ ne '.' && $_ ne '..' && !$keep{$_} } readdir $dh;
        closedir $dh;
        for my $e (@here) { bk_mv("$dd/$e", "$old/data/$e"); push @moved_out, $e }
        opendir($dh, "$work/data") or die "$work/data: $!\n";
        my @in = grep { $_ ne '.' && $_ ne '..' && !$keep{$_} } readdir $dh;
        closedir $dh;
        for my $e (@in) { bk_mv("$work/data/$e", "$dd/$e"); push @moved_in, $e }
        bk_run([ 'chown', '-R', "$uid:$gid", $dd ]) if defined $uid;

        # settings new in this version go into the restored center.conf (commented out, as an upgrade does)
        my $tpl = '/usr/share/mtmon-admin-center/center.conf.template';
        if (vcmp($m->{version} // '0', $VERSION) < 0 && -r $tpl) {
            my $r = eval { config_upgrade("$cdir/$cname", $tpl, 'mtmon-admin-center', $VERSION, 0, { 'web users' => [], 'api keys' => [], sites => [] }) };
            push @notes, $r ? ($r->{changed} ? "center.conf brought from $m->{version} to $VERSION (new settings added, commented out)" : ()) : "center.conf could not be upgraded: $@";
            if (-e "$cdir/$cname") { chmod 0640, "$cdir/$cname"; chown 0, $gid, "$cdir/$cname" if defined $gid }
        }
        1;
    };
    my $err = $@;
    if (!$ok && $old) {
        # back as it was
        for my $e (@moved_in)  { eval { bk_mv("$dd/$e", "$work/data/$e") } }
        for my $e (@moved_out) { eval { bk_mv("$old/data/$e", "$dd/$e") } }
        my $cdir = dirname($cfgfile);
        for my $t (@conf_old) {
            my $b = File::Basename::basename($t);
            my $src = -e "$old/config/$b" ? "$old/config/$b" : "$old/config/outside-$b";
            File::Copy::copy($src, $t) if -e $src;
        }
        unlink @conf_new;
        push @notes, 'Everything was put back as it was';
    }
    File::Path::remove_tree($work);
    unlink "$work.err";
    File::Path::remove_tree($old) if $ok && $old;
    die $err . ($old ? "Everything was put back as it was.\n" : '') unless $ok;
    my $rd = "$dd/restore";
    write_json("$rd/last.json", { t => time + 0, ok => JSON::PP::true, name => ($info && $info->{name}) || File::Basename::basename($file), by => ($info && $info->{by}) // '',
                                  host => $m->{host}, title => $m->{title}, created => $m->{created}, version => $m->{version}, sites => scalar @{ $m->{sites} || [] }, notes => \@notes });
    bk_own($rd, "$rd/last.json");
    return @notes;
}

# a restore staged for this start (systemd ExecStartPre=+, or the daemon starting as root)
sub bk_apply_pending {
    my ($cfgfile) = @_;
    my $cur = eval { load_config($cfgfile) };
    my $dd = $cur ? $cur->{general}{data_dir} : '/var/lib/mtmon-admin-center';
    my $rd = "$dd/restore";
    my $p = "$rd/pending.tar.gz";
    return 0 unless -e $p;
    my $info = read_json("$rd/pending.json") || {};
    my $what = ($info->{name} // 'pending.tar.gz') . (length($info->{by} // '') ? " (asked by $info->{by})" : '');
    if ($> != 0) {
        my $e = 'a restore must run as root before the centre starts: the systemd unit needs ExecStartPre=+/usr/bin/mtmon-admin-center --apply-restore '
              . '(or run mtmon-admin-center --apply-restore as root while the centre is stopped)';
        logmsg('error', "Restore of $what not done: $e");
        eval { write_json("$rd/last.json", { t => time + 0, ok => JSON::PP::false, name => $info->{name} // '', by => $info->{by} // '', error => $e }) };
        unlink $p, "$rd/pending.json";
        return 1;
    }
    logmsg('warn', "Restoring the centre from the backup $what");
    my @notes = eval { bk_apply($cfgfile, $p, 0, $info) };
    if (my $e = $@) {
        $e =~ s/\s+$//;
        logmsg('error', "Restore of $what failed: $e");
        make_path($rd) unless -d $rd;
        eval { write_json("$rd/last.json", { t => time + 0, ok => JSON::PP::false, name => $info->{name} // '', by => $info->{by} // '', error => $e }) };
        bk_own($rd, "$rd/last.json");
    } else {
        logmsg('info', "Restore of $what done" . (@notes ? ': ' . join('; ', @notes) : ''));
    }
    unlink $p, "$rd/pending.json";
    return 1;
}

# ---- command line -------------------------------------------------------------------------
sub bk_backup_cli {
    my ($cfg, $out) = @_;
    my $r = eval { bk_create($cfg, 'cli', (getpwuid($<))[0] // '', $out) };
    if (!$r) { print STDERR "Backup failed: $@"; return 1 }
    my $dir = length($out // '') ? (-d $out ? $out =~ s{/+$}{}r : dirname($out)) : bk_dir($cfg);
    printf "Backup %s/%s: %s, %d files, %d site(s)\n", $dir, $r->{name}, fmt_bytes($r->{size}), $r->{files}, $r->{sites};
    print "It holds the passwords, the site keys and the private key of the centre - keep it safe.\n";
    eval { bk_prune($cfg) } if $dir eq bk_dir($cfg);
    return 0;
}
sub bk_list_cli {
    my ($cfg) = @_;
    my @l = bk_list($cfg);
    print "Backups in " . bk_dir($cfg) . ":\n";
    print "  (none)\n" unless @l;
    printf "  %-52s %9s  %-16s %-14s %s\n", $_->{name}, fmt_bytes($_->{size}), fmt_time($_->{created} // 0), $_->{kind} // '', $_->{version} // '' for @l;
    my $st = bk_state($cfg);
    my $n = bk_next($cfg, $st->{last_auto}, time);
    print "Automatic: " . ($cfg->{backup}{_auto} eq 'off' ? 'off' : "$cfg->{backup}{auto}, next " . fmt_time($n // 0) . ", keep $cfg->{backup}{keep}") . "\n";
    print "Last: " . ($st->{last}{ok} ? "$st->{last}{name} at " : 'FAILED at ') . fmt_time($st->{last}{t}) . ($st->{last}{ok} ? '' : " - $st->{last}{error}") . "\n" if $st->{last};
    return 0;
}
sub bk_restore_cli {
    my ($cfgfile, $file) = @_;
    die "--restore must run as root (it writes the config folder)\n" if $> != 0;
    $file = File::Spec->rel2abs($file);
    my $m = bk_inspect($file);
    bk_newer_check($m);
    printf "Backup of %s (%s), mtmon-admin-center %s, %s, %d site(s), %d files\n", $m->{title} // '', $m->{host} // '', $m->{version}, fmt_time($m->{created}), scalar @{ $m->{sites} || [] }, $m->{files};
    if (my $pid = bk_daemon_running($cfgfile)) {
        my $cfg = load_config($cfgfile);
        bk_stage($cfg, $file, 'root (command line)');
        print "The centre runs (process $pid): it stops in a few seconds and its next start applies the backup\n"
            . "(systemd: ExecStartPre --apply-restore; restarted after 15 s). Follow it with: journalctl -u mtmon-admin-center -f\n";
        return 0;
    }
    my @notes = bk_apply($cfgfile, $file, 1, { by => 'root (command line)', name => File::Basename::basename($file) });
    print "Restored.\n", map { "  - $_\n" } @notes;
    print "Start the centre: systemctl start mtmon-admin-center\n";
    return 0;
}

# ---- web ----------------------------------------------------------------------------------
sub bk_info {
    my ($cfg) = @_;
    my $b = $cfg->{backup};
    my $st = bk_state($cfg);
    my $dd = $cfg->{general}{data_dir};
    my $ss = jread("$dd/server.json");
    my $top = (($ss || {})->{du} || {})->{top} || {};
    my %skip = (restore => 1);
    if (index(bk_dir($cfg) . '/', "$dd/") == 0) { my ($t) = substr(bk_dir($cfg), length($dd) + 1) =~ m{^([^/]+)}; $skip{$t} = 1 if defined $t }
    my $data = 0; $data += $top->{$_} // 0 for grep { !$skip{$_} } keys %$top;
    my $rd = bk_rdir($cfg);
    return {
        settings => { auto => $b->{_auto} eq 'hours' ? "$b->{_hours}h" : $b->{_auto}, time => sprintf('%02d:%02d', @{ $b->{_hm} }), weekday => $BK_WD[ $b->{_wd} ],
                      keep => $b->{keep} + 0, dir => bk_dir($cfg), mail => $b->{mail} ? JSON::PP::true : JSON::PP::false, file => $cfg->{_file} },
        next => bk_next($cfg, $st->{last_auto}, time), last => $st->{last}, last_ok => $st->{last_ok}, last_fail => $st->{last_fail},
        running => $st->{running} || undef, queued => (-e bk_req_f($cfg) ? JSON::PP::true : JSON::PP::false),
        list => [ bk_list($cfg) ], disk => sys_df(-d bk_dir($cfg) ? bk_dir($cfg) : $dd), data_bytes => $data + 0, data_dir => $dd,
        restore => { pending => (-e "$rd/pending.json" ? read_json("$rd/pending.json") : undef), last => read_json("$rd/last.json") },
        host => hostname(), version => $VERSION, now => time + 0, started => $^T + 0,
    };
}

# a request body straight into a file (an uploaded backup can be large) -> (bytes, why it stopped early)
sub bk_body_to_file {
    my ($c, $len, $fh) = @_;
    my ($got, $err, $buf) = (0, '', '');
    my $tls = ref($c) =~ /SSL/;
    my $sel = IO::Select->new($c);
    eval {
        local $SIG{ALRM} = sub { die "nothing more within 60 s\n" };
        while ($got < $len) {
            alarm 70;
            my $want = $len - $got;
            $want = 262144 if $want > 262144;
            my $r;
            if ($tls) {
                if (!$c->pending && !$sel->can_read(60)) { $err = 'nothing more within 60 s'; last }
                $r = sysread($c, $buf, $want);
                if (!defined $r) {
                    next if $!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}
                         || ($IO::Socket::SSL::SSL_ERROR && ($IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_WANT_READ()
                                                          || $IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_WANT_WRITE()));
                    $err = 'read error: ' . ($! || IO::Socket::SSL::errstr());
                    last;
                }
            } else {
                $r = read($c, $buf, $want);
                if (!defined $r) { $err = "read error: $!"; last }
            }
            if (!$r) { $err = 'the sender closed the connection'; last }
            print {$fh} $buf or do { $err = "writing failed: $!"; last };
            $got += $r;
        }
        alarm 0;
        1;
    } or $err = $@ =~ s/\s+$//r;
    alarm 0;
    return ($got, $err);
}

sub bk_same_origin {
    my ($h) = @_;
    my $or = $h->{origin} // return 1;
    my ($oh) = $or =~ m{^https?://([^/]+)}i;
    return $oh && lc $oh eq lc($h->{host} // '');
}

# /api/backup...  (users with role full who see every site, or such an API key) -> 1 when answered
sub bk_web {
    my ($c, $cfg, $route, $method, $h, $q, $who, $peer, $jr) = @_;
    return 0 unless $route =~ m{^/api/backup(?:/|$)};
    if (!bk_admin($who, $cfg)) { $jr->(403, { error => 'Backups are only for users with role full (not operator) who see every site: a backup holds every password and key of the centre.' }); return 1 }
    my $dir = bk_dir($cfg);
    my $user = $who->{name} // '';
    if ($route eq '/api/backup') { $jr->(200, bk_info($cfg)); return 1 }
    if ($route eq '/api/backup/download') {
        my $n = $q->{name} // '';
        ($n) = map { $_->{name} } grep { !$_->{error} } bk_list($cfg) if $n eq 'latest';
        $n //= '';
        if (!bk_name_ok($n) || !-f "$dir/$n") { $jr->(404, { error => 'No such backup.' }); return 1 }
        open(my $fh, '<:raw', "$dir/$n") or do { $jr->(500, { error => "Cannot read the backup: $!" }); return 1 };
        my $size = -s $fh;
        print {$c} "HTTP/1.1 200 OK\r\nContent-Type: application/gzip\r\nContent-Length: $size\r\n"
                 . "Content-Disposition: attachment; filename=\"$n\"\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n"
                 . "Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n";
        my ($sent, $buf) = (0, '');
        while (my $r = read($fh, $buf, 262144)) { print {$c} $buf or last; $sent += $r }
        close $fh;
        logmsg($sent == $size ? 'info' : 'warn', "Web: backup $n " . ($sent == $size ? 'downloaded' : "download broken off after " . fmt_bytes($sent)) . " by " . ($user || '?') . " from $peer");
        return 1;
    }
    if ($method ne 'POST') { $jr->(400, { error => 'POST expected' }); return 1 }
    if (!bk_same_origin($h)) { $jr->(403, { error => 'cross-site request refused' }); return 1 }
    if ($route eq '/api/backup/upload') {
        my $len = $h->{'content-length'} // '';
        if ($len !~ /^\d+$/ || !$len) { $jr->(400, { error => 'The file is empty (or its size was not sent).' }); return 1 }
        if (!-d $dir) { make_path($dir, { mode => 0700, error => \my $e }) }
        my $df = sys_df($dir);
        if ($df && defined $df->{avail} && $df->{avail} < $len + 20e6) { drain_body($c, $len); $jr->(413, { error => "Not enough free space in $dir: " . fmt_bytes($df->{avail}) . ' free.' }); return 1 }
        my $fn = File::Basename::basename($q->{name} // '');
        $fn =~ s/\.tgz$/.tar.gz/i;
        $fn =~ s/[^A-Za-z0-9._-]+/-/g; $fn =~ s/^[^A-Za-z0-9]+//; $fn =~ s/\.{2,}/./g;
        $fn = 'uploaded-' . strftime('%Y%m%d-%H%M%S', localtime) . '.tar.gz' unless bk_name_ok($fn);
        if (-e "$dir/$fn") { my $i = 2; my $b = $fn =~ s/\.tar\.gz$//r; $i++ while -e "$dir/$b-$i.tar.gz"; $fn = "$b-$i.tar.gz" }
        my $part = bk_tmp($dir, 'upload');
        open(my $fh, '>:raw', $part) or do { drain_body($c, $len); $jr->(500, { error => "Cannot write in $dir: $!" }); return 1 };
        chmod 0600, $part;
        my ($got, $err) = bk_body_to_file($c, $len, $fh);
        close $fh;
        if ($got < $len) { unlink $part; logmsg('warn', "Web: upload of a backup from $peer broken off ($err)"); $jr->(400, { error => "The upload stopped after " . fmt_bytes($got) . " of " . fmt_bytes($len) . " ($err)." }); return 1 }
        my $m = eval { bk_inspect($part) };
        if (!$m) { my $e = "$@" =~ s/\s+$//r; unlink $part; $jr->(400, { error => "This is not a usable backup of the centre: $e" }); return 1 }
        rename($part, "$dir/$fn") or do { unlink $part; $jr->(500, { error => "Cannot store the backup: $!" }); return 1 };
        my $note = { name => $fn, size => $len + 0, created => $m->{created}, kind => 'uploaded', by => $user, uploaded => time + 0, version => $m->{version},
                     host => $m->{host}, title => $m->{title}, sites => scalar @{ $m->{sites} || [] }, files => $m->{files} };
        eval { write_json("$dir/$fn.json", $note) };
        logmsg('info', "Web: backup $fn uploaded by " . ($user || '?') . " from $peer (" . fmt_bytes($len) . ", from $m->{host}, version $m->{version})");
        my @warn;
        push @warn, "It is from mtmon-admin-center $m->{version}, newer than this centre ($VERSION): install $m->{version} or newer before you restore it." if vcmp($m->{version}, $VERSION) > 0;
        push @warn, "Its data_dir ($m->{data_dir}) is not the one of this centre ($cfg->{general}{data_dir}): restore it with mtmon-admin-center --restore FILE as root." if $m->{data_dir} ne $cfg->{general}{data_dir};
        push @warn, "Its certificate files outside the config folder are not written by a restore from the web: " . join(', ', map { $_->{path} } @{ $m->{certs} }) if @{ $m->{certs} || [] };
        $jr->(200, { ok => JSON::PP::true, backup => $note, warnings => \@warn });
        return 1;
    }
    my $p = post_json($c, $h, $who, $jr, 4096, 'make or restore backups') or return 1;
    if ($route eq '/api/backup/create') {
        my $st = bk_state($cfg);
        if ($st->{running}) { $jr->(200, { ok => JSON::PP::true, running => $st->{running} }); return 1 }
        my $ok = eval { write_json(bk_req_f($cfg), { by => $user, t => time + 0 }); 1 };
        if (!$ok) { $jr->(500, { error => "Cannot write in $cfg->{general}{data_dir}: $@" }); return 1 }
        logmsg('info', "Web: backup asked for by " . ($user || '?') . " from $peer");
        $jr->(200, { ok => JSON::PP::true, queued => JSON::PP::true });
        return 1;
    }
    my $n = $p->{name} // '';
    if (!bk_name_ok($n) || !-f "$dir/$n") { $jr->(404, { error => 'No such backup.' }); return 1 }
    if ($route eq '/api/backup/delete') {
        unlink "$dir/$n", "$dir/$n.json";
        logmsg('info', "Web: backup $n deleted by " . ($user || '?') . " from $peer");
        $jr->(200, { ok => JSON::PP::true });
        return 1;
    }
    if ($route eq '/api/backup/restore') {
        if (($p->{confirm} // '') ne $n) { $jr->(400, { error => 'Confirm with the name of the backup.' }); return 1 }
        if (bk_state($cfg)->{running}) { $jr->(400, { error => 'A backup is being made - wait until it is done.' }); return 1 }
        my $m = eval { bk_stage($cfg, "$dir/$n", $user, $n) };
        if (!$m) { $jr->(400, { error => "$@" =~ s/\s+$//r }); return 1 }
        logmsg('warn', "Web: restore from the backup $n asked for by " . ($user || '?') . " from $peer");
        $jr->(200, { ok => JSON::PP::true, host => $m->{host}, created => $m->{created}, version => $m->{version}, sites => scalar @{ $m->{sites} || [] } });
        return 1;
    }
    $jr->(404, { error => 'unknown' });
    return 1;
}

sub center_ev_type { ($_[0] // '') =~ /^(site_offline|site_online|dev_added|dev_removed|dev_renamed|dev_changes|many_down)$/ }
sub last_mtmon_t {
    my ($f) = @_;
    open(my $fh, '<:raw', $f) or return undef;
    my $size = -s $fh;
    for my $back (65536, 1048576, $size) {                  # usually the last few lines are enough
        seek($fh, $size > $back ? $size - $back : 0, 0);
        local $/;
        my $tail = <$fh> // '';
        for my $l (reverse split /\n/, $tail) {
            my $r = eval { JSON::PP->new->utf8->decode($l) } or next;
            return $r->{t} if defined $r->{t} && !center_ev_type($r->{type}) && !$r->{center};
        }
        last if $back >= $size;
    }
    close $fh;
    return undef;
}

# ==========================================================================
# sites: online / offline (daemon, every minute)
# ==========================================================================
sub offline_limit {
    my ($cfg, $latest) = @_;
    return $cfg->{general}{offline_after} * 60 if $cfg->{general}{offline_after};
    my $iv = ($latest && $latest->{status}{interval}) || 300;
    my $l = 3 * $iv + 60;
    return $l < 600 ? 600 : $l;
}

sub site_summary {
    my ($cfg, $id) = @_;
    my $lt = site_latest($cfg, $id);
    my $st = $lt ? $lt->{status} : {};
    my $now = time;
    my $state = !$lt ? 'waiting' : $now - $lt->{received} > offline_limit($cfg, $lt) ? 'offline' : 'online';
    my (%n, @prob, @ports, @groups);
    my $loc = $st->{location} || $id;
    my @maint = grep { ($_->{from} // 0) <= $now && ($_->{until} // 0) > $now } @{ $st->{maintenance} || [] };
    for my $c (@{ $st->{controllers} || [] }) {
        my $gr = { kind => 'ap', name => $c->{heading} // $c->{name}, label => $c->{label}, host => $c->{host}, status => $c->{status},
                   since => $c->{down_since}, total => 0, ok => 0 };
        push @groups, $gr;
        for my $a (@{ $c->{aps} || [] }) {
            $n{ap_total}++;
            $gr->{total}++; $gr->{ok}++ if $a->{status} ne 'missing';
            # kind, status, name, "ip, controller", group, model, mac, missing since
            push @ports, [ 'ap', (($a->{maint} || $a->{behind}) && $a->{status} eq 'missing') ? 'muted' : ($a->{flap} && $a->{status} ne 'missing') ? 'warn' : $a->{status},
                           $a->{identity} || $a->{mac}, join(', ', grep { $_ } $a->{ip}, $c->{heading}),
                           $c->{heading} // $c->{name}, $a->{info} // '', $a->{mac} // '', $a->{missing_since} ];
            if ($a->{status} eq 'missing') {
                $n{ap_missing}++;
                # 13.6/7.10: behind a device that is down - shown, not counted as a problem of its own
                push @prob, { kind => 'ap', name => $a->{identity} || $a->{mac}, detail => join(', ', grep { $_ } $a->{ip}, $c->{heading}, ($a->{maint} ? 'maintenance' : ()), ($a->{behind} ? "behind $a->{behind}" : ())),
                              since => $a->{missing_since}, ($a->{maint} ? (muted => JSON::PP::true, maint => $a->{maint}) : ()), ($a->{behind} ? (muted => JSON::PP::true, behind => $a->{behind}) : ()) };
            } else {
                $n{ap_online}++;
                push @prob, { kind => 'flap', name => 'Unstable: ' . ($a->{identity} || $a->{mac}), detail => "$a->{flap} drops in " . (($st->{flap} || {})->{window} // 60) . " min, $c->{heading}",
                              since => $a->{flap_since}, ($a->{maint} ? (muted => JSON::PP::true, maint => $a->{maint}) : ()) } if $a->{flap};
            }
        }
        if ($c->{status} eq 'down') {
            $n{ctl_down}++;
            push @prob, { kind => 'ctl', name => $c->{heading}, detail => 'controller unreachable' . ($c->{maint} ? ', maintenance' : '') . ($c->{behind} ? ", behind $c->{behind}" : ''), since => $c->{down_since},
                          ($c->{maint} ? (muted => JSON::PP::true, maint => $c->{maint}) : ()), ($c->{behind} ? (muted => JSON::PP::true, behind => $c->{behind}) : ()) };
        }
    }
    my $dg = { kind => 'dev', name => $st->{devices}{heading} || 'Devices', total => 0, ok => 0 };
    push @groups, $dg if @{ $st->{devices}{items} || [] };
    for my $d (@{ $st->{devices}{items} || [] }) {
        $n{dev_total}++;
        $dg->{total}++; $dg->{ok}++ if $d->{status} ne 'down';
        push @ports, [ 'dev', (($d->{muted} || $d->{maint} || $d->{behind}) && $d->{status} eq 'down') ? 'muted' : $d->{status}, $d->{desc}, $d->{host},
                       $dg->{name}, '', '', $d->{down_since} ];
        my %mt = $d->{maint} ? (muted => JSON::PP::true, maint => $d->{maint}) : ();
        push @prob, { kind => 'flap', name => "Unstable: $d->{desc}", detail => "$d->{flap} drops, $d->{host}", since => $d->{flap_since}, %mt } if $d->{flap} && $d->{status} ne 'down';
        for my $al (grep { $_->{sent} } @{ ($d->{snmp} || {})->{alerts} || [] }) {
            push @prob, { kind => 'port', name => "$d->{desc}: $al->{text}", detail => $d->{host}, since => $al->{since}, %mt };
        }
        next unless $d->{status} eq 'down';
        $n{dev_down}++;
        push @prob, { kind => 'dev', name => $d->{desc}, detail => join(', ', $d->{host}, $st->{devices}{heading} // (), ($d->{maint} ? 'maintenance' : ()), ($d->{behind} ? "behind $d->{behind}" : ())),
                      since => $d->{down_since}, muted => ($d->{muted} || $d->{maint} || $d->{behind} ? JSON::PP::true : $d->{muted}), ($d->{maint} ? (maint => $d->{maint}) : ()),
                      ($d->{behind} ? (behind => $d->{behind}) : ()) };
    }
    my ($clients, @wifi) = (0);
    for my $c (@{ ($lt && $lt->{clients} && $lt->{clients}{controllers}) || [] }) {
        my $n = 0; $n += $_ for values %{ $c->{ssids} || {} };
        $clients += $n;
        push @wifi, { name => $c->{heading} // $c->{name}, label => $c->{label}, clients => $n + 0,
                      ssids => { map { ($_ => $c->{ssids}{$_} + 0) } keys %{ $c->{ssids} || {} } }, error => $c->{error} };
    }
    for my $ce (@{ $st->{certs} || [] }) {
        next unless $ce->{not_after};
        my $days = int(($ce->{not_after} - $now) / 86400);
        next unless $days <= ($cfg->{general}{_cert_warn}[0] // 30);
        push @prob, { kind => 'cert', name => "Certificate $ce->{name}", detail => ($days < 0 ? 'expired' : "expires in $days days") . ", $ce->{target}", since => undef,
                      (grep({ ($_->{target} // '') =~ /^(all|\*)$/i || maint_match($_->{target}, $ce->{name}) } @maint) ? (muted => JSON::PP::true, maint => 1) : ()) };
    }
    my $cmds = cmd_load($cfg, $id);
    my $cs = read_json(site_dir($cfg, $id) . '/center-state.json') || {};
    unshift @prob, { kind => 'site', name => 'Not reporting', detail => 'last report ' . fmt_time($lt->{received}) . (site_in_maint($cfg, $id, $lt) ? ', maintenance' : ''),
                     since => $cs->{offline_since} || $lt->{received}, (site_in_maint($cfg, $id, $lt) ? (muted => JSON::PP::true, maint => 1) : ()) } if $state eq 'offline';
    my $inv = $st->{inventory} || [];
    return { id => $id, title => $loc, host => $st->{host}, version => $st->{version}, state => $state, group => $cfg->{sites}{$id}{group} // '',
             (defined $cfg->{sites}{$id}{lat} ? (lat => $cfg->{sites}{$id}{lat}, lon => $cfg->{sites}{$id}{lon}) : ()),
             maintenance => \@maint, pending => scalar(@$cmds), maint_all => (site_in_maint($cfg, $id, $lt) ? JSON::PP::true : JSON::PP::false),
             inventory => { rows => scalar @$inv, mismatch => scalar(grep { $_->{mismatch} } @$inv) }, certs => scalar(@{ $st->{certs} || [] }),
             received => $lt ? $lt->{received} : undef, last_check => $st->{last_check}, interval => $st->{interval},
             counts => { map { ($_ => ($n{$_} // 0) + 0) } qw(ap_total ap_online ap_missing ctl_down dev_total dev_down) },
             clients => $clients + 0, clients_enabled => ($lt && $lt->{clients} && $lt->{clients}{enabled}) ? JSON::PP::true : JSON::PP::false,
             problems => \@prob, ports => \@ports, groups => \@groups, wifi => \@wifi,
             # 7.13: an agent (mtmon --agent): its version, whether it runs the configuration of the centre, its error
             ((-e agent_conf_file($cfg, $id) || ($lt && $lt->{agent})) ? (agent => { applied => (($lt && $lt->{agent} && ($lt->{agent}{config_md5} // '') eq (agent_conf_md5($cfg, $id) // '-')) ? JSON::PP::true : JSON::PP::false),
                 ($lt && $lt->{agent} ? (version => $lt->{agent}{version},
                     # the error is about the configuration saved now (not an older one that was corrected since)
                     (($lt->{agent}{config_error} && (!$lt->{agent}{config_bad} || $lt->{agent}{config_bad} eq (agent_conf_md5($cfg, $id) // ''))) ? (error => $lt->{agent}{config_error}) : ())) : ()) }) : ()) };
}

sub check_sites {
    my ($cfg) = @_;
    my (@off, @on);
    for my $id (sort keys %{ $cfg->{sites} }) {
        my $dir = site_dir($cfg, $id);
        my $lt = site_latest($cfg, $id) or next;            # never reported: nothing to say yet
        my $cs = read_json("$dir/center-state.json") || {};
        my $late = time - $lt->{received} > offline_limit($cfg, $lt);
        my $g = site_g($cfg, $id, $lt->{status}{interval});
        my $title = $lt->{status}{location} || $id;
        my $mt = site_in_maint($cfg, $id, $lt);
        if ($late && !$cs->{offline_since}) {
            $cs->{offline_since} = $lt->{received};
            $cs->{offline_quiet} = 1 if $mt;
            push @off, [ $id, $title, $lt->{received} ] unless $mt;
            append_jsonl($g, 'events.jsonl', { t => time + 0, type => 'site_offline', name => $title, text => 'no report since ' . fmt_time($lt->{received}),
                                               ($mt ? (maint => 1) : ()) });
            logmsg('warn', "Site $id ($title): no report since " . fmt_time($lt->{received}) . ($mt ? ' (maintenance window - no mail)' : ''));
        } elsif (!$late && $cs->{offline_since}) {
            my $quiet = delete $cs->{offline_quiet};
            push @on, [ $id, $title, $cs->{offline_since} ] unless $quiet;
            append_jsonl($g, 'events.jsonl', { t => time + 0, type => 'site_online', name => $title, ($quiet ? (maint => 1) : ()) });
            logmsg('info', "Site $id ($title): reporting again");
            delete $cs->{offline_since};
        } elsif ($late && $cs->{offline_quiet} && !$mt) {
            # went silent during its maintenance window and is still silent after it
            delete $cs->{offline_quiet};
            push @off, [ $id, $title, $lt->{received} ];
        } else { next }
        write_json("$dir/center-state.json", $cs);
    }
    return unless (@off || @on) && $cfg->{general}{notify_offline};
    # one mail to [mail] to with every site, one to each site's own recipients (mail= in [sites]) with theirs
    my %to;
    if (length $cfg->{mail}{to}) { $to{ $cfg->{mail}{to} } = [ [@off], [@on] ] }
    for my $x ([ \@off, 0 ], [ \@on, 1 ]) {
        for my $e (@{ $x->[0] }) {
            my $m = $cfg->{sites}{ $e->[0] }{mail};
            next unless length($m // '') && $m ne $cfg->{mail}{to};
            push @{ ($to{$m} ||= [ [], [] ])->[ $x->[1] ] }, $e;
        }
    }
    for my $rcpt (sort keys %to) {
        my ($o, $n) = @{ $to{$rcpt} };
        next unless @$o || @$n;
        my $subj = @$o ? (@$o == 1 ? "Site $o->[0][1] is not reporting" : scalar(@$o) . " sites are not reporting")
                       : (@$n == 1 ? "Site $n->[0][1] is reporting again" : scalar(@$n) . " sites are reporting again");
        my $body = "$cfg->{general}{title}\n\n";
        $body .= "Not reporting (nothing received from mtmon):\n" . join('', map { "  - $_->[1] ($_->[0]): last report " . fmt_time($_->[2]) . "\n" } @$o) . "\n" if @$o;
        $body .= "Reporting again:\n" . join('', map { "  - $_->[1] ($_->[0]), silent since " . fmt_time($_->[2]) . "\n" } @$n) . "\n" if @$n;
        $body .= "Possible causes: the mtmon server or its service is down, no internet at the site, or a firewall\n"
               . "blocks the connection to the centre. On the mtmon: systemctl status mtmon; mtmon --test-central\n" if @$o;
        my $mc = { %$cfg, mail => { %{ $cfg->{mail} }, to => $rcpt } };
        eval { send_mail($mc, $subj, $body, undef); logmsg('info', "Mail sent to $rcpt: $subj"); 1 } or logmsg('error', "Sending mail to $rcpt failed: $@");
    }
}

# ==========================================================================
# 7.8: devices added to or removed from a site's mtmon (or renamed) - an event per device, a push to the
# phones and one mail per check. The devices of every site are remembered in devices-known.json; the
# first report of a site (or the first run of 7.8) only fills it.
# ==========================================================================
sub dev_inventory {                                  # key => [kind, name, ip, where]
    my ($st) = @_;
    my %d;
    for my $c (@{ $st->{controllers} || [] }) {
        my $h = $c->{heading} // $c->{name};
        $d{"ctl|$c->{name}"} = [ 'ctl', $h, $c->{host} // '', $c->{label} // '' ];
        for my $a (@{ $c->{aps} || [] }) {
            my $id = $a->{mac} || $a->{identity} or next;
            $d{"ap|$c->{name}|" . lc $id} = [ 'ap', $a->{identity} || $a->{mac}, $a->{ip} // '', $h ];
        }
    }
    for my $x (@{ ($st->{devices} || {})->{items} || [] }) {
        $d{"dev|$x->{host}"} = [ 'dev', $x->{desc} // $x->{host}, $x->{host}, ($st->{devices} || {})->{heading} // '' ] if defined $x->{host};
    }
    return \%d;
}

sub center_dev_changes {
    my ($cfg) = @_;
    my $KIND = { ctl => 'controller', ap => 'access point', dev => 'device' };
    my (@all, %by);
    for my $id (sort keys %{ $cfg->{sites} }) {
        my $dir = site_dir($cfg, $id);
        my $lt = site_latest($cfg, $id) or next;
        my $kf = "$dir/devices-known.json";
        my $known = read_json($kf);
        next if $known && ($known->{received} // 0) >= ($lt->{received} // 0);     # no new report since the last look
        my $st = $lt->{status} || {};
        my $now = time;
        my $cur = dev_inventory($st);
        my (@ch);
        if ($known && ref $known->{d} eq 'HASH') {
            my $old = $known->{d};
            # a controller that cannot be read now: its access points are not "removed"
            my %ctl_ok = map { ($_->{name} => (($_->{status} // '') ne 'down' && scalar(@{ $_->{aps} || [] }) ? 1 : 0)) } @{ $st->{controllers} || [] };
            for my $k (sort keys %$cur) {
                my $n = $cur->{$k};
                if (!$old->{$k}) { push @ch, [ 'dev_added', $n ] }
                elsif (($old->{$k}[1] // '') ne ($n->[1] // '') && $n->[0] ne 'ctl') { push @ch, [ 'dev_renamed', $n, $old->{$k}[1] ] }
            }
            for my $k (sort keys %$old) {
                next if $cur->{$k};
                # an access point of a controller that is down (kept) or removed (said of the controller) is not listed
                next if $k =~ /^ap\|([^|]*)\|/ && !$ctl_ok{$1};
                push @ch, [ 'dev_removed', $old->{$k} ];
            }
        }
        # keep what was known of a controller's access points while the controller cannot be read
        my %keep;
        if ($known && ref $known->{d} eq 'HASH') {
            my %ctl_ok = map { ($_->{name} => (($_->{status} // '') ne 'down' && scalar(@{ $_->{aps} || [] }) ? 1 : 0)) } @{ $st->{controllers} || [] };
            for my $k (keys %{ $known->{d} }) {
                $keep{$k} = $known->{d}{$k} if !$cur->{$k} && $k =~ /^ap\|([^|]*)\|/ && exists $ctl_ok{$1} && !$ctl_ok{$1};
            }
        }
        write_json($kf, { received => $lt->{received} + 0, t => $now + 0, d => { %keep, %$cur } });
        next unless @ch;
        if (@ch > 50) {                                  # a whole new mtmon config, a renamed controller: one line
            logmsg('info', "Site $id: " . scalar(@ch) . " device changes - listed in the events, the mail only counts them");
        }
        my $g = site_g($cfg, $id, $st->{interval});
        my $title = $st->{location} || $id;
        my @ev = map {
            my ($type, $n, $was) = @$_;
            my $what = $KIND->{ $n->[0] } // 'device';
            +{ t => $now + 0, type => $type, kind => $n->[0], name => $n->[1], ip => $n->[2], heading => $n->[3],
               text => ($type eq 'dev_added' ? "new $what" : $type eq 'dev_removed' ? "$what no longer monitored" : "$what renamed, was $was")
                     . ($n->[0] eq 'ap' && length $n->[3] ? ", $n->[3]" : '') }
        } @ch;
        # many at once (a new controller, a new config): the phones get one summary, not a push per device
        if (@ev > 3) {
            $_->{quiet} = 1 for @ev;
            my %n; $n{ $_->{type} }++ for @ev;
            push @ev, { t => $now + 0, type => 'dev_changes', name => $title,
                        text => join(', ', ($n{dev_added} ? "$n{dev_added} added" : ()), ($n{dev_removed} ? "$n{dev_removed} removed" : ()), ($n{dev_renamed} ? "$n{dev_renamed} renamed" : ())) };
        }
        append_jsonl($g, 'events.jsonl', @ev);
        @ev = grep { $_->{type} ne 'dev_changes' } @ev;
        logmsg('info', "Site $id ($title): " . join('; ', map { "$_->{name} ($_->{ip}): $_->{text}" } @ev[0 .. ($#ev > 9 ? 9 : $#ev)]) . (@ev > 10 ? ' ...' : ''));
        my $e = [ $id, $title, \@ev ];
        push @all, $e;
        my $m = $cfg->{sites}{$id}{mail};
        push @{ $by{$m} }, $e if length($m // '') && $m ne $cfg->{mail}{to};
    }
    return unless @all && $cfg->{general}{notify_devices};
    my @send = ((length $cfg->{mail}{to} ? [ $cfg->{mail}{to}, \@all ] : ()), map { [ $_, $by{$_} ] } sort keys %by);
    for my $x (@send) {
        my ($rcpt, $list) = @$x;
        my ($na, $nr, $nn) = (0, 0, 0);
        for my $e (map { @{ $_->[2] } } @$list) { $e->{type} eq 'dev_added' ? $na++ : $e->{type} eq 'dev_removed' ? $nr++ : $nn++ }
        my $where = @$list == 1 ? " on $list->[0][1]" : ' on ' . scalar(@$list) . ' sites';
        my $subj = join(', ', ($na ? ($na == 1 ? 'New device' : "$na new devices") : ()), ($nr ? ($nr == 1 ? '1 device removed' : "$nr devices removed") : ()),
                        ($nn ? ($nn == 1 ? '1 device renamed' : "$nn devices renamed") : ())) . $where;
        my $body = "$cfg->{general}{title}\n\nThe list of monitored devices changed in the mtmon config (or a controller sees a new access point):\n\n";
        for my $s (@$list) {
            my @e = @{ $s->[2] };
            $body .= "$s->[1] ($s->[0]):\n";
            for my $t ([ 'dev_added', 'Added' ], [ 'dev_removed', 'Removed' ], [ 'dev_renamed', 'Renamed' ]) {
                my @x = grep { $_->{type} eq $t->[0] } @e or next;
                $body .= "  $t->[1]:\n" . join('', map { "    - $_->{name}" . (length $_->{ip} ? " ($_->{ip})" : '') . " - $_->{text}\n" } @x[0 .. ($#x > 99 ? 99 : $#x)])
                       . (@x > 100 ? '    ... and ' . (@x - 100) . " more (Events on the centre's page)\n" : '');
            }
            $body .= "\n";
        }
        $body .= "The devices are in Devices on the centre's page. No more of these mails: [general] notify_devices = no\n";
        my $mc = { %$cfg, mail => { %{ $cfg->{mail} }, to => $rcpt } };
        eval { send_mail($mc, $subj, $body, undef); logmsg('info', "Mail sent to $rcpt: $subj"); 1 } or logmsg('error', "Sending mail to $rcpt failed: $@");
    }
}

# ==========================================================================
# maintenance windows set in the centre: kept as commands per site until that mtmon confirms them
# ==========================================================================
sub cmd_load {
    my ($cfg, $id) = @_;
    my $d = read_json(site_dir($cfg, $id) . '/commands.json') || {};
    return [ grep { ref $_ eq 'HASH' && $_->{id} && ($_->{t} // 0) > time - 7 * 86400 } @{ $d->{cmds} || [] } ];
}
sub cmd_save {
    my ($cfg, $id, $list) = @_;
    my $dir = site_dir($cfg, $id);
    make_path($dir) unless -d $dir;
    write_json("$dir/commands.json", { cmds => $list });
}

# the whole site is in a maintenance window (reported by its mtmon, or set here and not yet confirmed)
sub site_in_maint {
    my ($cfg, $id, $lt) = @_;
    my $now = time;
    return 1 if grep { ($_->{target} // '') =~ /^(all|\*)$/i && ($_->{from} // 0) <= $now && ($_->{until} // 0) > $now }
                @{ ($lt && $lt->{status}{maintenance}) || [] };
    return 1 if grep { ($_->{op} // '') eq 'mute' && ($_->{target} // '') =~ /^(all|\*)$/i && ($_->{from} // 0) <= $now && $_->{until} > $now } @{ cmd_load($cfg, $id) };
    return 0;
}

sub site_maint_info {
    my ($cfg, $id) = @_;
    my $lt = site_latest($cfg, $id);
    my $now = time;
    return { site => $id, title => (($lt && $lt->{status}{location}) || $id),
             active => [ sort { $a->{until} <=> $b->{until} } grep { ($_->{until} // 0) > $now } @{ ($lt && $lt->{status}{maintenance}) || [] } ],
             pending => cmd_load($cfg, $id) };
}

# a POST with a JSON body from a page of the centre (role full, same origin) -> hash, or undef after answering
sub post_json {
    my ($c, $h, $who, $jr, $max, $what) = @_;
    if (($who->{role} // '') ne 'full') { $jr->(403, { error => 'Only users with role full may ' . ($what // 'set maintenance windows') . '.' }); return undef }
    if (($h->{'content-type'} // '') !~ m{^application/json}i) { $jr->(415, { error => 'JSON expected' }); return undef }
    if (defined(my $or = $h->{origin})) {
        my ($oh) = $or =~ m{^https?://([^/]+)}i;
        if (!$oh || lc $oh ne lc($h->{host} // '')) { $jr->(403, { error => 'cross-site request refused' }); return undef }
    }
    my $len = $h->{'content-length'} // 0;
    if ($len !~ /^\d+$/ || $len > ($max || 8192)) { $jr->(413, { error => 'request too large' }); return undef }
    my ($body) = read_body($c, $len, 10);
    my $p = eval { JSON::PP->new->utf8->decode($body) };
    if (ref $p ne 'HASH') { $jr->(400, { error => 'invalid JSON' }); return undef }
    return $p;
}

# new window / end a window for one site -> (code, answer)
sub center_maint {
    my ($cfg, $id, $p, $who, $peer, $op) = @_;
    my $lt = site_latest($cfg, $id) or return (404, { error => 'No report from this site yet.' });
    my $title = $lt->{status}{location} || $id;
    my $iv = int((($lt->{status}{interval} // 300) + 59) / 60);
    my $by = ($who->{name} || 'centre') . " ($peer)";
    my $cmds = cmd_load($cfg, $id);
    if ($op eq 'end') {
        my $mid = $p->{id} // '';
        return (400, { error => 'Which window?' }) unless length $mid;
        if (my ($c) = grep { ($_->{op} // '') eq 'mute' && ($_->{mid} eq $mid || $_->{id} eq $mid) } @$cmds) {
            cmd_save($cfg, $id, [ grep { $_ != $c } @$cmds ]);
            logmsg('info', "Site $id: maintenance '$c->{target}' withdrawn by $by before mtmon got it");
            return (200, { ok => JSON::PP::true, note => 'Withdrawn - it had not reached mtmon yet.' });
        }
        my ($m) = grep { $_->{id} eq $mid } @{ $lt->{status}{maintenance} || [] };
        return (404, { error => 'No such maintenance window.' }) unless $m;
        push @$cmds, { id => 'c' . substr(md5_hex(time . $$ . rand()), 0, 12), op => 'unmute', mid => $mid, target => $m->{target}, by => $by, t => time + 0 };
        cmd_save($cfg, $id, $cmds);
        push_now($cfg, { site => $id, type => 'maint_end', name => $m->{target}, text => "ended early by $by", by => $m->{by} // '' });
        logmsg('info', "Site $id: end of maintenance '$m->{target}' queued by $by");
        return (200, { ok => JSON::PP::true, queued => JSON::PP::true, note => "Saved - $title ends the window with its next report (within about $iv min)." });
    }
    (my $t = $p->{target} // '') =~ s/^\s+|\s+$//g;
    return (400, { error => 'Target missing.' }) unless length $t && length $t <= 200;
    my ($from, $until) = eval { maint_window($p->{duration} // '', time) };
    return (400, { error => ($@ =~ s/\s+$//r) }) unless $until;
    my $st = $lt->{status};
    my @names = map { ($_->{name}, $_->{host}, $_->{heading}, map { ($_->{identity}, $_->{mac}, $_->{ip}) } @{ $_->{aps} || [] }) } @{ $st->{controllers} || [] };
    push @names, map { ($_->{host}, $_->{desc}) } @{ ($st->{devices} || {})->{items} || [] };
    push @names, map { $_->{name} } @{ $st->{certs} || [] };
    return (400, { error => "'$t' matches nothing at $title." }) unless $t =~ /^(all|\*)$/i || maint_match($t, @names);
    my $m = { id => 'c' . substr(md5_hex(time . $$ . rand()), 0, 12), op => 'mute', mid => substr(md5_hex(rand() . $$ . time), 0, 8),
              target => $t, from => $from + 0, until => $until + 0, reason => substr($p->{reason} // '', 0, 200), by => $by, t => time + 0 };
    push @$cmds, $m;
    cmd_save($cfg, $id, $cmds);
    push_now($cfg, { site => $id, type => 'maint_start', name => $t, by => $by, reason => $m->{reason},
                     text => 'until ' . fmt_time($until) . ($from > time ? ' (from ' . fmt_time($from) . ')' : '') });
    logmsg('info', "Site $id: maintenance '$t' until " . fmt_time($until) . " queued by $by" . (length $m->{reason} ? " ($m->{reason})" : ''));
    return (200, { ok => JSON::PP::true, queued => JSON::PP::true, maintenance => { %$m, id => $m->{mid} },
                   note => "Saved - $title applies it with its next report (within about $iv min). "
                         . ($t =~ /^(all|\*)$/i ? 'The centre sends no "not reporting" mail meanwhile.' : '') });
}

# ==========================================================================
# the centre's own certificate (cert_warn_days) and the weekly / monthly report of all sites
# ==========================================================================
sub center_cert_info {
    my ($cfg) = @_;
    my $crt = $cfg->{web}{cert_file};
    return undef unless $cfg->{web}{tls} && -r $crt;
    my $out = `openssl x509 -in '$crt' -noout -enddate -subject -issuer 2>/dev/null`;
    my ($na) = $out =~ /notAfter=(.*)/ or return { name => 'Centre web certificate', target => $crt, error => 'cannot read' };
    my ($sub) = $out =~ /subject=.*?CN\s*=\s*([^,\/\n]+)/;
    my ($iss) = $out =~ /issuer=.*?CN\s*=\s*([^,\/\n]+)/;
    my $t = cert_date($na);
    return { name => 'Centre web certificate', target => $crt, not_after => $t, subject => $sub, issuer => $iss,
             days => (defined $t ? int(($t - time) / 86400) : undef), self_signed => (($sub // '') eq ($iss // '') ? 1 : 0) };
}

sub center_cert_check {
    my ($cfg) = @_;
    my $f = "$cfg->{general}{data_dir}/center-cert.json";
    my $st = read_json($f) || {};
    return if time - ($st->{t} // 0) < 86400;
    my $c = center_cert_info($cfg) or return;
    $st->{t} = time + 0;
    if (defined $c->{days}) {
        my @ge = grep { $c->{days} <= $_ } @{ $cfg->{general}{_cert_warn} };
        my $lvl = $c->{days} < 0 ? -1 : @ge ? $ge[-1] : undef;
        if (defined $lvl && (!defined $st->{warned} || $lvl < $st->{warned}) && length $cfg->{mail}{to}) {
            my $subj = "Certificate of the centre " . ($c->{days} < 0 ? 'has EXPIRED' : "expires in $c->{days} days");
            my $body = "$cfg->{general}{title}\n\nThe web certificate of the centre ($c->{target}" . ($c->{subject} ? ", $c->{subject}" : '') . ")\n"
                     . ($c->{days} < 0 ? 'expired on ' : 'is valid until ') . fmt_time($c->{not_after}) . ".\n\n"
                     . "The mtmon installations stop reporting when it is expired (or no longer matches their [central] fingerprint).\n"
                     . "After replacing it: mtmon-admin-center --fingerprint, and update fingerprint in [central] of every mtmon\n"
                     . "(or remove the line when the new certificate is a purchased one).\n";
            eval { send_mail($cfg, $subj, $body, undef); logmsg('warn', $subj); 1 } or logmsg('error', "Sending mail failed: $@");
            $st->{warned} = $lvl;
        } elsif (!defined $lvl) { delete $st->{warned} }
    }
    write_json($f, $st);
}

# this server (the centre itself): sample once a minute, the disk alert by mail and as an event
# (center-events.jsonl: the phones of users who see every site get it as a push)
sub center_server_check {
    my ($cfg, $now) = @_;
    my $g = $cfg->{general};
    return if $now - ($cfg->{_srv_t} // 0) < 60;
    $cfg->{_srv_t} = $now;
    my ($ss, $tr, $commit) = server_sample("$g->{data_dir}/server.json", $g->{data_dir}, $g->{disk_warn}, $now, 'mtmon-admin-center');
    if ($tr) {
        my $df = $ss->{df} || {};
        my $pct = $df->{total} ? sprintf('%.1f', 100 * $df->{avail} / ($df->{used} + $df->{avail} || 1)) : '?';
        my $text = ($tr eq 'low' ? "only $pct % free" : "$pct % free again") . ': ' . fmt_bytes($df->{avail}) . ' of ' . fmt_bytes($df->{used} + $df->{avail})
                 . " on $df->{mount} (alert below $g->{disk_warn} %)";
        my $subj = ($tr eq 'low' ? 'Disk almost full on the centre ' : 'Disk space OK again on the centre ') . hostname();
        if (length $cfg->{mail}{to}) {
            my $body = "$g->{title}\n\n$subj: $text\nData of the centre: $g->{data_dir}\n\n"
                     . ($tr eq 'low' ? "Details: mtmon-admin-center --server, or Server in the menu of the centre's page.\n"
                                       . "Space is taken mostly by the history of the sites: [web] history_days / history_hourly_days.\n" : '');
            eval { send_mail($cfg, $subj, $body, undef); logmsg('info', "Mail sent: $subj"); 1 } or logmsg('error', "Sending mail failed: $@");
        }
        logmsg($tr eq 'low' ? 'warn' : 'info', "$subj: $text");
        append_jsonl({ state_file => "$g->{data_dir}/server.json" }, 'center-events.jsonl',
                     { t => $now + 0, type => ($tr eq 'low' ? 'disk_low' : 'disk_ok'), name => hostname(), text => $text, heading => 'Centre' });
    }
    $commit->();
}

# ---- 7.7: every device of every site (Devices view) and the search for a Wi-Fi client --------------
sub port_summary {                                  # compact ports -> { up, n, vlans => [ids] }
    my ($pts) = @_;
    my ($up, $n, %v) = (0, 0);
    for my $p (@{ $pts || [] }) {
        my $wl = ($p->[1] // '') =~ /^(wlan|wifi)/i;
        if (!$wl) { $n++; $up++ if ($p->[3] // 0) == 1 }
        for my $x (split /,/, $p->[8] // '') {
            my ($a, $b) = $x =~ /^(\d+)(?:-(\d+))?[ut]?$/ or next;
            $v{$_} = 1 for $a .. ($b && $b - $a < 64 ? $b : $a);
        }
    }
    delete $v{1};
    return { up => $up, n => $n, vlans => [ sort { $a <=> $b } keys %v ] };
}

sub center_devices {
    my ($cfg, $ids) = @_;
    my @rows;
    for my $id (@$ids) {
        my $lt = site_latest($cfg, $id) or next;
        my $st = $lt->{status} || {};
        my $title = $st->{location} || $id;
        my $off = time - $lt->{received} > offline_limit($cfg, $lt) ? 1 : 0;
        my %inv = map { (($_->{key} // '') => $_) } @{ $st->{inventory} || [] };
        my %cl = map { ($_->{name} => ($_->{aps} || {})) } @{ ($lt->{clients} || {})->{controllers} || [] };
        my %b = (site => $id, site_title => $title, ($off ? (offline => JSON::PP::true) : ()));
        for my $c (@{ $st->{controllers} || [] }) {
            my $iv = $inv{"ctl|$c->{name}"} || {};
            my @aps = @{ $c->{aps} || [] };
            push @rows, { %b, kind => 'ctl', name => $c->{heading} // $c->{name}, ip => $c->{host}, status => $c->{status}, since => $c->{down_since}, maint => $c->{maint},
                          t => $c->{name}, mid => $c->{maint_id}, behind => $c->{behind},
                          model => $iv->{model} // $c->{label}, version => $iv->{version}, label => $c->{label}, aps => scalar(@aps) + 0,
                          aps_ok => scalar(grep { ($_->{status} // '') ne 'missing' } @aps) + 0 };
            for my $a (@aps) {
                my $iv2 = $inv{ 'ap|' . $c->{name} . '|' . ($a->{mac} // '') } || {};
                my $sn = $a->{snmp};
                my $n = ($cl{ $c->{name} } || {})->{ $a->{identity} // '' };
                push @rows, { %b, kind => 'ap', name => ap_name($st, $a), ip => $a->{ip}, mac => $a->{mac}, status => $a->{status}, since => $a->{missing_since},
                              t => $a->{mac} || $a->{identity}, mid => $a->{maint_id}, behind => $a->{behind},
                              seen => $a->{last_seen}, maint => $a->{maint}, flap => $a->{flap}, model => $a->{info} || $iv2->{model}, version => $a->{version} || $iv2->{version},
                              where => $c->{heading} // $c->{name}, (defined $n ? (clients => $n + 0) : ()),
                              ($sn ? (ports => { %{ port_summary($sn->{ports}) }, state => $sn->{state}, (defined $sn->{err} ? (err => $sn->{err}) : ()),
                                                 eth => [ map { [ $_->[1], $_->[3], $_->[5] ] } grep { ($_->[1] // '') !~ /^(wlan|wifi)/i } @{ $sn->{ports} || [] } ] }) : ()) };
            }
        }
        for my $d (@{ ($st->{devices} || {})->{items} || [] }) {
            my $iv = $inv{"sw|$d->{host}"} || {};
            my $sn = $d->{snmp};
            my ($hot) = sort { $b <=> $a } map { $_->[1] } @{ ($sn || {})->{temp} || [] };
            push @rows, { %b, kind => 'dev', name => $d->{desc}, ip => $d->{host}, status => $d->{status}, since => $d->{down_since}, seen => $d->{last_ok},
                          t => $d->{host}, mid => $d->{maint_id}, behind => $d->{behind},
                          maint => $d->{maint}, flap => $d->{flap}, muted => $d->{muted}, model => $iv->{model}, version => $iv->{version},
                          where => ($st->{devices} || {})->{heading},
                          ($sn ? (snmp => { state => $sn->{state}, (defined $sn->{err} ? (err => $sn->{err}) : ()), uptime => $sn->{uptime},
                                            (($sn->{poe} || {})->{pct} // undef) ? (poe => $sn->{poe}{pct} + 0) : (), (defined $hot ? (temp => $hot + 0) : ()),
                                            alerts => scalar(grep { $_->{sent} } @{ $sn->{alerts} || [] }) + 0, %{ port_summary($sn->{ports}) } }) : ()) };
        }
        my $sv = $st->{server};
        push @rows, { %b, kind => 'mtmon', name => $st->{host} || 'mtmon', ip => '', status => ($off ? 'down' : 'up'), since => ($off ? $lt->{received} : undef),
                      version => $st->{version}, model => 'mtmon',
                      ($sv ? (server => { mem => $sv->{mem}, cpu => $sv->{cpu_pct}, disk => ($sv->{disk} || {})->{free_pct}, disk_low => $sv->{disk_low} }) : ()) };
    }
    return \@rows;
}

# 7.9.1: an access point by its name, never by its MAC - the identity, else the name it gave over SNMP/SSH,
# else the inventory, else its IP
sub is_mac { ($_[0] // '') =~ /^(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}$|^[0-9a-f]{12}$/i }
sub ap_name {
    my ($st, $a) = @_;
    for my $n ($a->{identity}, ($a->{snmp} || {})->{sysname},
               (map { $_->{identity} // $_->{name} } grep { lc($_->{mac} // '') eq lc($a->{mac} // '-') } @{ $st->{inventory} || [] })) {
        return $n if defined $n && length $n && !is_mac($n);
    }
    return $a->{ip} || $a->{mac} || '';
}
sub push_name {                                          # the name of an event's device for the phone
    my ($st, $e) = @_;
    my $n = $e->{name} // '';
    return $n if length $n && !is_mac($n);
    my $mac = lc($e->{mac} // (is_mac($n) ? $n : ''));
    for my $c (@{ ($st || {})->{controllers} || [] }) {
        for my $a (@{ $c->{aps} || [] }) {
            return ap_name($st, $a) if (length $mac && lc($a->{mac} // '') eq $mac) || (length($e->{ip} // '') && ($a->{ip} // '') eq $e->{ip});
        }
    }
    return $e->{ip} || $n;
}

sub target_name {                                        # a maintenance target (MAC, IP, name, pattern) as the phone shows it
    my ($st, $t) = @_;
    return $t unless $st && defined $t;
    if (is_mac($t)) { return push_name($st, { name => $t }) . '' }
    if ($t =~ /^\d{1,3}(?:\.\d{1,3}){3}$/) {
        for my $d (@{ ($st->{devices} || {})->{items} || [] }) { return "$d->{desc} ($t)" if ($d->{host} // '') eq $t && length($d->{desc} // '') }
        my $n = push_name($st, { name => '', ip => $t });
        return $n ne $t ? "$n ($t)" : $t;
    }
    for my $c (@{ $st->{controllers} || [] }) { return ($c->{heading} // $c->{name}) . ' with all its access points' if $c->{name} eq $t }
    return $t;
}

# a Wi-Fi client (MAC, IP, name, user) on every site the user may see (role full)
sub center_client_find {
    my ($cfg, $ids, $q) = @_;
    my @r;
    my $qq = lc $q;
    (my $qm = $qq) =~ s/[^0-9a-f]//g;                       # MAC in any form: aa-bb.. aabb..
    for my $id (@$ids) {
        my $lt = site_latest($cfg, $id) or next;
        my $title = ($lt->{status} || {})->{location} || $id;
        for my $c (@{ ($lt->{clients} || {})->{controllers} || [] }) {
            for my $x (@{ $c->{clients} || [] }) {
                my $mac = lc($x->{mac} // '');
                (my $mh = $mac) =~ s/[^0-9a-f]//g;
                next unless (length($qm) >= 4 && index($mh, $qm) >= 0) || grep { index(lc($_ // ''), $qq) >= 0 } $x->{ip}, $x->{host}, $x->{user}, $x->{ssid};
                push @r, { site => $id, site_title => $title, controller => $c->{heading} // $c->{name}, map { ($_ => $x->{$_}) } qw(ap ssid ip mac host user band signal vlan uptime auth) };
                return { rows => \@r, more => JSON::PP::true } if @r >= 300;
            }
        }
    }
    return { rows => \@r, t => time + 0 };
}

# the Server view: the centre's own numbers and the space each site takes
sub center_server_info {
    my ($cfg, $ids) = @_;
    my $g = $cfg->{general};
    my $ss = jread("$g->{data_dir}/server.json") || {};
    my $i = server_info($ss, $g->{data_dir}, $g->{disk_warn}, 'mtmon-admin-center', $VERSION);
    my $sz = (($ss->{du} || {})->{sub} || {})->{sites} || {};
    $i->{sites} = [ map {
        my $lt = site_latest($cfg, $_);
        my $sv = $lt && $lt->{status}{server};
        { id => $_, title => (($lt && $lt->{status}{location}) || $_), bytes => $sz->{$_}, received => ($lt ? $lt->{received} : undef),
          ($sv ? (mtmon => { map { ($_ => $sv->{$_}) } qw(version host mem cpu_pct tasks started disk_low disk_warn) },
                  mtmon_disk => $sv->{disk}, mtmon_data => ($sv->{data} || {})->{total}) : ()) }
    } @$ids ];
    return $i;
}

sub center_report {
    my ($cfg, $kind, $from, $to) = @_;
    my (@all, %by);
    for my $id (sort keys %{ $cfg->{sites} }) {
        my $lt = site_latest($cfg, $id) or next;
        my $now = time;
        my $site = { id => $id, title => $lt->{status}{location} || $id,
                     stats => period_stats(site_g($cfg, $id, $lt->{status}{interval}), $from, $to),
                     certs => [ map { +{ %$_, days => ($_->{not_after} ? int(($_->{not_after} - $now) / 86400) : undef) } } @{ $lt->{status}{certs} || [] } ],
                     mismatch => [ grep { $_->{mismatch} } @{ $lt->{status}{inventory} || [] } ] };
        push @all, $site;
        my $m = $cfg->{sites}{$id}{mail};
        push @{ $by{$m} }, $site if length($m // '') && $m ne $cfg->{mail}{to};
    }
    return 0 unless @all;
    my $to_all = length $cfg->{report}{to} ? $cfg->{report}{to} : $cfg->{mail}{to};
    my @send = ((length $to_all ? [ $to_all, \@all, 1 ] : ()), map { [ $_, $by{$_}, @{ $by{$_} } > 1 ] } sort keys %by);
    for my $x (@send) {
        my ($rcpt, $sites, $multi) = @$x;
        my ($subj, $text, $html) = report_render({ kind => $kind, from => $from, to => $to, multi => $multi,
            title => ($multi ? $cfg->{general}{title} : $sites->[0]{title}), sites => $sites,
            footer => "mtmon-admin-center $VERSION on " . hostname() });
        my $mc = { %$cfg, mail => { %{ $cfg->{mail} }, to => $rcpt } };
        send_mail($mc, $subj, $text, $html);
        logmsg('info', "Report sent to $rcpt: $subj");
    }
    return 1;
}

sub center_report_check {
    my ($cfg, $now) = @_;
    my $rp = $cfg->{report};
    return unless $rp->{enabled} && ($rp->{weekly} || $rp->{monthly});
    my $f = "$cfg->{general}{data_dir}/report.json";
    my $st = read_json($f) || {};
    my $changed = 0;
    for my $kind (qw(week month)) {
        next unless $rp->{ $kind eq 'week' ? 'weekly' : 'monthly' };
        my ($from, $to) = period_bounds($kind, $now);
        if (!defined $st->{$kind}) { $st->{$kind} = $to + 0; $changed = 1; next }
        next if $st->{$kind} >= $to;
        my @d = localtime $to;
        next if $now < POSIX::mktime(0, $rp->{_hm}[1], $rp->{_hm}[0], $d[3], $d[4], $d[5], 0, 0, -1);
        next if ($st->{"${kind}_fail"} // 0) > $now - 1800;
        if (eval { center_report($cfg, $kind, $from, $to); 1 }) { $st->{$kind} = $to + 0; delete $st->{"${kind}_fail"} }
        else { logmsg('error', "Sending the $kind report failed: $@"); $st->{"${kind}_fail"} = $now + 0 }
        $changed = 1;
    }
    write_json($f, $st) if $changed;
}

sub center_report_cli {
    my ($cfg, $what) = @_;
    my $now = time;
    my ($kind, $from, $to);
    if ($what =~ /^(week|month)$/i) { $kind = lc $1; ($from, $to) = period_bounds($kind, $now) }
    elsif ($what =~ /^(\d+)d$/i && $1 > 0 && $1 <= 400) { $kind = 'days'; ($from, $to) = ($now - $1 * 86400, $now) }
    else { die "Usage: mtmon-admin-center --period-report week|month|7d\n" }
    if ($opt{'dry-run'}) { no warnings 'redefine'; *send_mail = sub { my ($c, $s, $t) = @_; print "----- To: $c->{mail}{to}\nSubject: $s\n\n$t\n"; 1 } }
    center_report($cfg, $kind, $from, $to) or print "No site has reported yet.\n";
    return 0;
}

# what a site with mtmon $v does not get on this centre (empty: everything)
sub mtmon_missing {
    my ($v) = @_;
    return () unless defined $v && $v =~ /^\d+(\.\d+)*$/;
    return ("mtmon $v is older than $MTMON_MIN, which this centre needs") if vcmp_ver($v, $MTMON_MIN) < 0;
    return map { "$_->[1] (mtmon $_->[0])" } grep { vcmp_ver($v, $_->[0]) < 0 } @MTMON_FEATURES;
}

# the newest mtmon known: the one this centre is built with, or a newer one a site already runs
sub mtmon_latest {
    my ($cfg) = @_;
    my $l = $MTMON_VERSION;
    for my $id (keys %{ $cfg->{sites} }) {
        my $lt = site_latest($cfg, $id) or next;
        my $v = $lt->{status}{version} or next;
        $l = $v if $v =~ /^\d+(\.\d+)*$/ && vcmp_ver($v, $l) > 0;
    }
    return $l;
}

sub list_sites {
    my ($cfg) = @_;
    my $latest = mtmon_latest($cfg);
    printf "%-20s %-8s %-19s %-28s %s\n", qw(SITE STATE LAST-REPORT LOCATION MTMON);
    my $old = 0;
    for my $id (sort keys %{ $cfg->{sites} }) {
        my $s = site_summary($cfg, $id);
        my $up = $s->{version} && vcmp_ver($s->{version}, $latest) < 0;
        $old++ if $up;
        printf "%-20s %-8s %-19s %-28s %s\n", $id, $s->{state}, $s->{received} ? fmt_time($s->{received}) : '-',
               substr($s->{title} // '', 0, 28), ($s->{version} // '-') . ($up ? "  (update to $latest)" : '');
    }
    print "\nCurrent mtmon: $latest" . ($latest ne $MTMON_VERSION ? " (this centre is built with $MTMON_VERSION)" : '') . ($old ? ", $old site(s) to update" : '') . "\n";
    for my $id (sort keys %{ $cfg->{sites} }) {
        my @m = mtmon_missing(site_summary($cfg, $id)->{version}) or next;
        print "  $id: without " . join('; ', @m) . "\n";
    }
    return 0;
}

# ==========================================================================
# web: the centre's pages and API
# ==========================================================================
sub may_see { my ($who, $id) = @_; return !$who->{sites} || $who->{sites}{$id} }

# ---- push notifications for the MT-Mon Android app ------------------------------------------
# A phone signs in once (its web session) and gets a device token; with it the app waits for new
# events of the sites its user may see (GET /api/push/events, answered as soon as there is one,
# or after up to 50 s). Only the hash of a token is kept, in data_dir/push-tokens.json.
# 7.9: what a phone is told about - chosen per phone on the centre's page (Push notifications).
# [key, row, column, event types, default]
sub push_cats {
    return (
        [ 'ap_down',    'Access points',    'problem', [qw(ap_missing)],  1 ], [ 'ap_up',    'Access points',    'ok', [qw(ap_back)],  1 ],
        [ 'dev_down',   'Switches, devices', 'problem', [qw(dev_down many_down)], 1 ], [ 'dev_up',   'Switches, devices', 'ok', [qw(dev_up)],   1 ],
        [ 'ctl_down',   'Controllers',      'problem', [qw(ctl_down)],    1 ], [ 'ctl_up',   'Controllers',      'ok', [qw(ctl_up)],   1 ],
        [ 'site_down',  'Sites',            'problem', [qw(site_offline)], 1 ], [ 'site_up', 'Sites',            'ok', [qw(site_online)], 1 ],
        [ 'disk_low',   'Server disk',      'problem', [qw(disk_low)],    1 ], [ 'disk_ok',  'Server disk',      'ok', [qw(disk_ok)],  1 ],
        [ 'maint_start', 'Maintenance',     'problem', [qw(maint_start)], 1 ], [ 'maint_end', 'Maintenance',     'ok', [qw(maint_end)], 0 ],
        [ 'maint_mine', 'Maintenance',      'mine',    [],                0 ],
        [ 'devices',    'Devices added, removed, renamed', 'problem', [qw(dev_added dev_removed dev_renamed dev_changes)], 1 ],
        [ 'flap',       'Unstable devices', 'problem', [qw(ap_flap dev_flap)], 0 ],
        [ 'ports',      'Switch ports',     'problem', [qw(port_problem)], 0 ], [ 'ports_ok', 'Switch ports', 'ok', [qw(port_ok)], 0 ],
        [ 'reboot',     'Restarts',         'problem', [qw(dev_reboot)],  0 ],
        [ 'cert',       'Certificates',     'problem', [qw(cert_warn)],   0 ],
    );
}
sub push_pref {                                          # a phone's entry -> { cat => 0|1 } with the defaults filled in
    my ($e) = @_;
    my $p = ref(($e // {})->{p}) eq 'HASH' ? $e->{p} : {};
    return { map { ($_->[0] => (exists $p->{ $_->[0] } ? ($p->{ $_->[0] } ? 1 : 0) : $_->[4])) } push_cats() };
}
sub push_types { my %t; $t{$_} = 1 for map { @{ $_->[3] } } push_cats(); sort keys %t }   # every type a phone can get
sub push_file { "$_[0]{general}{data_dir}/push-tokens.json" }
sub web_fail_file { "$_[0]{general}{data_dir}/web-fail.json" }
sub push_tokens { read_json(push_file($_[0])) || {} }
sub push_change {                                       # read, change and write under a lock
    my ($cfg, $fn) = @_;
    open(my $lk, '>>', push_file($cfg) . '.lock') or die "Cannot open the lock file: $!\n";
    flock($lk, LOCK_EX);
    my $t = push_tokens($cfg);
    my $r = $fn->($t);
    write_json(push_file($cfg), $t);
    chmod 0640, push_file($cfg);
    close $lk;
    return $r;
}
sub push_user {                                         # token -> the user it was made for (undef: unknown / user gone)
    my ($cfg, $tok) = @_;
    return undef unless ($tok // '') =~ /^mtp_[A-Za-z0-9_-]{20,}$/;
    my $h = sha256_hex($tok);
    my $e = push_tokens($cfg)->{$h} or return undef;
    my $u = %{ $cfg->{web}{_users} } ? $cfg->{web}{_users}{ lc($e->{user} // '') } : { name => '', role => 'full' };
    return $u ? { %$u, _push => $h, _push_name => $e->{name} } : undef;
}
sub push_list_cli {
    my ($cfg) = @_;
    my $t = push_tokens($cfg);
    print "No phone gets push notifications.\n" and return 0 unless %$t;
    printf "%-28s %-16s %-17s %s\n", 'Phone', 'User', 'Registered', 'Last seen';
    printf "%-28s %-16s %-17s %s\n", $_->{name}, $_->{user} || '-', strftime('%Y-%m-%d %H:%M', localtime $_->{created}),
        $_->{seen} ? strftime('%Y-%m-%d %H:%M', localtime $_->{seen}) : '-' for sort { lc $a->{name} cmp lc $b->{name} } values %$t;
    return 0;
}
sub push_remove_cli {
    my ($cfg, $name) = @_;
    my $n = push_change($cfg, sub { my $t = shift; my @k = grep { $name eq 'all' || lc $t->{$_}{name} eq lc $name } keys %$t; delete @$t{@k}; scalar @k });
    print $n ? "Removed $n phone(s); they get no more push notifications.\n" : "No phone named '$name' (see --push-list).\n";
    return $n ? 0 : 1;
}
# 7.9: maintenance set or ended on the centre goes to the phones at once (mtmon applies it only with its
# next report); the same event coming back from mtmon later is not pushed again
sub push_now {
    my ($cfg, $e) = @_;
    eval { append_jsonl({ state_file => "$cfg->{general}{data_dir}/x" }, 'push-now.jsonl', { %$e, t => time + 0 }); 1 }
        or logmsg('warn', "Push: cannot write push-now.jsonl: $@");
}
sub push_from_centre {                                   # this event of mtmon was already pushed by the centre
    my ($e) = @_;
    return 1 if ($e->{type} // '') eq 'maint_start' && ($e->{by} // '') =~ /\(centre\)$/;
    return 1 if ($e->{type} // '') eq 'maint_end' && ($e->{text} // '') =~ /^ended early by .*\(centre\)$/;
    return 0;
}

# new events of the visible sites after $since; waits up to $wait seconds for the first one
sub push_events {
    my ($cfg, $ids, $since, $wait, $own, $pe, $user) = @_;
    my $pp = push_pref($pe);
    my %want = map { ($_ => 1) } map { @{ $_->[3] } } grep { $pp->{ $_->[0] } } push_cats();
    # a maintenance window this user set (on the centre or on the mtmon, under the same name): only if asked for
    my $me = lc($user // '');
    my $mine = sub { my $b = lc($_[0]{by} // ''); length $me && ($b eq $me || index($b, "$me ") == 0) };
    my $ok = sub { my $e = shift; return 0 if ($e->{type} // '') =~ /^maint_/ && !$pp->{maint_mine} && $mine->($e); 1 };
    my $txt = sub {                                     # maintenance: say what, until when, who and why
        my ($e, $sst) = @_;
        return (push_name($sst, $e), $e->{text} // '') unless ($e->{type} // '') =~ /^maint_(start|end)$/;
        my $st = $1;
        my $w = ($e->{name} // '') =~ /^(all|\*)$/ ? 'whole site' : target_name($sst, $e->{name} // '');
        return (($st eq 'start' ? 'Maintenance: ' : 'Maintenance over: ') . $w,
                join(', ', grep { length } $e->{text} // '', (length($e->{by} // '') && $st eq 'start' ? "by $e->{by}" : ''), $e->{reason} // ''));
    };
    my $end = time + $wait;
    my %mt;
    while (1) {
        my @ev;
        for my $id (@$ids) {
            my $f = data_file(site_g($cfg, $id), 'events.jsonl');
            my $m = (stat $f)[9] // 0;
            next if defined $mt{$id} && $mt{$id} == $m;     # unchanged since the last look
            $mt{$id} = $m;
            next if $m < $since;
            my $lt = site_latest($cfg, $id);
            my $title = ($lt && $lt->{status}{location}) || $id;
            # by the time the centre got the event (rt): an event mtmon saw minutes before its report came
            # is still new for the phone (7.8; before, such events were lost when the report came late)
            my $st = $lt ? $lt->{status} : undef;
            # 7.9.2: the whole site in maintenance - nothing about its devices goes to the phones (as no mail goes),
            # also from a mtmon that does not mark every such event
            my $sm = $lt && site_in_maint($cfg, $id, $lt);
            push @ev, map { my ($n, $x) = $txt->($_, $st); +{ t => $_->{t}, site => $id, site_title => $title, type => $_->{type}, name => $n,
                              ip => $_->{ip} // $_->{host} // '', text => $x, heading => $_->{heading} // '' } }
                      grep { $want{ $_->{type} // '' } && !$_->{maint} && !$_->{behind} && !$_->{quiet} && ($_->{rt} // $_->{t}) > $since && $ok->($_) && !push_from_centre($_)
                             && !($sm && ($_->{type} // '') !~ /^maint_/) } read_jsonl($f, $since - 6 * 3600);
        }
        {                                                   # maintenance set on the centre (7.9)
            my $f = "$cfg->{general}{data_dir}/push-now.jsonl";
            my $m = (stat $f)[9] // 0;
            my %vis = map { ($_ => 1) } @$ids;
            if ((!defined $mt{'+'} || $mt{'+'} != $m) && $m >= $since) {
                $mt{'+'} = $m;
                for my $e (grep { $vis{ $_->{site} // '' } && $want{ $_->{type} // '' } && $_->{t} > $since && $ok->($_) } read_jsonl($f, $since)) {
                    my $lt = site_latest($cfg, $e->{site});
                    my ($n, $x) = $txt->($e, $lt ? $lt->{status} : undef);
                    push @ev, { t => $e->{t}, site => $e->{site}, site_title => ($lt && $lt->{status}{location}) || $e->{site}, type => $e->{type},
                                name => $n, ip => '', text => $x, heading => '' };
                }
            }
        }
        if ($own) {                                         # the centre's own (disk alert)
            my $f = "$cfg->{general}{data_dir}/center-events.jsonl";
            my $m = (stat $f)[9] // 0;
            if ((!defined $mt{''} || $mt{''} != $m) && $m >= $since) {
                $mt{''} = $m;
                push @ev, map { { t => $_->{t}, site => '', site_title => $cfg->{general}{title}, type => $_->{type}, name => $_->{name} // '',
                                  ip => '', text => $_->{text} // '', heading => $_->{heading} // '' } }
                          grep { $want{ $_->{type} // '' } && $_->{t} > $since } read_jsonl($f, $since);
            }
        }
        return [ sort { $a->{t} <=> $b->{t} } @ev ] if @ev || time >= $end;
        sleep 2;
    }
}

sub web_handle {
    my ($cfg, $c) = @_;
    my $w = $cfg->{web};
    local $SIG{ALRM} = sub { die "client timeout\n" };
    alarm 10;
    my ($req, %h, $n, $hb) = (req_line($c));
    if (!defined $req) { alarm 0; die "empty request\n" }
    while (defined(my $l = req_line($c))) {
        last if $l =~ /^\r?\n$/;
        $h{ lc $1 } = $2 if $l =~ /^([\w-]+):\s*(.*?)\s*$/;
        $hb += length $l;
        if (++$n > 100 || $hb > 32768) { alarm 0; die "headers too large\n" }
    }
    alarm 0;
    my ($method, $path) = $req =~ m{^(\w+)\s+(\S+)};
    $method //= '';
    my $peer = $c->peerhost // '';
    my ($route, $query) = split /\?/, $path // '/', 2;
    my %q = map { my ($k, $v) = split /=/, $_, 2; (url_dec($k) => url_dec($v // '')) } split /&/, $query // '';
    my $json = JSON::PP->new->utf8->canonical;
    my $jreply = sub { web_reply($c, $_[0], 'application/json', $json->encode($_[1])) };

    # ---- 7.13: an agent fetches its configuration and its saved state (site key, like the reports) ----
    if ($route =~ m{^/api/v1/agent/(config|backup)$}) {
        my $what = $1;
        return $jreply->(405, { error => 'GET only' }) unless $method eq 'GET';
        my ($key) = ($h{authorization} // '') =~ /^Bearer\s+(\S+)/i;
        my ($id) = ($key // '') =~ /^([A-Za-z0-9_-]+)\./;
        my $site = $id ? $cfg->{sites}{$id} : undef;
        if ((!$site || !const_eq(sha256_hex($key // ''), $site->{hash})) && ((stat $cfg->{_file})[9] // 0) != $cfg->{_mtime}) {
            my $new = eval { load_config($cfg->{_file}) };
            if ($new) { $cfg->{sites} = $new->{sites}; $site = $id ? $cfg->{sites}{$id} : undef }
        }
        if (!$site || !const_eq(sha256_hex($key // ''), $site->{hash})) {
            logmsg('warn', "Agent $what from $peer rejected: " . (!$id ? 'no site key' : !$site ? "site '$id' is not in [sites]" : "wrong key for site '$id'"));
            sleep 1;
            return $jreply->(401, { error => 'unknown site or wrong key' });
        }
        if ($what eq 'config') {
            my $t = agent_conf_read($cfg, $id);
            return $jreply->(404, { error => "no agent configuration for site '$id' on the centre (mtmon-admin-center --agent-config $id)" }) unless defined $t;
            logmsg('info', "Site $id: the agent at $peer took its configuration");
            return $jreply->(200, { config => $t, md5 => md5_hex(encode('UTF-8', $t)) });
        }
        my $b = read_json(site_dir($cfg, $id) . '/agent-backup.json');
        return $jreply->(404, { error => 'no saved state of this site' }) unless $b;
        logmsg('info', "Site $id: the agent at $peer took back its saved state (from " . fmt_time($b->{t}) . ')');
        return $jreply->(200, $b);
    }

    # ---- reports from the mtmon installations: site key, not limited by [web] allow ----
    # 7.21: /api/v1/history - the whole local history of a site in parts (mtmon 13.13+), same key
    if ($route =~ m{^/api/v1/(ingest|history)$}) {
        my $ep = $1;
        return $jreply->(405, { error => 'POST only' }) unless $method eq 'POST';
        my ($key) = ($h{authorization} // '') =~ /^Bearer\s+(\S+)/i;
        my ($id) = ($key // '') =~ /^([A-Za-z0-9_-]+)\./;
        my $site = $id ? $cfg->{sites}{$id} : undef;
        if ((!$site || !const_eq(sha256_hex($key // ''), $site->{hash})) && ((stat $cfg->{_file})[9] // 0) != $cfg->{_mtime}) {
            # center.conf changed after this web process started (e.g. mtmon-admin-center --add-site):
            # take the sites from the file now, without waiting for a reload
            my $new = eval { load_config($cfg->{_file}) };
            if ($new) { $cfg->{sites} = $new->{sites}; $site = $id ? $cfg->{sites}{$id} : undef }
            else      { logmsg('warn', "Reading $cfg->{_file} again failed: $@") }
        }
        if (!$site || !const_eq(sha256_hex($key // ''), $site->{hash})) {
            logmsg('warn', "Ingest from $peer rejected: " . (!$id ? 'no site key' : !$site ? "site '$id' is not in [sites] of $cfg->{_file}"
                : "wrong key for site '$id' (key ending ..." . substr($key, -4) . ')'));
            sleep 1;
            # read what the mtmon sends before answering: closing with unread data makes the connection
            # end with a reset, and the mtmon would only see "broken pipe" instead of this answer
            drain_body($c, $h{'content-length'});
            return $jreply->(401, { error => 'unknown site or wrong key' });
        }
        my $len = $h{'content-length'} // '';
        return $jreply->(411, { error => 'Content-Length required' }) unless $len =~ /^\d+$/;
        if ($len > 16_000_000) {
            logmsg('warn', "Site $id: report from $peer refused: $len bytes is more than 16 MB");
            return $jreply->(413, { error => 'report too large' });
        }
        my ($body, $err) = read_body($c, $len, 120);
        if (length($body) < $len) {
            logmsg('warn', "Site $id: report from $peer incomplete: got " . length($body) . " of $len bytes ($err)");
            return $jreply->(400, { error => 'incomplete body' });
        }
        if (($h{'content-encoding'} // '') =~ /gzip/i) {
            require IO::Uncompress::Gunzip;
            no warnings 'once';
            # unpacked in pieces, at most 100 MB: a small packed file cannot fill the memory
            my ($plain, $buf, $ok) = ('', '', 1);
            my $z = IO::Uncompress::Gunzip->new(\$body);
            if (!$z) { $ok = 0 }
            else {
                while ((my $r = $z->read($buf, 1 << 20)) > 0) {
                    $plain .= $buf;
                    if (length $plain > 100_000_000) { $ok = 0; last }
                }
                $ok = 0 if $z->error;
                $z->close;
            }
            unless ($ok) {
                logmsg('warn', "Site $id: report from $peer: cannot unpack (" . (length $plain > 100_000_000 ? 'more than 100 MB unpacked' : $IO::Uncompress::Gunzip::GunzipError // '') . ")");
                return $jreply->(400, { error => 'cannot unpack the report' });
            }
            $body = $plain;
        }
        my ($code, $res) = eval { $ep eq 'history' ? history_in($cfg, $site, $body, $peer) : ingest($cfg, $site, $body, $peer) };
        ($code, $res) = (500, { error => "$@" =~ s/\s+$//r }) unless defined $code;
        logmsg('warn', "Site $id: report from $peer not stored: $res->{error}") if $code != 200;
        return $jreply->($code, $res);
    }
    return web_reply($c, 200, 'text/plain', "ok\n") if $route eq '/healthz';
    return web_reply($c, 403, 'text/plain', "Access from $peer is not allowed.\n") unless ip_allowed($w, $peer);

    # ---- sign-in -------------------------------------------------------------
    my $auth_on = (%{ $w->{_users} } || %{ $cfg->{_api_keys} }) ? 1 : 0;
    my $who = $auth_on ? undef : { name => '', role => 'full' };
    if ($auth_on) {
        my %ck = map { /^\s*([^=]+)=(.*)$/ ? ($1 => $2) : () } split /;/, $h{cookie} // '';
        $who = session_valid($cfg, $ck{mtmon_session});
        if (!$who && $route =~ m{/api/} && ($h{authorization} // '') =~ /^Bearer\s+(\S+)/i) { $who = api_key_user($cfg, $1, $peer) }
        if (!$who && $route =~ m{/api/} && ($h{authorization} // '') =~ /^Basic\s+(\S+)/i) {
            my ($un, $pw) = split /:/, decode('UTF-8', decode_base64($1), Encode::FB_DEFAULT), 2;
            my $u = $w->{_users}{ lc($un // '') };
            my $fkey = $peer . '|' . lc($un // '');           # the same lock as the sign-in page
            if (!web_fail($cfg, 'check', $fkey)) {
                if ($u && pw_ok($u->{secret}, $pw // '')) { $who = $u; web_fail($cfg, 'ok', $fkey) }
                else { web_fail($cfg, 'fail', $fkey); logmsg('warn', "Web: failed API sign-in from $peer"); sleep 1 }
            }
        }
    }
    # a phone's device token (push notifications) - also when the centre has no sign-in
    if ($route =~ m{^/api/push/} && ($h{authorization} // '') =~ /^Bearer\s+(mtp_\S+)/i) { my $pu = push_user($cfg, $1); $who = $pu if $pu }
    if ($route eq '/login') {
        return web_reply($c, 303, 'text/plain', '', 'Location: /') if $who;
        if ($method eq 'POST') {
            my $len = $h{'content-length'} // 0;
            return web_reply($c, 413, 'text/plain', "Request too large.\n") if $len !~ /^\d+$/ || $len > 4096;
            my $body = '';
            alarm 10;
            read($c, $body, $len) if $len;
            alarm 0;
            my %f = map { my ($k, $v) = split /=/, $_, 2; (url_dec($k) => url_dec($v // '')) } split /&/, $body;
            my $fkey = $peer . '|' . lc($f{user} // '');          # locked: this name from this address only
            if (my $left = web_fail($cfg, 'check', $fkey)) {
                my $min = int(($left + 59) / 60);
                return web_reply($c, 200, 'text/html; charset=utf-8', login_page($cfg, "Too many wrong attempts. Try again in $min min.", $f{user}));
            }
            my $u = $w->{_users}{ lc($f{user} // '') };
            if ($u && pw_ok($u->{secret}, $f{password} // '')) {
                web_fail($cfg, 'ok', $fkey);
                $WEB_RESULT = 'ok';
                logmsg('info', "Web: '$u->{name}' signed in from $peer");
                my $max = $w->{session_hours} * 3600;
                return web_reply($c, 303, 'text/plain', '', 'Location: /',
                    'Set-Cookie: mtmon_session=' . session_token($cfg, $u, time + $max) . "; Path=/; Max-Age=$max; HttpOnly; SameSite=Strict" . ($w->{_secure} ? '; Secure' : ''));
            }
            $WEB_RESULT = 'fail';
            (my $tried = substr($f{user} // '', 0, 40)) =~ s/[^\w.\@\\-]/?/g;
            my $locked = web_fail($cfg, 'fail', $fkey);
            logmsg('warn', "Web: failed sign-in" . (length $tried ? " as '$tried'" : '') . " from $peer" . ($locked ? ' - locked for 5 min' : ''));
            sleep 1;
            return web_reply($c, 200, 'text/html; charset=utf-8', login_page($cfg, $locked ? 'Too many wrong attempts. Try again in 5 min.' : 'Wrong user name or password.', $f{user}));
        }
        return web_reply($c, 200, 'text/html; charset=utf-8', login_page($cfg, '', ''));
    }
    if ($route eq '/logout') {
        return web_reply($c, 303, 'text/plain', '', 'Location: /login',
            'Set-Cookie: mtmon_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict' . ($w->{_secure} ? '; Secure' : ''));
    }
    if (!$who) {
        return $jreply->(401, { error => 'sign in required' }) if $route =~ m{/api/};
        return web_reply($c, 303, 'text/plain', '', 'Location: /login');
    }
    my @ids = grep { may_see($who, $_) } sort keys %{ $cfg->{sites} };

    # ---- push notifications (MT-Mon app) ---------------------------------------------------
    if ($route eq '/api/push/register') {
        return $jreply->(405, { error => 'POST only' }) unless $method eq 'POST';
        return $jreply->(403, { error => 'sign in with a user, not with a key' }) if $who->{_push} || exists $who->{_allow};
        my $len = $h{'content-length'} // 0;
        return $jreply->(413, { error => 'too large' }) if $len !~ /^\d+$/ || $len > 4096;
        my ($body) = read_body($c, $len, 10);
        my $p = eval { JSON::PP->new->utf8->decode($body || '{}') } || {};
        (my $name = substr($p->{name} // 'phone', 0, 60)) =~ s/[^\w .\-]/_/g;
        my $tok = 'mtp_' . random_token(32);
        push_change($cfg, sub {
            my $t = shift;
            delete $t->{$_} for grep { lc $t->{$_}{name} eq lc $name && lc($t->{$_}{user} // '') eq lc($who->{name} // '') } keys %$t;
            $t->{ sha256_hex($tok) } = { name => $name, user => $who->{name} // '', created => time + 0 };
        });
        logmsg('info', "Push: phone '$name' registered by '" . ($who->{name} // '') . "' from $peer");
        return $jreply->(200, { token => $tok, name => $name, types => [ push_types() ], center => $cfg->{general}{title} });
    }
    if ($route eq '/api/push/unregister') {
        return $jreply->(401, { error => 'device token required' }) unless $who->{_push};
        push_change($cfg, sub { delete $_[0]{ $who->{_push} } });
        logmsg('info', "Push: phone '$who->{_push_name}' unregistered");
        return $jreply->(200, { ok => JSON::PP::true });
    }
    if ($route eq '/api/push/events') {
        return $jreply->(401, { error => 'device token required' }) unless $who->{_push};
        my $now = time;
        my $since = ($q{since} // '') =~ /^\d+$/ ? $q{since} : $now - 60;
        $since = $now - 86400 if $since < $now - 86400;
        my $wait = ($q{wait} // '') =~ /^\d+$/ ? ($q{wait} > 50 ? 50 : $q{wait}) : 0;
        my $h = $who->{_push};
        my $t = push_tokens($cfg);
        if ($t->{$h} && ($t->{$h}{seen} // 0) < $now - 3600) { eval { push_change($cfg, sub { $_[0]{$h}{seen} = $now if $_[0]{$h} }) } }
        my $ev = push_events($cfg, \@ids, $since, $wait, !$who->{sites} && ($who->{role} // '') eq 'full', $t->{$h}, $who->{name});
        return $jreply->(200, { now => time + 0, events => $ev, center => $cfg->{general}{title} });
    }

    # ---- 7.9: the phones of the signed-in user and what each is told about ------------------
    if ($route eq '/api/push/phones') {
        return $jreply->(403, { error => 'sign in with a user' }) if $who->{_push} || exists $who->{_allow};
        my $me = lc($who->{name} // '');
        my $admin = ($who->{role} // '') eq 'full' && !$who->{sites};       # sees and changes every phone
        my $mayp = sub { my $e = shift; $admin || lc($e->{user} // '') eq $me };
        if ($method eq 'POST') {
            my $len = $h{'content-length'} // 0;
            return $jreply->(413, { error => 'too large' }) if $len !~ /^\d+$/ || $len > 8192;
            my ($body) = read_body($c, $len, 10);
            my $p = eval { JSON::PP->new->utf8->decode($body || '{}') } || {};
            my $id = $p->{id} // '';
            return $jreply->(400, { error => 'id?' }) unless $id =~ /^[0-9a-f]{16}$/;
            my %cat = map { ($_->[0] => 1) } push_cats();
            my $r = push_change($cfg, sub {
                my $t = shift;
                my ($k) = grep { substr($_, 0, 16) eq $id } keys %$t or return 'none';
                return 'none' unless $mayp->($t->{$k});
                if ($p->{remove}) { logmsg('info', "Push: phone '$t->{$k}{name}' removed by '" . ($who->{name} // '') . "' on the page"); delete $t->{$k}; return 'ok' }
                for my $c (keys %{ ref $p->{p} eq 'HASH' ? $p->{p} : {} }) { $t->{$k}{p}{$c} = $p->{p}{$c} ? 1 : 0 if $cat{$c} }
                return 'ok';
            });
            return $jreply->(404, { error => 'no such phone' }) if $r eq 'none';
        }
        my $t = push_tokens($cfg);
        my @ph = map { my $e = $t->{$_}; +{ id => substr($_, 0, 16), name => $e->{name}, user => $e->{user} // '', created => $e->{created} // 0,
                                           seen => $e->{seen} // 0, p => push_pref($e) } }
                 sort { lc $t->{$a}{name} cmp lc $t->{$b}{name} } grep { $mayp->($t->{$_}) } keys %$t;
        return $jreply->(200, { phones => \@ph, admin => $admin ? JSON::PP::true : JSON::PP::false, me => $who->{name} // '',
                                cats => [ map { +{ k => $_->[0], row => $_->[1], col => $_->[2], def => $_->[4] } } push_cats() ] });
    }

    # ---- backup and restore (7.20) ---------------------------------------------------
    return if bk_web($c, $cfg, $route, $method, \%h, \%q, $who, $peer, $jreply);

    # ---- overview of all sites ----------------------------------------------------
    if ($route eq '/' || $route eq '/index.html') { return web_file($c, $cfg, 'center.html') }
    if ($route eq '/wall') { return web_file($c, $cfg, 'wall.html') }      # wall / NOC view (6.2 prototype)
    if ($route eq '/manual') {
        return manual_page($c, 'mtmon-admin-center', $q{lang}, $h{'accept-language'}, '/usr/share/doc/mtmon-admin-center', dirname(__FILE__) . '/docs', dirname(__FILE__));
    }
    if ($route eq '/manual/mtmon' || $route =~ m{^/site/[^/]+/manual$}) {     # also from a site page (the mtmon dashboard)
        return manual_page($c, 'mtmon', $q{lang}, $h{'accept-language'}, '/usr/share/doc/mtmon-admin-center', dirname(__FILE__) . '/docs', dirname(__FILE__));
    }
    if ($route eq '/report') {          # Wi-Fi report of all sites (the same page as a site's report)
        my $rc = JSON::PP->new->canonical->encode({ api => 'api/overview/report', dapi => 'api/overview/devices/report', back => '/#/wifi', kind => 'sites' });
        return web_file($c, $cfg, 'report.html', sub { $_[0] =~ s{/\*MTMON-REPORT\*/}{window.REPORT = $rc;} });
    }
    if ($route eq '/api/overview/devices/report') {
        my $to = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
        my $from = ($q{from} // '') =~ /^\d+$/ && $q{from} < $to ? $q{from} : $to - 30 * 86400;
        $from = $to - 3 * 366 * 86400 if $to - $from > 3 * 366 * 86400;
        my $grp = $q{group} // '';
        my @parts;
        for my $id (@ids) {
            next if length $grp && ($cfg->{sites}{$id}{group} // '') ne $grp;
            my $lt = site_latest($cfg, $id) or next;
            my $r = device_report_cached(site_g($cfg, $id, $lt->{status}{interval}), $from + 0, $to + 0, $lt->{status} || {});
            push @parts, [ $lt->{status}{location} || $id, $r ];
        }
        my $r = device_report_combine($from + 0, $to + 0, @parts);
        $r->{location} = $cfg->{general}{title} . (length $grp ? " · $grp" : '');
        my %sv;
        for my $id (@ids) {
            my $lt = site_latest($cfg, $id);
            my $name = ($lt && $lt->{status}{location}) || $id;
            $name .= " ($id)" if exists $sv{$name};
            $sv{$name} = $lt ? $lt->{status}{version} // '' : '';
        }
        $r->{site_versions} = \%sv;
        return $jreply->(200, $r);
    }
    if ($route eq '/api/overview/report') {
        my $to = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
        my $from = ($q{from} // '') =~ /^\d+$/ && $q{from} < $to ? $q{from} : $to - 30 * 86400;
        $from = $to - 3 * 366 * 86400 if $to - $from > 3 * 366 * 86400;
        my $grp = $q{group} // '';
        my @parts;
        for my $id (@ids) {
            next if length $grp && ($cfg->{sites}{$id}{group} // '') ne $grp;
            my $lt = site_latest($cfg, $id) or next;
            next unless ($lt->{clients} || {})->{enabled};
            my %ifmap = map { ($_->{name} => $_->{ifmap} || {}) } @{ ($lt->{clients} || {})->{controllers} || [] };
            my $r = client_report_cached({ general => site_g($cfg, $id, $lt->{status}{interval}) }, $from + 0, $to + 0, '', \%ifmap, ($q{aps} // '') eq '1');
            $r->{ap_count} = site_ap_count($lt, '');
            push @parts, [ $lt->{status}{location} || $id, $r ];
        }
        my $r = client_report_combine($from + 0, $to + 0, @parts);
        $r->{ap_count} = 0; $r->{ap_count} += $_->[1]{ap_count} // 0 for @parts;
        $r->{location} = $cfg->{general}{title} . (length $grp ? " · $grp" : '');
        $r->{controller_list} = [ map { { name => $_->[0], title => $_->[0] } } @parts ];
        return $jreply->(200, $r);
    }
    if ($route eq '/api/overview') {
        my @s = map { site_summary($cfg, $_) } @ids;
        my %gr = map { ($_->{group} => 1) } grep { length $_->{group} } @s;
    my $latest = mtmon_latest($cfg);
    $_->{outdated} = ($_->{version} && vcmp_ver($_->{version}, $latest) < 0) ? JSON::PP::true : JSON::PP::false for @s;
    for (@s) { my @m = mtmon_missing($_->{version}); $_->{missing} = \@m if @m }
        return $jreply->(200, { title => $cfg->{general}{title}, version => $VERSION, now => time + 0, started => $^T + 0, refresh => $w->{refresh} + 0,
                                user => $who->{name}, role => $who->{role}, operator => ($who->{operator} ? JSON::PP::true : JSON::PP::false), auth => ($auth_on ? JSON::PP::true : JSON::PP::false),
                                groups => [ sort { lc $a cmp lc $b } keys %gr ], mtmon_latest => $latest, mtmon_bundled => $MTMON_VERSION,
                                mtmon_min => $MTMON_MIN, sites => \@s,
                                admin => (bk_admin($who, $cfg) ? JSON::PP::true : JSON::PP::false), backup_alert => (bk_admin($who, $cfg) && bk_alert($cfg) ? JSON::PP::true : JSON::PP::false) });
    }
    if ($route eq '/api/overview/devices') { return $jreply->(200, { rows => center_devices($cfg, \@ids), t => time + 0 }) }
    if ($route eq '/api/overview/clients/find') {
        return $jreply->(403, { error => 'The client lists are only for users with role full.' }) unless $who->{role} eq 'full';
        my $q = $q{q} // '';
        $q =~ s/^\s+|\s+$//g;
        return $jreply->(400, { error => 'Type at least 2 characters.' }) if length($q) < 2;
        return $jreply->(200, center_client_find($cfg, \@ids, substr($q, 0, 60)));
    }
    if ($route eq '/api/overview/server') {
        return $jreply->(403, { error => 'Only for users with role full.' }) unless $who->{role} eq 'full';
        return $jreply->(200, center_server_info($cfg, \@ids));
    }
    if ($route eq '/api/overview/maintenance') {
        if ($method eq 'POST') {
            my $p = post_json($c, \%h, $who, $jreply) or return;
            my $id = $p->{site} // '';
            return $jreply->(404, { error => 'Unknown site.' }) unless $cfg->{sites}{$id} && may_see($who, $id);
            return $jreply->(center_maint($cfg, $id, $p, $who, $peer, 'add'));
        }
        return $jreply->(200, { can_edit => ($who->{role} eq 'full' ? JSON::PP::true : JSON::PP::false), sites => [ map { site_maint_info($cfg, $_) } @ids ] });
    }
    if ($route eq '/api/overview/maintenance/end' && $method eq 'POST') {
        my $p = post_json($c, \%h, $who, $jreply) or return;
        my $id = $p->{site} // '';
        return $jreply->(404, { error => 'Unknown site.' }) unless $cfg->{sites}{$id} && may_see($who, $id);
        return $jreply->(center_maint($cfg, $id, $p, $who, $peer, 'end'));
    }
    if ($route =~ m{^/api/overview/inventory(\.csv)?$}) {
        my $csv = $1;
        my @rows;
        my $latest_m = mtmon_latest($cfg);
        for my $id (@ids) {
            my $lt = site_latest($cfg, $id) or next;
            my $sv = $lt->{status}{version};
            push @rows, { type => 'mtmon', name => $lt->{status}{host} || $id, ip => $lt->{from}, version => $sv, site => ($lt->{status}{location} || $id),
                          site_id => $id, group => $cfg->{sites}{$id}{group}, status => (time - $lt->{received} > offline_limit($cfg, $lt) ? 'down' : 'up'),
                          ($sv && vcmp_ver($sv, $latest_m) < 0 ? (mismatch => "update to $latest_m") : ()) } if $sv;
            push @rows, map { +{ %$_, site => ($lt->{status}{location} || $id), site_id => $id, group => $cfg->{sites}{$id}{group} } } @{ $lt->{status}{inventory} || [] };
        }
        return web_reply($c, 200, 'text/csv; charset=utf-8', encode('UTF-8', inventory_csv(\@rows, 1)),
                         'Content-Disposition: attachment; filename="mtmon-inventory-all-sites-' . strftime('%Y%m%d', localtime) . '.csv"') if $csv;
        return $jreply->(200, { rows => \@rows });
    }
    if ($route eq '/api/overview/certificates') {
        my $now = time;
        my @l;
        for my $id (@ids) {
            my $lt = site_latest($cfg, $id) or next;
            push @l, map { +{ %$_, site => ($lt->{status}{location} || $id), site_id => $id,
                              days => ($_->{not_after} ? int(($_->{not_after} - $now) / 86400) : undef) } } @{ $lt->{status}{certs} || [] };
        }
        return $jreply->(200, { center => center_cert_info($cfg), certs => \@l, warn_days => $cfg->{general}{_cert_warn} });
    }
    if ($route eq '/api/overview/events') {
        my $lim = ($q{limit} // '') =~ /^\d+$/ ? ($q{limit} > 5000 ? 5000 : $q{limit}) : 200;
        my $days = ($q{days} // '') =~ /^\d+$/ && $q{days} > 0 ? $q{days} : 30;
        $days = $w->{history_days} if $days > $w->{history_days};
        my @ev;
        for my $id (@ids) {
            my $lt = site_latest($cfg, $id);
            my $title = ($lt && $lt->{status}{location}) || $id;
            my @e = read_jsonl(data_file(site_g($cfg, $id), 'events.jsonl'), time - $days * 86400);
            push @ev, map { { %$_, site => $id, site_title => $title } } @e[ ($#e > $lim ? $#e - $lim + 1 : 0) .. $#e ];
        }
        @ev = sort { $b->{t} <=> $a->{t} } @ev;
        splice @ev, $lim if @ev > $lim;
        return $jreply->(200, \@ev);
    }
    # access points + devices working and not working, all sites together (trend lines on the overview)
    if ($route eq '/api/overview/history') {
        my $to = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
        my $from = ($q{from} // '') =~ /^\d+$/ && $q{from} < $to ? $q{from} : $to - 86400;
        my $n = 120;
        my $step = int(($to - $from) / $n) || 1;
        my (%on, %bad);
        for my $id (@ids) {
            my $lt = site_latest($cfg, $id) or next;
            my $r = hist_range({ general => site_g($cfg, $id, $lt->{status}{interval}) }, 'history', $from + 0, $to + 0, $n);
            my %b;
            for my $p (@{ $r->{points} }) {
                my ($o, $x) = (0, 0);
                for my $c (values %{ $p->{c} || {} }) { $o += $c->[0] // 0; $x += ($c->[1] // 0) + 1 - ($c->[2] // 1) }
                if ($p->{s}) { $o += $p->{s}[0] // 0; $x += $p->{s}[1] // 0 }
                my $k = $from + int(($p->{t} - $from) / $step) * $step;
                my $e = $b{$k} ||= [ 0, 0, 0 ];
                $e->[0] += $o; $e->[1] += $x; $e->[2]++;
            }
            my @k = sort { $a <=> $b } keys %b or next;
            my $prev;
            # a site counts with its last known numbers until the end of the period, also while it
            # does not report - the total does not drop just because one report is late
            my $end = $from + int(($to - $from) / $step) * $step;
            for (my $k = $k[0]; $k <= $end; $k += $step) {
                $prev = [ $b{$k}[0] / $b{$k}[2], $b{$k}[1] / $b{$k}[2] ] if $b{$k};
                $on{$k} += $prev->[0]; $bad{$k} += $prev->[1];
            }
        }
        my $rd = sub { 0 + sprintf('%.2f', $_[0]) };
        return $jreply->(200, { from => $from + 0, to => $to + 0, step => $step + 0,
                                points => [ map { [ $_ + 0, $rd->($on{$_}), $rd->($bad{$_}) ] } sort { $a <=> $b } keys %on ] });
    }
    if ($route eq '/api/overview/clients') {
        my $to = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
        my $from = ($q{from} // '') =~ /^\d+$/ && $q{from} < $to ? $q{from} : $to - 86400;
        # every site on one common time grid, at most one point per site and step (average of the
        # averages, highest peak) - the browser adds the sites up per step. Without this a site that
        # is checked more often than once per step was counted several times (5.0.4).
        my (%r, $step);
        for my $id (@ids) {
            my $lt = site_latest($cfg, $id) or next;
            $r{$id} = hist_range({ general => site_g($cfg, $id, $lt->{status}{interval}) }, 'clients', $from + 0, $to + 0, 300);
            $step = $r{$id}{step} if !$step || $r{$id}{step} > $step;
        }
        $step ||= 300;
        my $min = int(($to - $from) / 300) || 1;
        $step = $min if $step < $min;
        my %out;
        for my $id (keys %r) {
            my %b;
            for my $p (@{ $r{$id}{points} }) {
                my $a = $p->{tot} && $p->{tot}{_all} or next;
                my $k = $from + int(($p->{t} - $from) / $step) * $step;
                my $e = $b{$k} ||= [ 0, 0, 0 ];
                $e->[0] += $a->[0] // 0; $e->[2]++;
                $e->[1] = $a->[1] if ($a->[1] // 0) > $e->[1];
            }
            $out{$id} = [ map { [ $_ + 0, 0 + sprintf('%.2f', $b{$_}[0] / $b{$_}[2]), $b{$_}[1] + 0 ] } sort { $a <=> $b } keys %b ];
        }
        return $jreply->(200, { from => $from + 0, to => $to + 0, step => $step + 0, sites => \%out });
    }

    # ---- one site: its own dashboard, with the data from the centre ----------------
    if ($route =~ m{^/site/([A-Za-z0-9_-]+)(/.*)?$}) {
        my ($id, $sub) = ($1, $2 // '');
        return web_reply($c, 404, 'text/plain', "Unknown site.\n") unless $cfg->{sites}{$id} && may_see($who, $id);
        return web_reply($c, 301, 'text/plain', '', "Location: /site/$id/") if $sub eq '';
        my $lt = site_latest($cfg, $id);
        my $g = site_g($cfg, $id, $lt ? $lt->{status}{interval} : 300);
        if ($sub eq '/' || $sub eq '/index.html') {
            return web_file($c, $cfg, 'dashboard.html', sub {
                my $nav = '<span class="sitenav"><a href="/" title="Back to the overview of all sites">&lsaquo; All sites</a>'
                        . '<select id="site-jump" aria-label="Go to another site" hidden></select></span>';
                $_[0] =~ s/<!--MTMON-SITENAV-->/$nav/;
            });
        }
        if ($sub eq '/topology') { return web_file($c, $cfg, 'topology.html') }   # 7.12: works without the web of that mtmon
        # 7.13: the configuration of an agent (mtmon --agent) - it holds passwords: role full only
        if ($sub eq '/agent' || $sub eq '/api/agent-config') {
            return ($sub eq '/agent' ? web_reply($c, 403, 'text/plain', "Only users with role full see the agent configuration.\n")
                                     : $jreply->(403, { error => 'Only users with role full see the agent configuration.' })) unless ($who->{role} // '') eq 'full';
            return web_file($c, $cfg, 'agent.html') if $sub eq '/agent';
            if ($method eq 'POST') {
                my $p = post_json($c, \%h, $who, $jreply, 300_000, 'change the agent configuration') or return;
                return $jreply->(400, { error => 'config?' }) unless defined $p->{config} && !ref $p->{config};
                return $jreply->(400, { error => 'The configuration is empty.' }) unless $p->{config} =~ /\S/;
                # someone else saved meanwhile: do not overwrite it unseen
                my $cur = agent_conf_md5($cfg, $id) // '';
                return $jreply->(409, { error => 'The configuration was changed meanwhile (by someone else or on the server). Load it again.', md5 => $cur })
                    if defined $p->{base} && $p->{base} ne $cur;
                my $bad = agent_conf_lint($p->{config});
                return $jreply->(400, { error => $bad }) if $bad;
                my $md5 = agent_conf_write($cfg, $id, $p->{config});
                logmsg('info', "Site $id: agent configuration changed by '" . ($who->{name} // '?') . "' from $peer");
            }
            my $t = agent_conf_read($cfg, $id);
            my $a = $lt && $lt->{agent};
            return $jreply->(200, { site => $id, title => ($lt ? $lt->{status}{location} : undef) || $id, exists => defined $t ? JSON::PP::true : JSON::PP::false,
                                    config => $t // agent_template($id), md5 => (defined $t ? md5_hex(encode('UTF-8', $t)) : ''),
                                    agent => $a, received => ($lt ? $lt->{received} : undef), interval => ($lt ? $lt->{status}{interval} : undef) });
        }
        if ($sub eq '/report') {
            my $rc = JSON::PP->new->canonical->encode({ api => 'api/clients/report', dapi => 'api/devices/report', back => './', kind => 'controllers' });
            return web_file($c, $cfg, 'report.html', sub { $_[0] =~ s{/\*MTMON-REPORT\*/}{window.REPORT = $rc;} });
        }
        return $jreply->(404, { error => 'no report from this site yet' }) unless $lt;
        if ($sub eq '/api/devices/report') {
            my $to = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
            my $from = ($q{from} // '') =~ /^\d+$/ && $q{from} < $to ? $q{from} : $to - 30 * 86400;
            $from = $to - 3 * 366 * 86400 if $to - $from > 3 * 366 * 86400;
            my $r = device_report_cached($g, $from + 0, $to + 0, $lt->{status} || {});
            $r->{location} = $lt->{status}{location} || $id;
            $r->{mtmon_version} = $lt->{status}{version};
            return $jreply->(200, $r);
        }
        if ($sub eq '/api/clients/report') {
            my $to = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
            my $from = ($q{from} // '') =~ /^\d+$/ && $q{from} < $to ? $q{from} : $to - 30 * 86400;
            $from = $to - 3 * 366 * 86400 if $to - $from > 3 * 366 * 86400;
            my @cl = @{ ($lt->{clients} || {})->{controllers} || [] };
            my $ctl = $q{ctl} // '';
            $ctl = '' unless grep { $_->{name} eq $ctl } @cl;
            my %ifmap = map { ($_->{name} => $_->{ifmap} || {}) } @cl;
            my $r = client_report_cached({ general => $g }, $from + 0, $to + 0, $ctl, \%ifmap, ($q{aps} // '') eq '1');
            $r->{location} = $lt->{status}{location} || $id;
            $r->{ap_count} = site_ap_count($lt, $ctl);
            $r->{controller_list} = [ map { { name => $_->{name}, title => ($_->{heading} || $_->{name}), label => $_->{label} } } @cl ];
            return $jreply->(200, $r);
        }
        if ($sub eq '/api/status') {
            my $s = { %{ $lt->{status} } };
            my $sum = site_summary($cfg, $id);
            @$s{qw(auth user role refresh)} = (($auth_on ? JSON::PP::true : JSON::PP::false), $who->{name}, $who->{role}, $w->{refresh} + 0);
            delete $s->{server} unless $who->{role} eq 'full';
            $s->{center} = { site => $id, state => $sum->{state}, received => $lt->{received} };
            return $jreply->(200, $s);
        }
        if ($sub eq '/api/clients') {
            my $cl = $lt->{clients} || { enabled => JSON::PP::false, controllers => [] };
            if ($who->{role} ne 'full' && $cl->{details}) {
                $cl = { %$cl, details => JSON::PP::false, details_off => 'role',
                        controllers => [ map { my %x = %$_; delete $x{clients}; \%x } @{ $cl->{controllers} || [] } ] };
            }
            return $jreply->(200, $cl);
        }
        if ($sub =~ m{^/api/(?:history|clients/history|clients/aphistory)$}) {
            my $kind = $sub eq '/api/history' ? 'history' : $sub eq '/api/clients/aphistory' ? 'clientsap' : 'clients';
            my $to = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
            my $from = ($q{from} // '') =~ /^\d+$/ && $q{from} < $to ? $q{from} : $to - ($q{hours} && $q{hours} =~ /^\d+$/ ? $q{hours} * 3600 : 86400);
            return $jreply->(200, hist_range({ general => $g }, $kind, $from + 0, $to + 0, 500));
        }
        if ($sub eq '/api/clients/peaks') { return $jreply->(200, client_peaks({ general => $g })) }
        if ($sub =~ m{^/api/maintenance(/end)?$}) {
            my $end = $1;
            if ($method eq 'POST') {
                my $p = post_json($c, \%h, $who, $jreply) or return;
                return $jreply->(center_maint($cfg, $id, $p, $who, $peer, $end ? 'end' : 'add'));
            }
            my $mi = site_maint_info($cfg, $id);
            return $jreply->(200, { can_edit => ($who->{role} eq 'full' ? JSON::PP::true : JSON::PP::false), active => $mi->{active}, pending => $mi->{pending} });
        }
        if ($sub eq '/api/inventory') { return $jreply->(200, { t => $lt->{received}, rows => $lt->{status}{inventory} || [], refreshed => ($lt->{status}{inventory_info} || {})->{refreshed} }) }
        if ($sub eq '/api/inventory.csv') {
            return web_reply($c, 200, 'text/csv; charset=utf-8', encode('UTF-8', inventory_csv($lt->{status}{inventory} || [])),
                             "Content-Disposition: attachment; filename=\"mtmon-inventory-$id-" . strftime('%Y%m%d', localtime) . '.csv"');
        }
        if ($sub eq '/api/certificates') { return $jreply->(200, $lt->{status}{certs} || []) }
        if ($sub eq '/api/events') {
            my $lim = ($q{limit} // '') =~ /^\d+$/ ? $q{limit} : 150;
            my @e = read_jsonl(data_file($g, 'events.jsonl'), time - ($cfg->{general}{_history_days} || 30) * 86400);
            @e = reverse @e;
            splice @e, $lim if @e > $lim;
            return $jreply->(200, \@e);
        }
        return $jreply->(404, { error => 'not found' });
    }
    return web_reply($c, 404, 'text/plain', "Not found.\n");
}

sub web_file {
    my ($c, $cfg, $name, $edit) = @_;
    my ($file) = grep { -r } "$cfg->{web}{html}/$name", dirname(__FILE__) . "/$name", dirname(__FILE__) . "/../$name";
    open(my $fh, '<:raw', $file // '') or return web_reply($c, 500, 'text/plain', "$name is missing\n");
    local $/;
    my $html = decode('UTF-8', <$fh>);
    close $fh;
    $edit->($html) if $edit;
    return web_reply($c, 200, 'text/html; charset=utf-8', $html, 'Cache-Control: no-store');
}

# ==========================================================================
# shared with mtmon (copied from mtmon when the package is built)
# ==========================================================================
sub logmsg {
    my ($lvl, $msg) = @_;
    return if $lvl eq 'debug' && !$DEBUG;
    chomp $msg;
    my %prio = (error => 3, warn => 4, info => 6, debug => 7);
    if (-t STDERR) { print STDERR strftime('%Y-%m-%d %H:%M:%S', localtime) . " [$lvl] $msg\n" }
    elsif (($ENV{MTMON_LOG} // '') eq 'plain') { print STDERR "[$lvl] $msg\n" }   # container (RouterOS log, docker logs)
    else           { print STDERR "<$prio{$lvl}>$msg\n" }    # journald priority
}

sub fmt_time {
    my ($t) = @_;
    return '-' unless $t;
    return strftime('%Y-%m-%d %H:%M', localtime $t);
}

sub h {
    my $s = shift // '';
    $s =~ s/&/&amp;/g; $s =~ s/</&lt;/g; $s =~ s/>/&gt;/g; $s =~ s/"/&quot;/g;
    return $s;
}

sub web_start {
    my ($cfg) = @_;
    return unless $cfg->{web}{enabled};
    my $pid = fork;
    if (!defined $pid) { logmsg('error', "Cannot start the web dashboard: $!"); $WEB_NEXT = time + 30; return }
    if ($pid == 0) { web_main($cfg) }
    $WEB_PID = $pid;
    $WEB_STARTED = time;
}

sub web_check {
    my ($cfg) = @_;
    return unless $cfg->{web}{enabled};
    if ($WEB_PID && waitpid($WEB_PID, WNOHANG) == $WEB_PID) {
        my $how = ($? & 127) ? "signal " . ($? & 127) : "exit " . ($? >> 8);
        # stops right after starting again and again (e.g. port in use, bad certificate):
        # wait longer each time, 10 s doubling up to 5 min
        $WEB_RUNS = time - $WEB_STARTED < 60 ? $WEB_RUNS + 1 : 1;
        my $wait = 10 * 2 ** ($WEB_RUNS > 6 ? 5 : $WEB_RUNS - 1);
        $wait = 300 if $wait > 300;
        logmsg('warn', "Web dashboard stopped ($how), restarting in $wait s");
        $WEB_PID = 0;
        $WEB_NEXT = time + $wait;
    }
    web_start($cfg) if !$WEB_PID && time >= $WEB_NEXT;
}

sub web_main {
    my ($cfg) = @_;
    $0 = web_procname();
    my $w = $cfg->{web};
    $SIG{TERM} = $SIG{INT} = sub { exit 0 };
    $SIG{HUP}  = 'IGNORE';
    # a client timeout must only end that request, never the web server (default action of SIGALRM)
    $SIG{ALRM} = sub { die "client timeout\n" };
    my $parent = getppid();
    my $ctx;
    if ($w->{tls}) {
        my ($crt, $key) = web_cert_files($cfg) or exit 3;
        eval { require IO::Socket::SSL; 1 }
            or do { logmsg('error', "Web dashboard: tls = yes needs IO::Socket::SSL (libio-socket-ssl-perl): $@"); exit 3 };
        $ctx = IO::Socket::SSL::SSL_Context->new(SSL_server => 1, SSL_cert_file => $crt, SSL_key_file => $key)
            or do { logmsg('error', "Web dashboard: cannot use certificate $crt / key $key: "
                                  . IO::Socket::SSL::errstr()); exit 3 };
        $w->{_secure} = 1;
        logmsg('debug', "Web dashboard: certificate $crt, key $key");
    }
    my $srv = IO::Socket::INET->new(LocalAddr => $w->{listen}, LocalPort => $w->{port}, Proto => 'tcp',
                                    Listen => 16, ReuseAddr => 1)
        or do { logmsg('error', "Web dashboard: cannot listen on $w->{listen}:$w->{port}: $@"); exit 3 };
    logmsg('info', "Web dashboard on " . ($ctx ? 'https' : 'http') . "://$w->{listen}:$w->{port}/"
        . (@{ $w->{_allow} } ? " (allowed: $w->{allow})" : '') . (length $w->{user} ? ' with login' : ''));
    # every connection is handled by its own short-lived process, so a slow or idle client
    # (e.g. a browser's unused pre-connection) never holds up the others
    my $sel = IO::Select->new($srv);
    my %kids;                                                # pid -> client address
    my $reap = sub {
        while ((my $k = waitpid(-1, WNOHANG)) > 0) {
            delete $kids{$k};                                # (failed sign-ins: web_fail, a shared file)
        }
    };
    while (1) {
        exit 0 if !$opt{web} && getppid() != $parent;           # the daemon is gone
        $reap->();
        next unless $sel->can_read(2);
        my $c = $srv->accept or next;
        $reap->();
        my $ip = $c->peerhost // '';
        # at most 64 connections at once, and max_per_ip of them from one address: a few slow
        # clients cannot take the whole web server, an office behind one address still has room
        if (keys %kids >= 64) { close $c; logmsg('debug', "web: too many connections, $ip dropped"); next }
        if ((grep { $_ eq $ip } values %kids) >= ($w->{max_per_ip} || 24)) { close $c; logmsg('debug', "web: more than " . ($w->{max_per_ip} || 24) . " connections from $ip, dropped"); next }
        my $pid = fork;
        if (!defined $pid) { web_conn($cfg, $ctx, $c); next }  # cannot fork: handle it here
        if ($pid == 0) {
            close $srv;
            $SIG{TERM} = $SIG{INT} = sub { POSIX::_exit(0) };
            my $rc = web_conn($cfg, $ctx, $c);
            POSIX::_exit($rc);
        }
        $kids{$pid} = $ip;
        close $c;
    }
}

sub web_conn {
    my ($cfg, $ctx, $c) = @_;
    $WEB_RESULT = '';
    # a client that does not take the answer cannot hold this process: sending gives up after 2 min
    eval { setsockopt($c, Socket::SOL_SOCKET(), Socket::SO_SNDTIMEO(), pack('l!l!', 120, 0)) };
    eval {
        if ($ctx) {
            # plain http:// on the https port -> redirect; anything else is a TLS handshake
            my $first = '';
            IO::Select->new($c)->can_read(10) or die "client timeout\n";
            defined recv($c, $first, 1, MSG_PEEK) or die "recv: $!\n";
            die "client closed\n" unless length $first;
            if ($first =~ /^[A-Za-z]$/) {
                web_https_redirect($cfg, $c);
                $c = undef;
            } else {
                my $plain = $c;
                $c = IO::Socket::SSL->start_SSL($plain, SSL_server => 1, SSL_reuse_ctx => $ctx, Timeout => 10)
                    or do { close $plain; die "TLS handshake with " . ($plain->peerhost // '?') . ": "
                                              . IO::Socket::SSL::errstr() . "\n" };
                # a handshake with a Timeout can leave the socket non-blocking: reading the request then
                # gives up at once when it has not fully arrived (the client sees the connection closed)
                $c->blocking(1);
            }
        }
        web_handle($cfg, $c) if $c;
        alarm 0;
        1;
    } or do { alarm 0; logmsg('debug', "web: $@") };
    alarm 0;
    eval { close $c if $c; 1 };
    return $WEB_RESULT eq 'fail' ? 10 : $WEB_RESULT eq 'ok' ? 11 : 0;
}

sub web_https_redirect {
    my ($cfg, $c) = @_;
    local $SIG{ALRM} = sub { die "client timeout\n" };
    alarm 10;
    my ($req, %h, $n, $hb) = (req_line($c));
    while (defined $req && defined(my $l = req_line($c))) {
        last if $l =~ /^\r?\n$/;
        $h{ lc $1 } = $2 if $l =~ /^([\w-]+):\s*(.*?)\s*$/;
        last if ++$n > 100;
    }
    alarm 0;
    my ($path) = ($req // '') =~ m{^\w+\s+(/\S*)};
    $path //= '/';
    my $host = $h{host} // '';
    $host = $c->sockhost . ':' . $c->sockport unless $host =~ /^[\w.\-:\[\]]+$/;
    return web_reply($c, 403, 'text/plain', "Access is not allowed.\n") unless ip_allowed($cfg->{web}, $c->peerhost // '');
    web_reply($c, 301, 'text/plain', "Use https://$host$path\n", "Location: https://$host$path");
}

sub web_reply {
    my ($c, $code, $type, $body, @hdr) = @_;
    my %txt = (200 => 'OK', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 400 => 'Bad Request', 401 => 'Unauthorized',
               403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 413 => 'Payload Too Large',
               500 => 'Internal Server Error');
    $body = encode('UTF-8', $body) if utf8::is_utf8($body);
    print {$c} "HTTP/1.1 $code $txt{$code}\r\n"
        . "Content-Type: $type\r\nContent-Length: " . length($body) . "\r\n"
        . "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n"
        . "X-Frame-Options: DENY\r\nConnection: close\r\n"
        . join('', map { "$_\r\n" } @hdr) . "\r\n" . $body;
}

sub login_page {
    my ($cfg, $msg, $user) = @_;
    my $loc  = h($cfg->{general}{location});
    my $u    = h($user // '');
    my $prod = 'MT-Mon Admin Center';
    my $err  = length $msg ? qq{<p class="err" role="alert">@{[ h($msg) ]}</p>} : '';
    my ($af1, $af2) = length $u ? ('', ' autofocus') : (' autofocus', '');
    my $static = <<'LOGINCSS';
<style>
:root { --bg:#f2f5f8; --ink:#13202c; --ink-2:#4a5a6a; --ink-3:#7a8a99; --line:#d5dde5; --field:#fff; --btn:#17375a; --btn-ink:#fff;
        --bad:#d9364b; --bad-soft:#fdeaec; --focus:#2f80ed; --scope:#07121d; --sig:#2ee59d; --amb:#ffb340; color-scheme: light; }
@media (prefers-color-scheme: dark) { :root { --bg:#0f1720; --ink:#e7eef5; --ink-2:#a6b4c2; --ink-3:#71808f; --line:#2a3848; --field:#152230;
        --btn:#5fa8ff; --btn-ink:#06121e; --bad-soft:#3a1d24; --focus:#7cb8ff; color-scheme: dark; } }
* { box-sizing: border-box; }
html, body { height: 100%; }
body { margin: 0; background: var(--bg); color: var(--ink); display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(360px, 1fr);
       font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
.scope { position: relative; overflow: hidden; background: radial-gradient(900px 600px at 30% 40%, #0f2a3d 0, transparent 70%), var(--scope); color: #dce8f2; }
.scope canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.scope .id { position: absolute; left: clamp(22px, 5vw, 56px); bottom: clamp(22px, 6vh, 56px); right: 22px; }
.scope .site { font-size: clamp(30px, 4.4vw, 56px); font-weight: 750; letter-spacing: -.02em; line-height: 1.05; color: #fff; overflow-wrap: anywhere; }
.scope .prod { margin-top: 10px; font-size: 14px; color: #8fb0c8; display: flex; align-items: center; gap: 8px; }
.scope .prod::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--sig); box-shadow: 0 0 10px var(--sig); }
.side { display: grid; place-items: center; padding: 40px 28px; }
form { width: 100%; max-width: 340px; display: grid; gap: 16px; }
h1 { margin: 0 0 6px; font-size: 26px; font-weight: 700; letter-spacing: -.015em; }
label { display: grid; gap: 6px; font-size: 13px; font-weight: 600; color: var(--ink-2); }
.fld { position: relative; }
input { width: 100%; font: inherit; font-size: 16px; color: var(--ink); background: var(--field); border: 1px solid var(--line); border-radius: 10px;
        padding: 12px 14px; transition: border-color .15s, box-shadow .15s; }
input:hover { border-color: var(--ink-3); }
input:focus { outline: none; border-color: var(--focus); box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 22%, transparent); }
.fld input[type=password], .fld input.shown { padding-right: 48px; }
.eye { position: absolute; right: 6px; top: 50%; transform: translateY(-50%); width: 36px; height: 36px; border: 0; border-radius: 8px;
       background: transparent; color: var(--ink-3); cursor: pointer; display: grid; place-items: center; padding: 0; }
.eye:hover { color: var(--ink); background: color-mix(in srgb, var(--ink) 7%, transparent); }
.eye:focus-visible, .go:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.eye svg { width: 20px; height: 20px; }
.eye .off { display: none; } .eye[aria-pressed=true] .on { display: none; } .eye[aria-pressed=true] .off { display: block; }
.caps { display: none; font-size: 12.5px; font-weight: 500; color: var(--amb); margin-top: -2px; }
@media (prefers-color-scheme: light) { .caps { color: #a35d00; } }
.caps.on { display: block; }
.go { position: relative; font: inherit; font-size: 15.5px; font-weight: 650; border: 0; border-radius: 10px; padding: 13px 16px; cursor: pointer;
      background: var(--btn); color: var(--btn-ink); margin-top: 6px; transition: filter .15s, transform .05s; }
.go:hover { filter: brightness(1.1); } .go:active { transform: translateY(1px); }
.go.busy { color: transparent; pointer-events: none; }
.go.busy::after { content: ""; position: absolute; left: 50%; top: 50%; width: 18px; height: 18px; margin: -9px; border-radius: 50%;
                  border: 2px solid var(--btn-ink); border-right-color: transparent; animation: spin .7s linear infinite; }
@keyframes spin { to { transform: rotate(1turn); } }
.err { margin: 0; padding: 11px 14px; border-radius: 10px; background: var(--bad-soft); color: var(--ink); font-size: 14px;
       border: 1px solid color-mix(in srgb, var(--bad) 35%, transparent); display: flex; gap: 10px; align-items: flex-start; animation: nudge .35s ease-out; }
.err::before { content: "!"; flex: none; width: 20px; height: 20px; border-radius: 50%; background: var(--bad); color: #fff; font-weight: 800; font-size: 13px;
               display: grid; place-items: center; margin-top: 1px; }
@keyframes nudge { 0%, 100% { transform: none; } 25% { transform: translateX(-6px); } 60% { transform: translateX(4px); } }
@media (max-width: 820px) {
  body { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
  .scope { height: 34vh; min-height: 200px; max-height: 300px; }
  .scope .id { bottom: 20px; left: 20px; } .scope .prod { font-size: 13px; margin-top: 6px; }
  .side { place-items: start center; padding: 28px 20px 40px; }
 }
@media (prefers-reduced-motion: reduce) { .err { animation: none; } }
</style>
LOGINCSS
    my $script = <<'LOGINJS';
<script>
(function () {
  var f = document.getElementById("f"), pw = document.getElementById("pw"), eye = document.getElementById("eye"), caps = document.getElementById("caps");
  eye.addEventListener("click", function () { var s = pw.type === "password"; pw.type = s ? "text" : "password"; pw.classList.toggle("shown", s);
    eye.setAttribute("aria-pressed", s); eye.setAttribute("aria-label", s ? "Hide password" : "Show password"); pw.focus(); });
  function ck(e) { if (e.getModifierState) caps.classList.toggle("on", e.getModifierState("CapsLock")); }
  pw.addEventListener("keydown", ck); pw.addEventListener("keyup", ck); pw.addEventListener("blur", function () { caps.classList.remove("on"); });
  f.addEventListener("submit", function () { document.getElementById("go").classList.add("busy"); });
  window.addEventListener("pageshow", function () { document.getElementById("go").classList.remove("busy"); });

  /* the picture: a small network, one per site (seeded from the site name), with traffic moving along the links */
  var cv = document.getElementById("net"), cx = cv.getContext("2d"), seed = 7, name = document.body.getAttribute("data-site") || "";
  for (var i = 0; i < name.length; i++) seed = (seed * 31 + name.charCodeAt(i)) >>> 0;
  function rnd() { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }
  var still = window.matchMedia && matchMedia("(prefers-reduced-motion: reduce)").matches;
  var W, H, D, nodes = [], links = [], pk = [];
  function build() {
    var r = cv.getBoundingClientRect(); D = Math.min(window.devicePixelRatio || 1, 2); W = r.width; H = r.height;
    cv.width = W * D; cv.height = H * D; cx.setTransform(D, 0, 0, D, 0, 0);
    var s0 = seed; nodes = []; links = []; pk = [];
    var wide = W > 600, core = { x: W * (wide ? .5 : .68), y: H * (wide ? .4 : .38), k: 0, r: 7 }; nodes.push(core);
    var nsw = 3 + Math.floor(rnd() * 3), R = Math.min(W, H) * (wide ? .2 : .26);
    function fit(o) { o.x = Math.max(18, Math.min(W - 18, o.x)); o.y = Math.max(18, Math.min(H * (wide ? .72 : .55), o.y)); return o; }
    for (var a = 0; a < nsw; a++) {
      var t = a / nsw * Math.PI * 2 + rnd() * .5, sw = { x: core.x + Math.cos(t) * R * 1.25, y: core.y + Math.sin(t) * R * .9, k: 1, r: 5 }; fit(sw);
      nodes.push(sw); links.push([core, sw]);
      var nap = 2 + Math.floor(rnd() * 4);
      for (var b = 0; b < nap; b++) {
        var u = t + (b - (nap - 1) / 2) * .42, d = R * (.55 + rnd() * .35), ap = { x: sw.x + Math.cos(u) * d * 1.3, y: sw.y + Math.sin(u) * d, k: 2, r: 3.2 }; fit(ap);
        nodes.push(ap); links.push([sw, ap]);
      }
    }
    for (var n = 0; n < 70; n++) nodes.push({ x: rnd() * W, y: rnd() * H, k: 3, r: rnd() * 1.1 + .3, tw: rnd() * 6 });
    for (var p = 0; p < links.length; p++) pk.push({ l: links[p], t: rnd(), v: .12 + rnd() * .25, dir: rnd() < .5 ? 1 : -1, amb: rnd() < .08 });
    seed = s0;
  }
  function draw(ts) {
    var s = (ts || 0) / 1000; cx.clearRect(0, 0, W, H);
    cx.lineWidth = 1;
    for (var i = 0; i < links.length; i++) { var l = links[i]; cx.strokeStyle = "rgba(120,180,220," + (l[0].k ? .16 : .28) + ")";
      cx.beginPath(); cx.moveTo(l[0].x, l[0].y); cx.lineTo(l[1].x, l[1].y); cx.stroke(); }
    for (var j = 0; j < pk.length; j++) { var q = pk[j], t = still ? q.t : (q.t + s * q.v * q.dir) % 1; if (t < 0) t += 1;
      var x = q.l[0].x + (q.l[1].x - q.l[0].x) * t, y = q.l[0].y + (q.l[1].y - q.l[0].y) * t, c = q.amb ? "255,179,64" : "46,229,157";
      var g = cx.createRadialGradient(x, y, 0, x, y, 7); g.addColorStop(0, "rgba(" + c + ",.9)"); g.addColorStop(1, "rgba(" + c + ",0)");
      cx.fillStyle = g; cx.beginPath(); cx.arc(x, y, 7, 0, 7); cx.fill(); }
    for (var k = 0; k < nodes.length; k++) { var o = nodes[k];
      if (o.k === 3) { cx.fillStyle = "rgba(170,205,235," + (still ? .25 : .12 + .18 * (1 + Math.sin(s * .8 + o.tw)) / 2) + ")"; cx.beginPath(); cx.arc(o.x, o.y, o.r, 0, 7); cx.fill(); continue; }
      if (o.k === 0 && !still) { var ph = (s % 3) / 3; cx.strokeStyle = "rgba(46,229,157," + (.45 * (1 - ph)) + ")"; cx.beginPath(); cx.arc(o.x, o.y, o.r + ph * 36, 0, 7); cx.stroke(); }
      cx.fillStyle = o.k === 2 ? "#9fd8ff" : "#e9f6ff"; cx.shadowColor = o.k === 0 ? "#2ee59d" : "rgba(159,216,255,.8)"; cx.shadowBlur = o.k === 0 ? 16 : 8;
      cx.beginPath(); if (o.k === 1) cx.rect(o.x - o.r, o.y - o.r * .7, o.r * 2, o.r * 1.4); else cx.arc(o.x, o.y, o.r, 0, 7); cx.fill(); cx.shadowBlur = 0; }
    if (!still) requestAnimationFrame(draw);
  }
  build(); draw(0);
  var rt; window.addEventListener("resize", function () { clearTimeout(rt); rt = setTimeout(function () { build(); if (still) draw(0); }, 120); });
 })();
</script>
LOGINJS
    return <<"HTML";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Sign in - $loc</title>
$static</head>
<body data-site="$loc">
<aside class="scope" aria-hidden="true">
  <canvas id="net"></canvas>
  <div class="id"><div class="site">$loc</div><div class="prod">$prod</div></div>
</aside>
<main class="side">
  <form id="f" method="post" action="/login" autocomplete="on">
    <h1>Sign in</h1>
    $err
    <label for="un">User name</label>
    <div class="fld" style="margin-top:-10px"><input id="un" name="user" value="$u" autocomplete="username" autocapitalize="none" spellcheck="false" required$af1></div>
    <label for="pw">Password</label>
    <div class="fld" style="margin-top:-10px"><input id="pw" name="password" type="password" autocomplete="current-password" required$af2>
      <button type="button" class="eye" id="eye" aria-label="Show password" aria-pressed="false"><svg class="on" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg><svg class="off" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3l18 18M10.6 5.1A10.4 10.4 0 0 1 12 5c6.4 0 10 7 10 7a17 17 0 0 1-3.2 4.1M6.6 6.6C3.9 8.3 2 12 2 12s3.6 7 10 7c1.8 0 3.4-.5 4.8-1.3M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg></button></div>
    <div class="caps" id="caps" role="status">Caps Lock is on.</div>
    <button type="submit" class="go" id="go">Sign in</button>
  </form>
</main>
$script</body>
</html>
HTML
}

sub req_line {
    my ($c) = @_;
    # read byte by byte up to the line end: a line longer than 8 KB is refused (a client cannot
    # fill the memory with one endless line)
    my ($l, $tls, $tries) = ('', ref($c) =~ /SSL/, 0);
    while (1) {
        my $r = read($c, my $ch, 1);
        if ($r) {
            $l .= $ch;
            return $l if $ch eq "\n";
            die "request line too long\n" if length $l > 8192;
            next;
        }
        last unless $tls;                                   # plain socket: the end
        last if ++$tries > 20;
        last unless $c->pending || IO::Select->new($c)->can_read(5);
    }
    return length $l ? $l : undef;
}

sub ip_allowed {
    my ($w, $ip) = @_;
    return 1 unless @{ $w->{_allow} };
    $ip =~ s/^::ffff://i;
    return 1 if $ip eq '127.0.0.1' || $ip eq '::1';
    return 0 unless $ip =~ /^\d{1,3}(?:\.\d{1,3}){3}$/;
    my $n = unpack('N', pack('C4', split /\./, $ip));
    return scalar grep { ($n & $_->[1]) == $_->[0] } @{ $w->{_allow} };
}

sub parse_cidr {
    my ($c) = @_;
    my ($ip, $len) = $c =~ m{^(\d{1,3}(?:\.\d{1,3}){3})(?:/(\d{1,2}))?$} or return undef;
    $len //= 32;
    return undef if $len > 32 || grep { $_ > 255 } split /\./, $ip;
    my $mask = $len ? (0xFFFFFFFF << (32 - $len)) & 0xFFFFFFFF : 0;
    return [ unpack('N', pack('C4', split /\./, $ip)) & $mask, $mask ];
}

sub web_fail {
    my ($cfg, $op, $key) = @_;
    my $f = web_fail_file($cfg);
    open(my $lk, '>>', "$f.lock") or return 0;
    flock($lk, LOCK_EX);
    my $t = jread($f) || {};
    my $now = time;
    my $e = $t->{$key} || { n => 0 };
    my $left = ($e->{until} // 0) > $now ? $e->{until} - $now : 0;
    if ($op eq 'fail' && !$left) {
        $e->{n}++; $e->{seen} = $now;
        if ($e->{n} >= 5) { $e->{until} = $now + 300; $e->{n} = 0; $left = 300 }
        $t->{$key} = $e;
    }
    elsif ($op eq 'ok') { delete $t->{$key} }
    if ($op ne 'check') {
        delete $t->{$_} for grep { ($t->{$_}{seen} // 0) < $now - 3600 && ($t->{$_}{until} // 0) < $now } keys %$t;
        jwrite($f, $t);
    }
    close $lk;
    return $left;
}

sub const_eq {
    my ($x, $y) = @_;
    return 0 unless defined $x && defined $y && length $x == length $y;
    my $r = 0;
    $r |= ord(substr $x, $_, 1) ^ ord(substr $y, $_, 1) for 0 .. length($x) - 1;
    return $r == 0;
}

sub url_dec { my $v = shift // ''; $v =~ tr/+/ /; $v =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ge; return decode('UTF-8', $v, Encode::FB_DEFAULT) }

sub web_secret {
    my ($cfg) = @_;
    my $f = data_file($cfg->{general}, 'web.secret');
    if (open(my $fh, '<:raw', $f)) { local $/; my $s = <$fh>; close $fh; return $s if length($s // '') >= 32 }
    open(my $r, '<:raw', '/dev/urandom') or die "Cannot read /dev/urandom: $!\n";
    read($r, my $s, 32) == 32 or die "Short read from /dev/urandom\n";
    close $r;
    my $old = umask 077;
    open(my $fh, '>:raw', $f) or die "Cannot write $f: $!\n";
    print {$fh} $s;
    close $fh;
    umask $old;
    return $s;
}

sub session_token {
    my ($cfg, $u, $exp) = @_;
    (my $n = encode_base64(encode('UTF-8', lc $u->{name}), '')) =~ tr{+/=}{-_}d;
    return "$n.$exp." . hmac_sha256_hex(encode('UTF-8', lc($u->{name}) . "|$exp|$u->{role}"), web_secret($cfg) . encode('UTF-8', $u->{secret}));
}

sub session_valid {
    my ($cfg, $tok) = @_;
    return undef unless defined $tok && $tok =~ /^([A-Za-z0-9_-]+)\.(\d+)\.[0-9a-f]{64}$/;
    my ($n64, $exp) = ($1, $2);
    return undef if $exp < time || $exp > time + $cfg->{web}{session_hours} * 3600 + 60;
    (my $b = $n64) =~ tr{-_}{+/};
    my $name = decode('UTF-8', decode_base64($b . '=' x ((4 - length($b) % 4) % 4)), Encode::FB_DEFAULT);
    my $u = $cfg->{web}{_users}{ lc $name } or return undef;
    return const_eq($tok, session_token($cfg, $u, $exp)) ? $u : undef;
}

sub pw_ok {
    my ($secret, $given) = @_;
    $given = encode('UTF-8', $given);
    if ($secret =~ /^\{PBKDF2\}(\d+)\$([A-Za-z0-9+\/]+)\$([A-Za-z0-9+\/]+)$/) {
        my ($it, $salt, $hash) = ($1, decode_base64($2), decode_base64($3));
        return 0 if $it < 1 || $it > 5_000_000;
        return const_eq(pbkdf2_sha256($given, $salt, $it), $hash);
    }
    return const_eq($given, encode('UTF-8', $secret));
}

sub pbkdf2_sha256 {
    my ($pw, $salt, $iter) = @_;
    my $u = hmac_sha256($salt . pack('N', 1), $pw);
    my $t = $u;
    for (2 .. $iter) { $u = hmac_sha256($u, $pw); $t ^= $u }
    return $t;
}

sub hash_password_cli {
    my $tty = -t STDIN;
    my $ask = sub {
        print STDERR $_[0] if $tty;
        system('stty', '-echo') if $tty;
        my $p = <STDIN>;
        system('stty', 'echo') if $tty;
        print STDERR "\n" if $tty;
        die "No password given\n" unless defined $p;
        chomp $p;
        return decode('UTF-8', $p, Encode::FB_DEFAULT);
    };
    my $p = $ask->('Password: ');
    die "Empty password\n" unless length $p;
    if ($tty) { die "The passwords do not match\n" if $ask->('Again: ') ne $p }
    open(my $r, '<:raw', '/dev/urandom') or die "Cannot read /dev/urandom: $!\n";
    read($r, my $salt, 16) == 16 or die "Short read from /dev/urandom\n";
    close $r;
    my $it = 50000;
    my $h = pbkdf2_sha256(encode('UTF-8', $p), $salt, $it);
    my $b = sub { (my $x = encode_base64($_[0], '')) =~ s/=+$//; $x };
    print "{PBKDF2}$it\$" . $b->($salt) . '$' . $b->($h) . "\n";
    print STDERR "Put it in /etc/mtmon-admin-center/center.conf, e.g.:  [web users]  name = <the line above>\n" if $tty;
    return 0;
}

sub random_token {
    my ($bytes) = @_;
    open(my $r, '<:raw', '/dev/urandom') or die "Cannot read /dev/urandom: $!\n";
    read($r, my $b, $bytes) == $bytes or die "Short read from /dev/urandom\n";
    close $r;
    (my $t = encode_base64($b, '')) =~ tr{+/=}{-_}d;
    return $t;
}

sub api_key_user {
    my ($cfg, $key, $peer) = @_;
    my $k = $cfg->{_api_keys}{ sha256_hex($key) } or return undef;
    return undef if @{ $k->{_allow} } && !ip_allowed({ _allow => $k->{_allow} }, $peer);
    return $k;
}

sub new_api_key_cli {
    my ($name) = @_;
    die "Usage: mtmon --new-api-key NAME\n" unless defined $name && $name =~ /^[\w.\-]+$/;
    my $key = 'mtk_' . random_token(32);
    print "API key (shown only now - give it to the app or script):\n\n  $key\n\n";
    print "Add to /etc/mtmon-admin-center/center.conf and run systemctl reload mtmon-admin-center:\n\n  [api keys]\n  $name = {SHA256}" . sha256_hex($key) . "  role=full\n\n";
    print "Use:  curl -k -H 'Authorization: Bearer $key' https://<this server>/api/overview\n";
    return 0;
}

sub send_mail {
    my ($cfg, $subject, $body, $html) = @_;
    return agent_mail(@_) if do { no warnings 'once'; $main::AGENT };      # mtmon --agent: the centre sends it
    my $m  = $cfg->{mail};
    my @to = grep { length } split /\s*[,;]\s*/, $m->{to};
    die "[mail] 'to' is not set\n" unless @to;

    my @dn = qw(Sun Mon Tue Wed Thu Fri Sat);
    my @mn = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
    my @lt = localtime;
    my $date = sprintf('%s, %02d %s %d %s', $dn[$lt[6]], $lt[3], $mn[$lt[4]], $lt[5] + 1900,
                       strftime('%H:%M:%S %z', @lt));
    my $host = hostname();

    my $msg = "From: $m->{from}\n"
            . "To: " . join(', ', @to) . "\n"
            . "Subject: " . encode('MIME-Header', "$m->{subject_prefix} $subject") . "\n"
            . "Date: $date\n"
            . "Message-ID: <mtmon-center." . time . ".$$\@$host>\n"
            . "MIME-Version: 1.0\n"
            . "X-Mailer: mtmon-admin-center $VERSION\n";
    my $shown;   # what --dry-run prints
    if (defined $html) {
        # multipart/alternative: plain text first, HTML last (= preferred by mail clients)
        my $b = 'mtmon-' . md5_hex(time . $$ . rand());
        my $text_part = "--$b\n"
                      . "Content-Type: text/plain; charset=UTF-8\n"
                      . "Content-Transfer-Encoding: 8bit\n\n"
                      . $body . "\n";
        $msg .= "Content-Type: multipart/alternative; boundary=\"$b\"\n\n"
              . "This is a multi-part message in MIME format.\n\n";
        $shown = $msg . $text_part . "--$b\n[HTML part: " . length($html) . " characters, not shown]\n--$b--\n";
        $msg  .= $text_part
               . "--$b\n"
               . "Content-Type: text/html; charset=UTF-8\n"
               . "Content-Transfer-Encoding: quoted-printable\n\n"
               . decode('ASCII', encode_qp(encode('UTF-8', $html), "\n"))   # QP keeps lines < 76 chars
               . "\n--$b--\n";
    } else {
        $msg .= "Content-Type: text/plain; charset=UTF-8\n"
              . "Content-Transfer-Encoding: 8bit\n"
              . "\n" . $body;
        $shown = $msg;
    }
    my $bytes = encode('UTF-8', $msg);

    if ($opt{'dry-run'}) {
        print "----- DRY RUN: mail not sent -----\n$shown\n----- end -----\n";
        return 1;
    }

    if ($m->{method} eq 'sendmail') {
        open(my $sm, '|-', $m->{sendmail}, '-t', '-oi') or die "Cannot run $m->{sendmail}: $!\n";
        print {$sm} $bytes;
        close $sm or die "sendmail returned an error ($?)\n";
        return 1;
    }

    my $sh = $m->{smtp_host};
    my %ssl_opts = (
        SSL_verify_mode   => $m->{ssl_verify} ? 1 : 0,
        SSL_verifycn_name => ($m->{ssl_verify_name} || $sh),
        ($sh =~ /^[\d.:]+$/ ? () : (SSL_hostname => $sh)),    # SNI only for a name, not an IP
    );
    my $tls_err = sub {
        my $e = do { no warnings 'once'; $IO::Socket::SSL::SSL_ERROR } // '';
        $e = "$e" if ref $e;
        my $hint = '';
        if ($e =~ /certificate verify failed|verify|hostname/i) {
            $hint = "\n  Hint: the SMTP server certificate is not trusted or does not match the name '$sh'."
                  . "\n  Set smtp_host exactly as in the certificate (not an IP), or ssl_verify_name = <name in certificate>;"
                  . "\n  for a self-signed certificate use ssl_verify = 0.";
        } elsif ($e =~ /wrong version|unsupported protocol|dh key too small|ee key too small|sslv3|no protocols/i) {
            $hint = "\n  Hint: the server uses an outdated TLS version or a weak key, which OpenSSL 3 on Debian 13 rejects.";
        }
        return ($e || 'unknown TLS error') . $hint;
    };

    my $smtp = Net::SMTP->new($sh,
        Port    => $m->{smtp_port},
        Timeout => 30,
        Hello   => $host,
        ($m->{ssl} ? (SSL => 1, %ssl_opts) : ()),
    ) or die "SMTP connection to $sh:$m->{smtp_port} failed: "
           . ($m->{ssl} ? $tls_err->() : ($@ || $!)) . "\n";

    if ($m->{starttls} && !$m->{ssl}) {
        $smtp->starttls(%ssl_opts) or die "STARTTLS to $sh:$m->{smtp_port} failed: " . $tls_err->() . "\n";
    }
    if ($m->{smtp_user}) {
        $smtp->auth($m->{smtp_user}, $m->{smtp_password})
            or die "SMTP authentication failed: " . ($smtp->message // '') . "\n";
    }
    my ($env_from) = $m->{from} =~ /<([^>]+)>/;
    $env_from //= $m->{from};
    $smtp->mail($env_from) or die "MAIL FROM rejected: " . ($smtp->message // '') . "\n";
    for my $rcpt (@to) {
        my ($a) = $rcpt =~ /<([^>]+)>/;
        $smtp->to($a // $rcpt) or die "RCPT TO $rcpt rejected: " . ($smtp->message // '') . "\n";
    }
    $smtp->data or die "DATA rejected\n";
    $smtp->datasend($bytes);
    $smtp->dataend or die "Server rejected the message: " . ($smtp->message // '') . "\n";
    $smtp->quit;
    return 1;
}

sub data_file { dirname($_[0]{state_file}) . "/$_[1]" }

sub append_jsonl {
    my ($g, $name, @recs) = @_;
    return unless @recs;
    my $f = data_file($g, $name);
    open(my $fh, '>>', $f) or die "Cannot write $f: $!\n";
    binmode $fh;
    print {$fh} JSON::PP->new->utf8->canonical->encode($_), "\n" for @recs;
    close $fh;
    # keep the files small: above 2 MB drop everything older than history_days
    # (not the hourly / daily files - they have their own retention, see hist_trim)
    if ($name !~ /-1[hd]\.jsonl$/ && -s $f > 2_000_000) {
        my $limit = time - ($g->{_history_days} || 30) * 86400;
        my @keep = grep { my $r = eval { JSON::PP->new->utf8->decode($_) }; $r && ($r->{t} // 0) >= $limit } read_lines($f);
        my ($tfh, $tmp) = tempfile('.trim-XXXXXX', DIR => dirname($f));
        binmode $tfh;
        print {$tfh} @keep;
        close $tfh;
        rename $tmp, $f;
    }
}

sub read_lines {
    my ($f) = @_;
    open(my $fh, '<:raw', $f) or return ();
    my @l = <$fh>;
    close $fh;
    return @l;
}

sub read_jsonl {
    my ($f, $since, $until) = @_;
    my $js = json_fast();
    $since //= 0;
    my @r;
    for my $l (read_lines($f)) {
        # records are written with sorted keys, "t" is the time: skip lines outside the range unparsed
        if ($l =~ /"t":\s*(\d+)\s*[,}]/) { next if $1 < $since || (defined $until && $1 >= $until) }
        my $x = eval { $js->decode($l) } or next;
        push @r, $x if ($x->{t} // 0) >= $since && (!defined $until || ($x->{t} // 0) < $until);
    }
    return @r;
}

sub read_jsonl_first {
    my ($f) = @_;
    open(my $fh, '<:raw', $f) or return undef;
    while (my $l = <$fh>) { my $r = eval { JSON::PP->new->utf8->decode($l) }; if ($r) { close $fh; return $r } }
    close $fh;
    return undef;
}

sub last_t {
    my ($f) = @_;
    open(my $fh, '<:raw', $f) or return undef;
    my $size = -s $fh;
    seek($fh, $size > 8192 ? $size - 8192 : 0, 0);
    local $/;
    my $tail = <$fh> // '';
    close $fh;
    for my $l (reverse split /\n/, $tail) {
        my $r = eval { JSON::PP->new->utf8->decode($l) } or next;
        return $r->{t} if defined $r->{t};
    }
    return undef;
}

sub jread {
    my ($f) = @_;
    open(my $fh, '<:raw', $f) or return undef;
    local $/;
    my $d = eval { JSON::PP->new->utf8->decode(<$fh> // '') };
    close $fh;
    return $d;
}

sub jwrite {
    my ($f, $d) = @_;
    my ($fh, $tmp) = tempfile('.j-XXXXXX', DIR => dirname($f));
    binmode $fh;
    print {$fh} JSON::PP->new->utf8->canonical->encode($d);
    close $fh or die "Writing $f failed: $!\n";
    chmod 0640, $tmp;
    rename($tmp, $f) or die "Cannot rename $tmp to $f: $!\n";
}

sub local_floor {
    my ($t, $unit) = @_;
    my @l = localtime $t;
    return $t - $l[0] - 60 * $l[1] if $unit eq 'h';
    return POSIX::mktime(0, 0, 0, $l[3], $l[4], $l[5], 0, 0, -1);
}

sub next_bucket {
    my ($t, $unit) = @_;
    return local_floor($t + 3600 + 60, 'h') if $unit eq 'h';
    my @l = localtime($t + 3 * 3600);                      # safe across DST changes
    return POSIX::mktime(0, 0, 0, $l[3] + 1, $l[4], $l[5], 0, 0, -1);
}

sub hist_norm {
    my ($kind, $r) = @_;
    return $r if $r->{n};                                  # already aggregated
    if ($kind =~ /^(?:clients|devstats)/) {                # clients (per SSID), clientsap (per access point), devstats (per device)
        # tot = all clients of a controller (and _all = of every controller) at that check:
        # [average, peak, time of the peak] - the peak of the sum, not the sum of the SSID peaks
        my %c = map { my $o = $r->{c}{$_}; ($_ => { map { ($_ => [ $o->{$_}, $o->{$_} ]) } keys %$o }) } keys %{ $r->{c} || {} };
        my %tot = map { my $n = 0; $n += $_ for values %{ $r->{c}{$_} }; ($_ => [ $n, $n, $r->{t} ]) } keys %c;
        if (%tot) { my $a = 0; $a += $_->[0] for values %tot; $tot{_all} = [ $a, $a, $r->{t} ] }
        return { t => $r->{t}, n => { map { ($_ => 1) } keys %tot }, c => \%c, tot => \%tot };
    }
    my %c = %{ $r->{c} || {} };
    return { t => $r->{t}, n => { (map { ($_ => 1) } keys %c), ($r->{s} ? (_s => 1) : ()) }, c => \%c,
             cm => { map { ($_ => [ @{ $c{$_} }[0, 1] ]) } keys %c }, ($r->{s} ? (s => $r->{s}, sm => [ @{ $r->{s} } ]) : ()) };
}

sub hist_merge {
    my ($kind, $t, @recs) = @_;
    my (%N, %S, %M);
    my $rd = sub { 0 + sprintf('%.2f', $_[0]) };
    if ($kind =~ /^(?:clients|devstats)/) {
        my (%TS, %TM, %TT);
        for my $r (@recs) {
            for my $k (keys %{ $r->{c} }) {
                my $n = $r->{n}{$k} || 1;
                $N{$k} += $n;
                for my $s (keys %{ $r->{c}{$k} }) {
                    my ($avg, $pk) = @{ $r->{c}{$k}{$s} };
                    $S{$k}{$s} += $avg * $n;
                    $M{$k}{$s} = $pk if !defined $M{$k}{$s} || $pk > $M{$k}{$s};
                }
            }
            $N{_all} += $r->{n}{_all} || 1 if $r->{tot} && $r->{tot}{_all};
            for my $k (keys %{ $r->{tot} || {} }) {
                my ($avg, $pk, $pt) = @{ $r->{tot}{$k} };
                $TS{$k} += $avg * ($r->{n}{$k} || 1);
                if (!defined $TM{$k} || $pk > $TM{$k}) { $TM{$k} = $pk; $TT{$k} = $pt }
            }
        }
        return { t => $t, n => \%N,
                 c   => { map { my $k = $_; ($k => { map { ($_ => [ $rd->($S{$k}{$_} / $N{$k}), $M{$k}{$_} ]) } keys %{ $S{$k} } }) } grep { $_ ne '_all' } keys %N },
                 tot => { map { ($_ => [ $rd->($TS{$_} / ($N{$_} || 1)), $TM{$_}, $TT{$_} ]) } keys %TS } };
    }
    my (%C, %CM, @s, @sm, $ns);
    for my $r (@recs) {
        for my $k (keys %{ $r->{c} || {} }) {
            my $n = $r->{n}{$k} || 1;
            $N{$k} += $n;
            $C{$k}[$_] += $r->{c}{$k}[$_] * $n for 0 .. 2;
            my $m = $r->{cm}{$k} || [ @{ $r->{c}{$k} }[0, 1] ];
            $CM{$k}[0] = $m->[0] if !defined $CM{$k}[0] || $m->[0] < $CM{$k}[0];
            $CM{$k}[1] = $m->[1] if !defined $CM{$k}[1] || $m->[1] > $CM{$k}[1];
        }
        if ($r->{s}) {
            my $n = $r->{n}{_s} || 1;
            $ns += $n;
            $s[$_] += $r->{s}[$_] * $n for 0, 1;
            my $m = $r->{sm} || $r->{s};
            $sm[0] = $m->[0] if !defined $sm[0] || $m->[0] < $sm[0];
            $sm[1] = $m->[1] if !defined $sm[1] || $m->[1] > $sm[1];
        }
    }
    return { t => $t, n => { %N, ($ns ? (_s => $ns) : ()) },
             c  => { map { my $k = $_; ($k => [ map { $rd->($C{$k}[$_] / $N{$k}) } 0 .. 2 ]) } keys %N },
             cm => \%CM, ($ns ? (s => [ map { $rd->($s[$_] / $ns) } 0, 1 ], sm => \@sm) : ()) };
}

sub hist_rollup {
    my ($g, $kind, $now) = @_;
    for my $st ([ 'h', "$kind.jsonl", "$kind-1h.jsonl" ], [ 'd', "$kind-1h.jsonl", "$kind-1d.jsonl" ]) {
        my ($unit, $src, $dst) = @$st;
        my $cur = local_floor($now, $unit);                 # the running hour/day is not complete yet
        my $last = last_t(data_file($g, $dst));
        next if defined $last && next_bucket($last, $unit) >= $cur;
        my $from = defined $last ? next_bucket($last, $unit) : 0;
        my %b;
        for my $r (read_jsonl(data_file($g, $src), $from)) {
            next if $r->{t} >= $cur;
            push @{ $b{ local_floor($r->{t}, $unit) } }, hist_norm($kind, $r);
        }
        next unless %b;
        append_jsonl($g, $dst, map { hist_merge($kind, $_, @{ $b{$_} }) } sort { $a <=> $b } keys %b);
    }
}

sub hist_trim {
    my ($g, $file, $days, $force) = @_;
    my $f = data_file($g, $file);
    return unless $days && -e $f;
    return unless $force || time - ($TRIMMED{$f} // 0) > 86400;
    $TRIMMED{$f} = time;
    my $limit = time - $days * 86400;
    my @all = read_lines($f);
    my @keep = grep { my $r = eval { JSON::PP->new->utf8->decode($_) }; $r && ($r->{t} // 0) >= $limit } @all;
    return if @keep == @all;
    my ($tfh, $tmp) = tempfile('.trim-XXXXXX', DIR => dirname($f));
    binmode $tfh;
    print {$tfh} @keep;
    close $tfh;
    rename $tmp, $f;
}

sub hist_maintain {
    my ($g, $kind, $now) = @_;
    hist_upgrade_clients($g) if $kind eq 'clients';
    hist_rollup($g, $kind, $now);
    hist_trim($g, "$kind.jsonl", $g->{_history_days} || 30);
    hist_trim($g, "$kind-1h.jsonl", $g->{_history_hourly_days} || 400);
}

sub hist_upgrade_clients {
    my ($g) = @_;
    return if $CLIENTS_CHECKED++;
    my $h = data_file($g, 'clients-1h.jsonl');
    my $first = read_jsonl_first($h) or return;
    return if $first->{tot};
    my $raw = read_jsonl_first(data_file($g, 'clients.jsonl'));
    if ($raw && $raw->{t} <= $first->{t} + 3600) {
        unlink $h, data_file($g, 'clients-1d.jsonl');
        logmsg('info', "Wi-Fi client history: hourly and daily files rebuilt with the peak of all clients");
    }
}

sub hist_range {
    my ($cfg, $kind, $from, $to, $max) = @_;
    my $g = $cfg->{general};
    my $now = time;
    my $step0 = ($to - $from) / $max;
    my @tiers = (
        [ 'raw', $g->{interval},  $now - ($g->{_history_days} || 30) * 86400,         "$kind.jsonl",    undef ],
        [ 'hour', 3600,           $now - ($g->{_history_hourly_days} || 400) * 86400, "$kind-1h.jsonl", 'h' ],
        [ 'day', 86400,           0,                                                  "$kind-1d.jsonl", 'd' ],
    );
    my @cover = grep { $_->[2] <= $from + 3600 } @tiers;
    @cover = ($tiers[-1]) unless @cover;
    my ($tier) = reverse grep { $_->[1] <= $step0 } @cover;
    $tier //= $cover[0];
    my @recs = map { hist_norm($kind, $_) } read_jsonl(data_file($g, $tier->[3]), $from, $to);
    # newer records that are not rolled up into this step yet
    if ($tier->[0] ne 'raw') {
        my $i = (grep { $tiers[$_] == $tier } 0 .. $#tiers)[0];
        my $edge = @recs ? next_bucket($recs[-1]{t}, $tier->[4]) : $from;
        for my $fine (reverse @tiers[0 .. $i - 1]) {
            my @more = read_jsonl(data_file($g, $fine->[3]), $edge, $to);
            next unless @more;
            push @recs, map { hist_norm($kind, $_) } @more;
            $edge = $fine->[4] ? next_bucket($more[-1]{t}, $fine->[4]) : $more[-1]{t} + 1;
        }
    }
    my $step = $tier->[1];
    if (@recs > $max) {
        $step = int(($to - $from) / $max) + 1;
        my %b;
        push @{ $b{ $from + int(($_->{t} - $from) / $step) * $step } }, $_ for @recs;
        @recs = map { hist_merge($kind, $_, @{ $b{$_} }) } sort { $a <=> $b } keys %b;
    }
    delete $_->{n} for @recs;
    my $first;
    for my $tt (reverse @tiers) { my $r = (read_jsonl_first(data_file($g, $tt->[3]))); if ($r) { $first = $r->{t}; last } }
    return { from => $from + 0, to => $to + 0, step => $step + 0, tier => $tier->[0], first => $first, points => \@recs };
}

sub client_peaks {
    my ($cfg) = @_;
    my $now = time;
    my @l = localtime $now;
    my $mid = POSIX::mktime(0, 0, 0, @l[3, 4, 5], 0, 0, -1);
    my $wday = ($l[6] + 6) % 7;                           # Monday = 0
    my @per = (
        [ today => 'Today',      $mid,                                                  $now ],
        [ yday  => 'Yesterday',  POSIX::mktime(0, 0, 0, $l[3] - 1, @l[4, 5], 0, 0, -1), $mid ],
        [ week  => 'This week',  POSIX::mktime(0, 0, 0, $l[3] - $wday, @l[4, 5], 0, 0, -1), $now ],
        [ month => 'This month', POSIX::mktime(0, 0, 0, 1, @l[4, 5], 0, 0, -1),           $now ],
        [ year  => 'This year',  POSIX::mktime(0, 0, 0, 1, 0, $l[5], 0, 0, -1),           $now ],
        [ all   => 'All time',   0,                                                     $now ],
    );
    my %pk;
    for my $p (@per) {
        my $h = hist_range($cfg, 'clients', $p->[2], $p->[3] + 1, 1e9);
        for my $rec (@{ $h->{points} }) {
            for my $k (keys %{ $rec->{tot} || {} }) {
                my ($avg, $n, $t) = @{ $rec->{tot}{$k} };
                $pk{$k}{ $p->[0] } = [ $n + 0, $t + 0 ] if !$pk{$k}{ $p->[0] } || $n > $pk{$k}{ $p->[0] }[0];
            }
        }
    }
    return { periods => [ map { { key => $_->[0], label => $_->[1], from => $_->[2] + 0, to => $_->[3] + 0 } } @per ], peaks => \%pk };
}

sub client_report {
    my ($cfg, $from, $to, $scope, $noprev, $ifmap, $want_aps) = @_;
    $ifmap ||= {};
    $scope //= '';
    my $key = length $scope ? $scope : '_all';
    my $g = $cfg->{general};
    my $hours = ($to - $from) / 3600;
    # hourly steps (finest that still covers the start), never finer
    # the period before (only its totals): daily steps are enough when it is a week or longer
    # $noprev: 0 = with the period before, 1 = only totals (that period itself), 2 = all details, no period before
    my $max = ($noprev // 0) == 1 && $hours >= 7 * 24 ? $hours / 24 : $hours > 1 ? $hours : 1;
    my $h  = hist_range($cfg, 'clients', $from, $to, $max);
    my $ha = $want_aps ? hist_range($cfg, 'clientsap', $from, $to, $max) : { points => [], step => $h->{step} };
    my $step = $h->{step} < 3600 ? 3600 : $h->{step};
    my $rebucket = sub {             # raw points (only for short periods) -> hours
        my ($kind, $pts) = @_;
        return $pts unless @$pts && $h->{step} < 3600;
        my %b;
        push @{ $b{ local_floor($_->{t}, 'h') } }, $_ for @$pts;
        return [ map { my $r = hist_merge($kind, $_, @{ $b{$_} }); delete $r->{n}; $r } sort { $a <=> $b } keys %b ];
    };
    my $pts  = $rebucket->('clients', $h->{points});
    my $apts = $rebucket->('clientsap', $ha->{points});
    my @ctls = do { my %s; $s{$_}++ for map { keys %{ $_->{c} || {} } } @$pts; sort keys %s };

    my (@series, %ss, %day, %mon, @heat, @heatn, $pk, $sum, $n);
    for my $p (@$pts) {
        my $tot = ($p->{tot} || {})->{$key};
        if (!$tot && $key eq '_all' && %{ $p->{c} || {} }) {           # very old files without totals
            my $a = 0; for my $o (values %{ $p->{c} }) { $a += $_->[0] for values %$o }
            $tot = [ $a, $a, $p->{t} ];
        }
        next unless $tot;
        my ($avg, $peak, $pt) = ($tot->[0] + 0, $tot->[1] + 0, ($tot->[2] // $p->{t}) + 0);
        push @series, [ $p->{t} + 0, $avg, $peak ];
        $sum += $avg; $n++;
        $pk = [ $peak, $pt ] if !$pk || $peak > $pk->[0];
        my @l = localtime $p->{t};
        my $d = POSIX::mktime(0, 0, 0, @l[3, 4, 5], 0, 0, -1);
        my $m = POSIX::mktime(0, 0, 0, 1, @l[4, 5], 0, 0, -1);
        for my $b ([ \%day, $d ], [ \%mon, $m ]) {
            my $e = $b->[0]{ $b->[1] } ||= [ 0, 0, 0, 0 ];             # sum avg, count, peak, peak time
            $e->[0] += $avg; $e->[1]++;
            @$e[2, 3] = ($peak, $pt) if $peak > $e->[2] || !$e->[3];
        }
        if ($step <= 3600) {
            my $wd = ($l[6] + 6) % 7;                                   # Monday = 0
            $heat[$wd][ $l[2] ] += $avg; $heatn[$wd][ $l[2] ]++;
        }
        # SSIDs: all controllers of the scope, same names added up
        my %o;
        for my $k (length $scope ? ($scope) : keys %{ $p->{c} || {} }) {
            my $c = $p->{c}{$k} or next;
            for my $s (keys %$c) { $o{$s}[0] += $c->{$s}[0]; $o{$s}[1] += $c->{$s}[1] }
        }
        for my $s (keys %o) {
            my $e = $ss{$s} ||= { name => $s, sum => 0, peak => 0, peak_t => 0 };
            $e->{sum} += $o{$s}[0];
            @$e{qw(peak peak_t)} = ($o{$s}[1] + 0, $p->{t} + 0) if $o{$s}[1] > $e->{peak};
        }
    }
    my $sh = sub {             # finish a {name => {sum, peak}} map: average over the hours with data, share
        my ($m, $cnt) = @_;
        $cnt //= $n;
        my $all = 0; $all += $_->{sum} for values %$m;
        return [ sort { $b->{avg} <=> $a->{avg} || $b->{peak} <=> $a->{peak} || $a->{name} cmp $b->{name} }
                 map { my $e = $_; my $sum = delete $e->{sum};
                       +{ %$e, avg => 0 + sprintf('%.2f', $cnt ? $sum / $cnt : 0), share => 0 + sprintf('%.4f', $all ? $sum / $all : 0) } } values %$m ];
    };
    # access points (per controller; names can repeat on different controllers)
    my (%ap, $an);
    for my $p (@$apts) {
        my $any;
        for my $k (length $scope ? ($scope) : keys %{ $p->{c} || {} }) {
            my $c = $p->{c}{$k} or next;
            $any = 1;
            # history written with CAPsMAN interface names: the CAP they belong to (radios / SSIDs of one AP added up)
            my %one;
            for my $a (keys %$c) {
                my $nm = ($ifmap->{$k} || {})->{$a} // $a;
                $one{$nm}[0] += $c->{$a}[0];
                $one{$nm}[1] += $c->{$a}[1];
            }
            for my $a (keys %one) {
                my $e = $ap{"$k\0$a"} ||= { name => $a, ctl => $k, sum => 0, peak => 0, peak_t => 0 };
                $e->{sum} += $one{$a}[0];
                @$e{qw(peak peak_t)} = ($one{$a}[1] + 0, $p->{t} + 0) if $one{$a}[1] > $e->{peak};
            }
        }
        $an++ if $any;
    }
    my $aps = $sh->(\%ap, $an);
    # controllers (only for all of them)
    my %cl;
    if (!length $scope) {
        for my $p (@$pts) {
            for my $k (keys %{ $p->{tot} || {} }) {
                next if $k eq '_all';
                my $t = $p->{tot}{$k};
                my $e = $cl{$k} ||= { name => $k, sum => 0, peak => 0, peak_t => 0 };
                $e->{sum} += $t->[0];
                @$e{qw(peak peak_t)} = ($t->[1] + 0, ($t->[2] // $p->{t}) + 0) if $t->[1] > $e->{peak};
            }
        }
    }
    my $fin = sub { my ($m) = @_; [ map { [ $_ + 0, 0 + sprintf('%.2f', $m->{$_}[0] / $m->{$_}[1]), $m->{$_}[2] + 0, $m->{$_}[3] + 0 ] } sort { $a <=> $b } keys %$m ] };
    my $r = {
        from => $from + 0, to => $to + 0, step => $step + 0, tier => $h->{tier}, first => $h->{first},
        scope => $scope, controllers => \@ctls,
        hours => scalar(@series), hours_total => int(($to - $from) / $step + .5),
        peak => $pk, avg => ($n ? 0 + sprintf('%.2f', $sum / $n) : undef),
        client_hours => 0 + sprintf('%.1f', ($sum // 0) * $step / 3600),
        series => \@series, days => $fin->(\%day), months => $fin->(\%mon),
        heat => ($step <= 3600 && $n ? [ map { my $d = $_; [ map { $heatn[$d][$_] ? 0 + sprintf('%.2f', $heat[$d][$_] / $heatn[$d][$_]) : undef } 0 .. 23 ] } 0 .. 6 ] : undef),
        heat_n => ($step <= 3600 && $n ? [ map { my $d = $_; [ map { $heatn[$d][$_] // 0 } 0 .. 23 ] } 0 .. 6 ] : undef),
        ssids => $sh->(\%ss), aps => $aps, ap_hours => $an // 0,
        ctl => (length $scope ? [] : $sh->(\%cl)),
    };
    # the period before, as long as this one (a month before a month, a year before a year)
    if (!$noprev) {
        my ($pf, $pt) = report_prev($from, $to);
        my $p = client_report($cfg, $pf, $pt, $scope, 1, $ifmap, 0);
        $r->{prev} = { from => $pf + 0, to => $pt + 0, avg => $p->{avg}, peak => $p->{peak}, client_hours => $p->{client_hours},
                       hours => $p->{hours}, hours_total => $p->{hours_total} };
    }
    $r->{series} = [] if $to - $from > 62 * 86400;       # long periods: days / months are enough for the page
    return $r;
}

sub client_report_cached {
    my ($cfg, $from, $to, $scope, $ifmap, $want_aps, $noprev) = @_;
    $noprev //= 0;
    my $g = $cfg->{general};
    my $over = $to <= time - 2 * 3600;
    require Digest::MD5;
    my $dir = data_file($g, 'report-cache');
    my $key = Digest::MD5::md5_hex(JSON::PP->new->canonical->encode([ 2, $from + 0, $to + 0, $scope // '', $want_aps ? 1 : 0, $noprev, $ifmap || {} ]));
    my $f = "$dir/$key.json";
    if ($over && -r $f) { my $r = jread($f); return $r if $r && $r->{from} }
    my $r;
    my @l = localtime $from;
    my $m1 = POSIX::mktime(0, 0, 0, 1, $l[4] + 1, $l[5], 0, 0, -1);           # start of the next month
    if ($to - $from > 45 * 86400 && $m1 < $to) {
        # long periods (a year): put together from months, each of them kept once it is over
        my @parts;
        for (my ($a, $i) = ($from, 0); $a < $to && $i < 60; $i++) {
            my @m = localtime $a;
            my $b = POSIX::mktime(0, 0, 0, 1, $m[4] + 1, $m[5], 0, 0, -1);
            $b = $to if $b > $to;
            push @parts, client_report_cached($cfg, $a, $b, $scope, $ifmap, $want_aps, 2);
            $a = $b;
        }
        $r = client_report_merge($from, $to, @parts);
        if ($noprev != 2) {
            my ($pf, $pt) = report_prev($from, $to);
            my $p = client_report($cfg, $pf, $pt, $scope, 1, $ifmap, 0);
            $r->{prev} = { from => $pf + 0, to => $pt + 0, avg => $p->{avg}, peak => $p->{peak}, client_hours => $p->{client_hours},
                           hours => $p->{hours}, hours_total => $p->{hours_total} };
        }
    } else {
        $r = client_report($cfg, $from, $to, $scope, $noprev, $ifmap, $want_aps);
    }
    return $r unless $over;
    if (-d $dir || mkdir $dir, 0750) {
        jwrite($f, $r);
        my @all = sort { (stat $a)[9] <=> (stat $b)[9] } glob("$dir/*.json");
        unlink @all[0 .. $#all - 300] if @all > 300;
    }
    return $r;
}

sub client_report_merge {
    my ($from, $to, @p) = @_;
    @p = grep { $_ } @p;
    my ($hours, $tot, $sum, $ch, $pk, $first, $an) = (0, 0, 0, 0, undef, undef, 0);
    my (@days, @months, @series, @hs, @hn, %ss, %ap, %cl, %ctls);
    for my $r (@p) {
        my $n = $r->{hours} || 0;
        $hours += $n; $tot += $r->{hours_total} || 0; $ch += $r->{client_hours} || 0;
        $sum += ($r->{avg} // 0) * $n;
        $pk = $r->{peak} if $r->{peak} && (!$pk || $r->{peak}[0] > $pk->[0]);
        $first = $r->{first} if defined $r->{first} && (!defined $first || $r->{first} < $first);
        push @days, @{ $r->{days} || [] };
        push @series, @{ $r->{series} || [] };
        $ctls{$_} = 1 for @{ $r->{controllers} || [] };
        # a month that is split (the start of a custom period) adds up into one month row
        for my $m (@{ $r->{months} || [] }) {
            if (@months && $months[-1][0] == $m->[0]) {
                my $o = $months[-1];
                my ($n0, $n1) = ($o->[4] || 1, $n || 1);
                $o->[1] = 0 + sprintf('%.2f', ($o->[1] * $n0 + $m->[1] * $n1) / ($n0 + $n1));
                @$o[2, 3] = @$m[2, 3] if $m->[2] > $o->[2];
                $o->[4] = $n0 + $n1;
            } else { push @months, [ @$m, $n ] }
        }
        if ($r->{heat} && $r->{heat_n}) {
            for my $d (0 .. 6) { for my $h (0 .. 23) {
                my $c = $r->{heat_n}[$d][$h] or next;
                $hs[$d][$h] += $r->{heat}[$d][$h] * $c; $hn[$d][$h] += $c;
            } }
        }
        my $acc = sub { my ($m, $list, $w, $kf) = @_;
            for my $x (@{ $list || [] }) {
                my $k = $kf ? $kf->($x) : $x->{name};
                my $e = $m->{$k} ||= { %$x, sum => 0, peak => 0, peak_t => 0 };
                $e->{sum} += $x->{avg} * $w;
                @$e{qw(peak peak_t)} = @$x{qw(peak peak_t)} if $x->{peak} > $e->{peak};
            } };
        $acc->(\%ss, $r->{ssids}, $n);
        $acc->(\%cl, $r->{ctl}, $n);
        $acc->(\%ap, $r->{aps}, $r->{ap_hours} || 0, sub { ($_[0]{ctl} // '') . "\0" . $_[0]{name} });
        $an += $r->{ap_hours} || 0;
    }
    my $fin = sub { my ($m, $w) = @_;
        my $all = 0; $all += $_->{sum} for values %$m;
        [ sort { $b->{avg} <=> $a->{avg} || $b->{peak} <=> $a->{peak} || $a->{name} cmp $b->{name} }
          map { my $e = { %$_ }; my $s = delete $e->{sum};
                +{ %$e, avg => 0 + sprintf('%.2f', $w ? $s / $w : 0), share => 0 + sprintf('%.4f', $all ? $s / $all : 0) } } values %$m ] };
    $#$_ = 3 for @months;
    return {
        from => $from + 0, to => $to + 0, step => 3600, tier => ($p[0] || {})->{tier}, first => $first, scope => ($p[0] || {})->{scope} // '',
        controllers => [ sort keys %ctls ], hours => $hours, hours_total => $tot,
        peak => $pk, avg => ($hours ? 0 + sprintf('%.2f', $sum / $hours) : undef), client_hours => 0 + sprintf('%.1f', $ch),
        series => ($to - $from > 62 * 86400 ? [] : \@series), days => \@days, months => \@months,
        heat => (@hn ? [ map { my $d = $_; [ map { $hn[$d][$_] ? 0 + sprintf('%.2f', $hs[$d][$_] / $hn[$d][$_]) : undef } 0 .. 23 ] } 0 .. 6 ] : undef),
        heat_n => (@hn ? [ map { my $d = $_; [ map { $hn[$d][$_] // 0 } 0 .. 23 ] } 0 .. 6 ] : undef),
        ssids => $fin->(\%ss, $hours), aps => $fin->(\%ap, $an), ap_hours => $an, ctl => $fin->(\%cl, $hours),
    };
}

sub device_report {
    my ($g, $from, $to, $status, $noprev) = @_;
    $status ||= {};
    my $secs = $to - $from;
    # every known device, also those without an outage (100 %)
    my (@list, %seen);
    for my $c (@{ $status->{controllers} || [] }) {
        push @list, { kind => 'ctl', key => "ctl|$c->{name}", name => $c->{heading} || $c->{name}, where => $c->{label} // '', ip => $c->{host} // '' };
        for my $a (@{ $c->{aps} || [] }) {
            push @list, { kind => 'ap', key => "ap|$c->{name}|" . ($a->{mac} || $a->{identity} // ''), name => $a->{identity} || $a->{mac} || '?',
                          where => $c->{heading} || $c->{name}, ip => $a->{ip} // '' };
        }
    }
    for my $d (@{ ($status->{devices} || {})->{items} || [] }) {
        push @list, { kind => 'dev', key => "dev|$d->{host}", name => $d->{desc} || $d->{host}, where => '', ip => $d->{host} };
    }
    local $g->{_known} = { map { ($_->{key} => 1) } @list } if @list;
    my $ps = period_stats($g, $from, $to);
    my %it = map { ($_->{key} => $_) } @{ $ps->{items} || [] };
    my %bykey;
    my $tnow = $to < time ? $to : time;             # an outage still going on ends now, not at the end of the period
    for my $o (@{ $ps->{outages} || [] }) { push @{ $bykey{ $o->{key} } }, [ $o->{start} < $from ? $from : $o->{start} + 0, ($o->{end} // $tnow) > $tnow ? $tnow : ($o->{end} // $tnow) + 0 ] }
    my @devices;
    for my $d (@list) {
        next if $seen{ $d->{key} }++;
        my $i = delete $it{ $d->{key} } || {};
        push @devices, { %$d, down => ($i->{down} // 0) + 0, n => ($i->{n} // 0) + 0, maint_down => ($i->{maint_down} // 0) + 0,
                         avail => 0 + sprintf('%.3f', 100 * (1 - ($i->{down} // 0) / ($secs || 1))) };
    }
    # devices that had outages but are gone from the configuration now
    for my $i (grep { $_->{kind} ne 'site' } values %it) {
        push @devices, { kind => $i->{kind}, key => $i->{key}, name => $i->{name}, where => $i->{where} // '', ip => $i->{ip} // '', gone => 1,
                         down => $i->{down} + 0, n => $i->{n} + 0, maint_down => ($i->{maint_down} // 0) + 0,
                         avail => 0 + sprintf('%.3f', 100 * (1 - $i->{down} / ($secs || 1))) };
    }
    @devices = sort { $a->{avail} <=> $b->{avail} || $b->{n} <=> $a->{n} || $a->{kind} cmp $b->{kind} || lc $a->{name} cmp lc $b->{name} } @devices;
    my %k = (ctl => 0, ap => 0, dev => 0);
    $k{ $_->{kind} }++ for grep { !$_->{gone} } @devices;
    my ($down, $long) = (0, undef);
    for my $o (@{ $ps->{outages} || [] }) { $down += $o->{dur}; $long = $o if !$long || $o->{dur} > $long->{dur} }
    # availability per day from the history (devices answering, access points online, controllers reachable)
    my $h = hist_range({ general => $g }, 'history', $from, $to, ($secs / 3600 > 1 ? $secs / 3600 : 1));
    my %day;
    for my $p (@{ $h->{points} }) {
        my @l = localtime $p->{t};
        my $e = $day{ POSIX::mktime(0, 0, 0, @l[3, 4, 5], 0, 0, -1) } ||= [ (0) x 6 ];
        for my $c (values %{ $p->{c} || {} }) { $e->[0] += $c->[0] // 0; $e->[1] += ($c->[0] // 0) + ($c->[1] // 0); $e->[2] += $c->[2] // 1; $e->[3]++ }
        if ($p->{s}) { $e->[4] += $p->{s}[0] // 0; $e->[5] += ($p->{s}[0] // 0) + ($p->{s}[1] // 0) }
    }
    my $pc = sub { $_[1] ? 0 + sprintf('%.3f', 100 * $_[0] / $_[1]) : undef };
    my @days = map { my $e = $day{$_}; [ $_ + 0, $pc->(@$e[4, 5]), $pc->(@$e[0, 1]), $pc->(@$e[2, 3]) ] } sort { $a <=> $b } keys %day;
    # switch statistics (devstats, since mtmon 12.0.0)
    my $sh = hist_range({ general => $g }, 'devstats', $from, $to, ($secs / 3600 > 1 ? $secs / 3600 : 1));
    my %sw;
    my %names = map { ($_->{host} => ($_->{desc} || $_->{host})) } @{ ($status->{devices} || {})->{items} || [] };
    for my $p (@{ $sh->{points} }) {
        for my $host (keys %{ $p->{c} || {} }) {
            my $m = $p->{c}{$host};
            my $cnt = ref $p->{n} eq 'HASH' ? ($p->{n}{$host} // 1) : 1;
            my $e = $sw{$host} ||= { host => $host, name => $names{$host} // $host, m => {}, hours => 0 };
            $e->{hours}++;
            for my $k (keys %$m) {
                my ($avg, $pk) = ref $m->{$k} ? @{ $m->{$k} } : ($m->{$k}, $m->{$k});
                my $x = $e->{m}{$k} ||= { sum => 0, n => 0, peak => undef, peak_t => 0, tot => 0 };
                $x->{sum} += $avg; $x->{n}++; $x->{tot} += $avg * $cnt;
                @$x{qw(peak peak_t)} = ($pk + 0, $p->{t} + 0) if !defined $x->{peak} || $pk > $x->{peak};
            }
        }
    }
    my @switches;
    for my $e (sort { lc $a->{name} cmp lc $b->{name} } values %sw) {
        my $m = $e->{m};
        my $av = sub { my $x = $m->{ $_[0] } or return undef; 0 + sprintf('%.2f', $x->{sum} / ($x->{n} || 1)) };
        my $pk = sub { my $x = $m->{ $_[0] } or return undef; $x->{peak} };
        my @ul;
        for my $k (sort grep { /^rx:/ } keys %$m) {
            my $tok = substr($k, 3);
            my $spd = $pk->("sp:$tok");
            push @ul, { port => $tok, speed => $spd, rx_avg => $av->("rx:$tok"), rx_peak => $pk->("rx:$tok"), rx_peak_t => $m->{"rx:$tok"}{peak_t},
                        tx_avg => $av->("tx:$tok"), tx_peak => $pk->("tx:$tok"), tx_peak_t => ($m->{"tx:$tok"} || {})->{peak_t} };
        }
        push @switches, { host => $e->{host}, name => $e->{name}, hours => $e->{hours},
                          up_avg => $av->('up'), up_peak => $pk->('up'), ports => $pk->('n'),
                          poe_avg => $av->('poe'), poe_peak => $pk->('poe'), poe_peak_t => ($m->{poe} || {})->{peak_t}, poe_budget => $pk->('poew'),
                          temp_avg => $av->('temp'), temp_max => $pk->('temp'), temp_max_t => ($m->{temp} || {})->{peak_t},
                          errors => ($m->{err} ? int($m->{err}{tot} + .5) : undef), uplinks => \@ul };
    }
    # timeline: devices with outages, their outage stretches
    my @timeline = map { { key => $_->{key}, kind => $_->{kind}, name => $_->{name}, where => $_->{where}, segs => $bykey{ $_->{key} } } }
                   grep { $bykey{ $_->{key} } } sort { $b->{down} <=> $a->{down} } @devices;
    splice @timeline, 40 if @timeline > 40;
    my $r = {
        from => $from + 0, to => $to + 0, kind => 'devices',
        avail => $ps->{avail}, counts => $ps->{counts}, known => \%k,
        downtime => $down + 0, longest => ($long ? { name => $long->{name}, kind => $long->{kind}, where => $long->{where}, start => $long->{start} + 0, dur => $long->{dur} + 0 } : undef),
        outages_n => scalar(@{ $ps->{outages} || [] }), maint_outages => $ps->{maint_outages},
        days => \@days, devices => \@devices, timeline => \@timeline,
        outages => [ map { { kind => $_->{kind}, name => $_->{name}, where => $_->{where}, start => $_->{start} + 0, end => $_->{end}, dur => $_->{dur} + 0 } }
                     @{ $ps->{outages} || [] }[0 .. ($#{ $ps->{outages} || [] } < 24 ? $#{ $ps->{outages} || [] } : 24)] ],
        flaps => $ps->{flaps}, reboots => [ map { { name => $_->{name}, ip => $_->{ip}, t => $_->{t} + 0, text => $_->{text} } } @{ $ps->{reboots} || [] } ],
        versions => [ map { { name => $_->{name}, t => $_->{t} + 0, text => $_->{text} // '' } } @{ $ps->{versions} || [] } ],
        maint => [ map { { name => $_->{name}, t => ($_->{from} // $_->{t}) + 0, until => ($_->{until} // 0) + 0, text => $_->{reason} // $_->{text} // '' } } @{ $ps->{maint} || [] } ],
        switches => \@switches, hist_points => scalar(@{ $h->{points} }),
    };
    if (!$noprev) {
        my ($pf, $pt) = report_prev($from, $to);
        my $p = period_stats($g, $pf, $pt);
        my $pd = 0; $pd += $_->{dur} for @{ $p->{outages} || [] };
        $r->{prev} = { from => $pf + 0, to => $pt + 0, avail => $p->{avail}, outages_n => scalar(@{ $p->{outages} || [] }), downtime => $pd + 0 };
    }
    return $r;
}

sub device_report_cached {
    my ($g, $from, $to, $status) = @_;
    my $over = $to <= time - 2 * 3600;
    return device_report($g, $from, $to, $status) unless $over;
    require Digest::MD5;
    my $dir = data_file($g, 'report-cache');
    my @keys = sort map { $_->{key} // '' } ();
    my $sig = join(',', sort((map { $_->{name} } @{ $status->{controllers} || [] }), (map { $_->{host} } @{ ($status->{devices} || {})->{items} || [] })));
    my $f = "$dir/" . Digest::MD5::md5_hex(join('|', 'dev', 1, $from, $to, $sig)) . '.json';
    if (-r $f) { my $r = jread($f); return $r if $r && $r->{from} }
    my $r = device_report($g, $from, $to, $status);
    jwrite($f, $r) if -d $dir || mkdir $dir, 0750;
    return $r;
}

sub device_report_combine {
    my ($from, $to, @parts) = @_;                   # [title, report] ...
    my (@devices, @outages, @timeline, @flaps, @reboots, @versions, @maint, @switches, %known, %counts, %w, %days, %pw, $down, $long, $n, $mo, $pn, $pdown);
    for my $pp (@parts) {
        my ($t, $r) = @$pp;
        push @devices, map { +{ %$_, site => $t } } @{ $r->{devices} };
        push @outages, map { +{ %$_, site => $t } } @{ $r->{outages} };
        push @timeline, map { +{ %$_, site => $t } } @{ $r->{timeline} };
        push @flaps, map { +{ %$_, site => $t } } @{ $r->{flaps} || [] };
        push @reboots, map { +{ %$_, site => $t } } @{ $r->{reboots} || [] };
        push @versions, map { +{ %$_, site => $t } } @{ $r->{versions} || [] };
        push @maint, map { +{ %$_, site => $t } } @{ $r->{maint} || [] };
        push @switches, map { +{ %$_, site => $t } } @{ $r->{switches} || [] };
        $known{$_} += $r->{known}{$_} // 0 for keys %{ $r->{known} || {} };
        $counts{$_} += $r->{counts}{$_} // 0 for keys %{ $r->{counts} || {} };
        for my $k (qw(dev ap ctl)) {                  # weighted by the number of devices of that kind
            my $v = ($r->{avail} || {})->{$k}; my $c = ($r->{known} || {})->{$k} || 0;
            next unless defined $v && $c;
            $w{$k}[0] += $v * $c; $w{$k}[1] += $c;
            my $pv = (($r->{prev} || {})->{avail} || {})->{$k};
            if (defined $pv) { $pw{$k}[0] += $pv * $c; $pw{$k}[1] += $c }
        }
        for my $d (@{ $r->{days} || [] }) {
            my $e = $days{ $d->[0] } ||= [ map { [0, 0] } 1 .. 3 ];
            for my $j (0 .. 2) { my $c = $r->{known}{ (qw(dev ap ctl))[$j] } || 0; next unless defined $d->[ $j + 1 ] && $c; $e->[$j][0] += $d->[ $j + 1 ] * $c; $e->[$j][1] += $c }
        }
        $down += $r->{downtime} // 0; $n += $r->{outages_n} // 0; $mo += $r->{maint_outages} // 0;
        $long = { %{ $r->{longest} }, site => $t } if $r->{longest} && (!$long || $r->{longest}{dur} > $long->{dur});
        if ($r->{prev}) { $pn += $r->{prev}{outages_n} // 0; $pdown += $r->{prev}{downtime} // 0 }
    }
    my $avg = sub { my $x = shift; $x && $x->[1] ? 0 + sprintf('%.3f', $x->[0] / $x->[1]) : undef };
    @outages = (sort { $b->{dur} <=> $a->{dur} } @outages)[0 .. (@outages > 25 ? 24 : $#outages)];
    @timeline = (sort { (eval { my $s = 0; $s += $_->[1] - $_->[0] for @{ $b->{segs} }; $s } // 0) <=> (eval { my $s = 0; $s += $_->[1] - $_->[0] for @{ $a->{segs} }; $s } // 0) } @timeline);
    splice @timeline, 40 if @timeline > 40;
    my ($pfrom, $pto) = report_prev($from, $to);
    return {
        from => $from + 0, to => $to + 0, kind => 'devices', sites => scalar(@parts),
        avail => { dev => $avg->($w{dev}), ap => $avg->($w{ap}), ctl => $avg->($w{ctl}) }, counts => \%counts, known => \%known,
        downtime => $down // 0, longest => $long, outages_n => $n // 0, maint_outages => $mo // 0,
        days => [ map { my $e = $days{$_}; [ $_ + 0, map { $avg->($e->[$_]) } 0 .. 2 ] } sort { $a <=> $b } keys %days ],
        devices => [ sort { $a->{avail} <=> $b->{avail} || $b->{n} <=> $a->{n} } @devices ], timeline => \@timeline, outages => \@outages,
        flaps => \@flaps, reboots => \@reboots, versions => \@versions, maint => \@maint, switches => \@switches,
        prev => (%pw ? { from => $pfrom + 0, to => $pto + 0, avail => { map { ($_ => $avg->($pw{$_})) } keys %pw }, outages_n => $pn // 0, downtime => $pdown // 0 } : undef),
    };
}

sub report_prev {
    my ($from, $to) = @_;
    my @f = localtime $from;
    my @t = localtime $to;
    if ($f[0] + $f[1] + $f[2] == 0 && $t[0] + $t[1] + $t[2] == 0 && $f[3] == 1 && $t[3] == 1) {
        my $months = ($t[5] - $f[5]) * 12 + $t[4] - $f[4];
        if ($months >= 1) {
            return (POSIX::mktime(0, 0, 0, 1, $f[4] - $months, $f[5], 0, 0, -1), $from);
        }
    }
    return ($from - ($to - $from), $from);
}

sub client_report_combine {
    my ($from, $to, @parts) = @_;                   # [title, report] ...
    my (%s, %day, %mon, @heat, %ss, @ctl, @aps, %prevsum);
    my $step = 3600;
    for my $pp (@parts) {
        my ($title, $r) = @$pp;
        $step = $r->{step} if $r->{step} > $step;
    }
    # hours when every site has them, otherwise days (long periods come without the hourly curve)
    my $by_day = grep { !@{ $_->[1]{series} || [] } && @{ $_->[1]{days} || [] } } @parts;
    $step = 86400 if $by_day;
    for my $pp (@parts) {
        my ($title, $r) = @$pp;
        for my $p (@{ $by_day ? $r->{days} : $r->{series} }) {
            my $k = $step > 3600 ? local_floor($p->[0], 'd') : $p->[0];
            my $e = $s{$k} ||= [ $k, 0, 0, {} ];
            $e->[3]{$title} = [ $p->[1], $p->[2] ];
        }
        if ($r->{heat}) { for my $d (0 .. 6) { for my $hh (0 .. 23) { my $v = $r->{heat}[$d][$hh]; $heat[$d][$hh] += $v if defined $v } } }
        for my $x (@{ $r->{ssids} }) { my $e = $ss{ $x->{name} } ||= { name => $x->{name}, avg => 0, peak => 0, peak_t => 0 }; $e->{avg} += $x->{avg}; @$e{qw(peak peak_t)} = @$x{qw(peak peak_t)} if $x->{peak} > $e->{peak} }
        push @ctl, { name => $title, avg => $r->{avg} // 0, peak => ($r->{peak} || [0])->[0], peak_t => ($r->{peak} || [0, 0])->[1] };
        push @aps, map { +{ %$_, ctl => $title } } @{ $r->{aps} };
        if ($r->{prev}) {
            $prevsum{avg} += $r->{prev}{avg} // 0; $prevsum{client_hours} += $r->{prev}{client_hours} // 0;
            $prevsum{hours} = $r->{prev}{hours} if ($r->{prev}{hours} // 0) > ($prevsum{hours} // 0);
            $prevsum{hours_total} = $r->{prev}{hours_total};
            @prevsum{qw(from to)} = @{ $r->{prev} }{qw(from to)};
        }
    }
    my (@series, $pk, $sum, $n);
    for my $k (sort { $a <=> $b } keys %s) {
        my $e = $s{$k};
        my ($a, $p) = (0, 0);
        for my $v (values %{ $e->[3] }) { $a += $v->[0]; $p += $v->[1] }       # peak of all = sum of the peaks of the step (upper bound)
        push @series, [ $k + 0, 0 + sprintf('%.2f', $a), $p + 0 ];
        $sum += $a * ($by_day ? 24 : 1); $n += $by_day ? 24 : 1;
        $pk = [ $p, $k + 0 ] if !$pk || $p > $pk->[0];
        my @l = localtime $k;
        for my $b ([ \%day, POSIX::mktime(0, 0, 0, @l[3, 4, 5], 0, 0, -1) ], [ \%mon, POSIX::mktime(0, 0, 0, 1, @l[4, 5], 0, 0, -1) ]) {
            my $d = $b->[0]{ $b->[1] } ||= [ 0, 0, 0, 0 ];
            $d->[0] += $a; $d->[1]++;
            @$d[2, 3] = ($p, $k) if $p > $d->[2] || !$d->[3];
        }
    }
    my $tot = 0; $tot += $_->{avg} for @ctl;
    my $share = sub { my ($l) = @_; my $t = 0; $t += $_->{avg} for @$l; $_->{share} = 0 + sprintf('%.4f', $t ? $_->{avg} / $t : 0) for @$l;
                      [ sort { $b->{avg} <=> $a->{avg} || $b->{peak} <=> $a->{peak} } @$l ] };
    my $fin = sub { my ($m) = @_; [ map { [ $_ + 0, 0 + sprintf('%.2f', $m->{$_}[0] / $m->{$_}[1]), $m->{$_}[2] + 0, $m->{$_}[3] + 0 ] } sort { $a <=> $b } keys %$m ] };
    return {
        from => $from + 0, to => $to + 0, step => $step, scope => '', sites => scalar(@parts),
        controllers => [ map { $_->[0] } @parts ],
        hours => scalar(@series), hours_total => int(($to - $from) / $step + .5),
        peak => $pk, avg => ($n ? 0 + sprintf('%.2f', $sum / $n) : undef),
        client_hours => 0 + sprintf('%.1f', $sum // 0),
        series => ($by_day ? [] : \@series), days => $fin->(\%day), months => $fin->(\%mon),
        heat => (@heat ? [ map { my $d = $_; [ map { defined $heat[$d][$_] ? 0 + sprintf('%.2f', $heat[$d][$_]) : undef } 0 .. 23 ] } 0 .. 6 ] : undef),
        ssids => $share->([ values %ss ]), aps => $share->(\@aps), ctl => $share->(\@ctl), ctl_kind => 'site',
        prev => (%prevsum ? { %prevsum, peak => undef } : undef),
    };
}

sub json_fast {
    our $JSON_FAST;
    $JSON_FAST //= (eval { require Cpanel::JSON::XS; 'Cpanel::JSON::XS' } || eval { require JSON::XS; 'JSON::XS' } || 'JSON::PP');
    return $JSON_FAST->new->utf8;
}

sub fmt_dur {
    my $s = shift;
    my ($d, $h, $m) = (int($s / 86400), int($s % 86400 / 3600), int($s % 3600 / 60));
    return $d ? "${d}d ${h}h" : $h ? "${h}h ${m}m" : "${m}m";
}

sub html_tiles {
    my ($tiles) = @_;
    my @tiles = @$tiles;
    my $html = '';
    if (@tiles) {
        $html .= qq{<tr><td style="padding:20px 24px 4px 24px;">\n};
        while (my @row = splice(@tiles, 0, 3)) {
            $html .= qq{<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px;"><tr>\n};
            for my $i (0 .. 2) {
                my $t = $row[$i];
                my $pad = $i == 0 ? '0 6px 0 0' : $i == 1 ? '0 3px' : '0 0 0 6px';
                $html .= qq{<td width="33%" style="padding:$pad;">};
                $html .= qq{<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:$t->[3];border-left:4px solid $t->[2];border-radius:4px;"><tr><td style="padding:10px 12px;">}
                       . qq{<div style="font-size:24px;font-weight:700;color:$t->[2];">$t->[0]</div>}
                       . qq{<div style="font-size:12px;color:#5f6b7a;">$t->[1]</div></td></tr></table>} if $t;
                $html .= "</td>\n";
            }
            $html .= "</tr></table>\n";
        }
        $html .= "</td></tr>\n";
    }
    return $html;
}

sub maint_match {
    my ($t, @names) = @_;
    $t = lc($t // '');
    return 0 unless length $t;
    my $re;
    if ($t =~ /[*?]/) { my $x = quotemeta $t; $x =~ s/\\\*/.*/g; $x =~ s/\\\?/./g; $re = qr/^$x$/s }
    for my $n (grep { defined && length } @names) {
        my $l = lc $n;
        return 1 if $re ? $l =~ $re : $l eq $t;
    }
    return 0;
}

sub maint_window {
    my ($spec, $now) = @_;
    $spec = lc($spec // '');
    $spec =~ s/\s+//g;
    my ($from, $until) = ($now);
    if ($spec =~ /^(\d+)$/) { $until = $now + $1 * 60 }
    elsif ($spec =~ /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m(?:in)?)?$/ && ($1 || $2 || $3)) { $until = $now + ($1 // 0) * 86400 + ($2 // 0) * 3600 + ($3 // 0) * 60 }
    elsif ($spec =~ /^(?:(\d{4}-\d\d-\d\d)t)?(\d?\d):(\d\d)(?:-(?:(\d{4}-\d\d-\d\d)t)?(\d?\d):(\d\d))?$/) {
        my ($d1, $h1, $m1, $d2, $h2, $m2) = ($1, $2, $3, $4, $5, $6);
        die "invalid time in '$spec'\n" if $h1 > 23 || $m1 > 59 || (defined $h2 && ($h2 > 23 || $m2 > 59));
        if (!defined $h2) {                                  # until HH:MM (the next one)
            $until = at_time($d1, $h1, $m1, $now);
            $until = at_time(undef, $h1, $m1, $now + 86400) if !$d1 && $until <= $now;
        } else {                                             # window FROM-UNTIL
            $until = at_time($d2, $h2, $m2, $now);
            $until = at_time(undef, $h2, $m2, $now + 86400) if !$d2 && $until <= $now;
            $from = at_time($d1 // $d2, $h1, $m1, $until);
            $from = at_time(undef, $h1, $m1, $until - 86400) if !$d1 && $from >= $until;
            $from = $now if $from < $now;
        }
    }
    else { die "cannot read the duration '$spec' (e.g. 2h, 90m, 1d, 18:00, 22:00-02:00)\n" }
    die "the window has already ended\n" if $until <= $now;
    die "a window can last at most 31 days\n" if $until - $from > 31 * 86400;
    return ($from, $until);
}

sub at_time {
    my ($date, $h, $m, $base) = @_;
    my @l = localtime $base;
    my ($y, $mo, $d) = $date ? split(/-/, $date) : ($l[5] + 1900, $l[4] + 1, $l[3]);
    return POSIX::mktime(0, $m, $h, $d, $mo - 1, $y - 1900, 0, 0, -1);
}

sub cert_date {
    my ($s) = @_;
    my %m = (jan => 0, feb => 1, mar => 2, apr => 3, may => 4, jun => 5, jul => 6, aug => 7, sep => 8, oct => 9, nov => 10, dec => 11);
    my ($mon, $d, $H, $M, $S, $y) = $s =~ /([A-Za-z]{3})\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d{4})/ or return undef;
    return undef unless exists $m{ lc $mon };
    return eval { Time::Local::timegm($S, $M, $H, $d, $m{ lc $mon }, $y) };
}

sub inventory_csv {
    my ($rows, $site) = @_;
    my @cols = ([ type => 'Type' ], [ name => 'Name' ], [ where => 'Controller / group' ], [ ip => 'IP' ], [ mac => 'MAC' ],
                [ model => 'Model' ], [ serial => 'Serial number' ], [ version => 'Version' ], [ firmware => 'Firmware' ],
                [ status => 'Status' ], [ mismatch => 'Version mismatch' ], [ descr => 'Description' ]);
    unshift @cols, [ site => 'Site' ] if $site;
    my $q = sub { my $v = shift // ''; $v =~ s/[\r\n]+/ /g; return $v =~ /[;",]/ ? '"' . ($v =~ s/"/""/gr) . '"' : $v };
    my %tn = (controller => 'Controller', ap => 'Access point', switch => 'Switch');
    my $out = "\x{FEFF}" . join(';', map { $_->[1] } @cols) . "\r\n";
    for my $r (@$rows) {
        $out .= join(';', map { $q->($_->[0] eq 'type' ? ($tn{ $r->{type} } // $r->{type}) : $r->{ $_->[0] }) } @cols) . "\r\n";
    }
    return $out;
}

sub period_bounds {
    my ($kind, $now) = @_;
    my @l = localtime $now;
    if ($kind eq 'week') {
        my $wday = ($l[6] + 6) % 7;
        return (POSIX::mktime(0, 0, 0, $l[3] - $wday - 7, $l[4], $l[5], 0, 0, -1),
                POSIX::mktime(0, 0, 0, $l[3] - $wday, $l[4], $l[5], 0, 0, -1));
    }
    return (POSIX::mktime(0, 0, 0, 1, $l[4] - 1, $l[5], 0, 0, -1), POSIX::mktime(0, 0, 0, 1, $l[4], $l[5], 0, 0, -1));
}

sub period_label {
    my ($kind, $from, $to) = @_;
    my @mn = qw(January February March April May June July August September October November December);
    my @a = localtime $from;
    return "$mn[$a[4]] " . ($a[5] + 1900) if $kind eq 'month';
    return 'last ' . int(($to - $from) / 86400 + 0.5) . ' days' if $kind eq 'days';
    my @b = localtime($to - 3600);
    return sprintf('%d.%d. - %d.%d.%d', $a[3], $a[4] + 1, $b[3], $b[4] + 1, $b[5] + 1900);
}

sub period_stats {
    my ($g, $from, $to) = @_;
    my $secs = $to - $from;
    my @ev = sort { $a->{t} <=> $b->{t} } read_jsonl(data_file($g, 'events.jsonl'), $from - 120 * 86400, $to);
    my %pair = (ap_missing => [ 'ap', 1 ], ap_back => [ 'ap', 0 ], ap_forgotten => [ 'ap', 0 ], dev_down => [ 'dev', 1 ], dev_up => [ 'dev', 0 ],
                ctl_down => [ 'ctl', 1 ], ctl_up => [ 'ctl', 0 ], site_offline => [ 'site', 1 ], site_online => [ 'site', 0 ]);
    my (%open, @out, %item, @flap, @reboot, @vers, @maint, @certs, %cnt);
    # maintenance windows (from their events): an outage that began in one counts as maintenance only
    # until that window ended, the rest as a normal outage
    my (%win, @win);
    for my $e (@ev) {
        if ($e->{type} eq 'maint_start' && $e->{id}) { $win{ $e->{id} } = { target => $e->{name}, start => ($e->{from} // $e->{t}), end => ($e->{until} // $to) } }
        elsif ($e->{type} eq 'maint_end' && $e->{id} && $win{ $e->{id} }) { $win{ $e->{id} }{end} = $e->{t} if $e->{t} < $win{ $e->{id} }{end} }
    }
    @win = values %win;
    my $close;
    $close = sub {
        my ($o, $end, $still) = @_;
        if ($o->{maint} && @win) {
            my @n = grep { defined } $o->{name}, $o->{ip}, $o->{mac}, $o->{ctl}, $o->{heading};
            my ($mend) = sort { $b <=> $a } map { $_->{end} } grep { $_->{start} <= $o->{start} + 60 && $_->{end} > $o->{start}
                            && ($_->{target} =~ /^(all|\*)$/i || maint_match($_->{target}, @n)) } @win;
            if (defined $mend && $mend < $end) {
                $close->({ %$o, end_m => 1 }, $mend);
                return $close->({ %$o, maint => 0, start => $mend }, $end, $still);
            }
        }
        my ($s, $e) = ($o->{start} > $from ? $o->{start} : $from, $end < $to ? $end : $to);
        return unless $e > $s;
        my $d = $e - $s;
        push @out, { %$o, end => ($still ? undef : $end), dur => $d };
        my $it = $item{ $o->{key} } ||= { key => $o->{key}, kind => $o->{kind}, name => $o->{name}, where => $o->{where}, ip => $o->{ip}, down => 0, maint_down => 0, n => 0 };
        $it->{ $o->{maint} ? 'maint_down' : 'down' } += $d;
        $it->{n}++ unless $o->{maint};
        $cnt{ $o->{kind} }++ unless $o->{maint};
    };
    for my $e (@ev) {
        my $t = $e->{t};
        if (my $p = $pair{ $e->{type} }) {
            my ($kind, $start) = @$p;
            my $key = $kind eq 'ap' ? "ap|" . ($e->{ctl} // '') . "|" . ($e->{mac} || $e->{name} // '')
                    : $kind eq 'dev' ? "dev|" . ($e->{ip} // $e->{name} // '')
                    : $kind eq 'ctl' ? "ctl|" . ($e->{ctl} // '') : 'site';
            if ($start) {
                $open{$key} //= { key => $key, kind => $kind, start => $t, maint => ($e->{maint} ? 1 : 0),
                                  mac => $e->{mac}, ctl => $e->{ctl}, heading => $e->{heading},
                                  name => ($kind eq 'ctl' ? ($e->{heading} || $e->{ctl}) : $kind eq 'site' ? 'Site not reporting' : ($e->{name} || $e->{mac} || $e->{ip})),
                                  where => ($kind eq 'ap' ? ($e->{heading} || $e->{ctl}) : $kind eq 'dev' ? $e->{ip} : $kind eq 'ctl' ? $e->{host} : ''),
                                  ip => $e->{ip} // $e->{host} // '' };
            } elsif (my $o = delete $open{$key}) {
                $close->($o, $t);
            }
            next;
        }
        if ($e->{type} eq 'baseline' && defined $e->{ctl}) { $close->(delete $open{$_}, $t) for grep { /^ap\|\Q$e->{ctl}\E\|/ } keys %open; next }
        if ($e->{type} eq 'baseline_dev') { $close->(delete $open{$_}, $t) for grep { /^dev\|/ } keys %open; next }
        next if $t < $from;
        if    ($e->{type} =~ /^(ap|dev)_flap$/) { push @flap, $e }
        elsif ($e->{type} eq 'dev_reboot')      { push @reboot, $e }
        elsif ($e->{type} eq 'inv_change')      { push @vers, $e }
        elsif ($e->{type} eq 'maint_start')     { push @maint, $e }
        elsif ($e->{type} eq 'cert_warn')       { push @certs, $e }
    }
    # still going on: up to now - but not for a device that is not in the configuration any more
    # (13.7.1: it was removed while down, or was there only for a moment; its outage never ends)
    $close->($_, ($to < time ? $to : time), 1) for grep { !$g->{_known} || $_->{kind} eq 'site' || $g->{_known}{ $_->{key} } } values %open;
    undef $close;

    # availability from the history: access points online / known, controllers reachable, devices responding
    my $h = hist_range({ general => $g }, 'history', $from, $to, 2000);
    my ($apu, $apk, $cr, $cn, $du, $dk) = (0) x 6;
    for my $p (@{ $h->{points} }) {
        for my $c (values %{ $p->{c} || {} }) { $apu += $c->[0] // 0; $apk += ($c->[0] // 0) + ($c->[1] // 0); $cr += $c->[2] // 1; $cn++ }
        if ($p->{s}) { $du += $p->{s}[0] // 0; $dk += ($p->{s}[0] // 0) + ($p->{s}[1] // 0) }
    }
    my $pct = sub { my ($a, $b) = @_; return $b ? 0 + sprintf('%.2f', 100 * $a / $b) : undef };
    # Wi-Fi clients: peak (with time), average, peak per SSID
    my $w = hist_range({ general => $g }, 'clients', $from, $to, 2000);
    my ($peak, $pt, $asum, $an, %ss) = (0, undef, 0, 0);
    for my $p (@{ $w->{points} }) {
        if (my $a = ($p->{tot} || {})->{_all}) {
            $asum += $a->[0]; $an++;
            if ($a->[1] > $peak) { $peak = $a->[1]; $pt = $a->[2] // $p->{t} }
        }
        my %sum;
        for my $c (values %{ $p->{c} || {} }) { $sum{$_} += $c->{$_}[1] // 0 for keys %$c }
        $ss{$_} = $sum{$_} for grep { !defined $ss{$_} || $sum{$_} > $ss{$_} } keys %sum;
    }
    my %fl;
    for my $e (@flap) { my $k = ($e->{name} // '') . '|' . ($e->{heading} // $e->{ip} // ''); $fl{$k} ||= { name => $e->{name}, where => $e->{heading} || $e->{ip}, n => 0 }; $fl{$k}{n}++ }
    return {
        from => $from + 0, to => $to + 0, secs => $secs,
        avail => { ap => $pct->($apu, $apk), ctl => $pct->($cr, $cn), dev => $pct->($du, $dk), points => scalar @{ $h->{points} } },
        items => [ sort { $b->{down} <=> $a->{down} || $b->{n} <=> $a->{n} } map { { %$_, avail => 0 + sprintf('%.2f', 100 * (1 - $_->{down} / $secs)) } } values %item ],
        outages => [ sort { $b->{dur} <=> $a->{dur} } grep { !$_->{maint} } @out ],
        maint_outages => scalar(grep { $_->{maint} } @out),
        counts => { map { ($_ => $cnt{$_} // 0) } qw(ap dev ctl site) },
        wifi => ($an ? { peak => $peak + 0, peak_t => $pt, avg => 0 + sprintf('%.1f', $asum / $an),
                         ssids => { map { ($_ => $ss{$_} + 0) } keys %ss } } : undef),
        flaps => [ sort { $b->{n} <=> $a->{n} } values %fl ], reboots => \@reboot, versions => \@vers, maint => \@maint, cert_warns => \@certs,
    };
}

sub fmt_pct { my $v = shift; return '-' unless defined $v; return $v >= 99.995 ? '100 %' : sprintf('%.2f %%', $v) }

sub fmt_dur_long {
    my $s = int(shift // 0);
    my ($d, $h, $m) = (int($s / 86400), int($s % 86400 / 3600), int($s % 3600 / 60));
    return $d ? "${d} d ${h} h" : $h ? "${h} h ${m} min" : $m ? "${m} min" : "$s s";
}

sub report_render {
    my ($o) = @_;
    my $kind = $o->{kind};
    my $per = period_label($kind, $o->{from}, $o->{to});
    my $multi = @{ $o->{sites} } > 1 || $o->{multi};
    my $word = $kind eq 'week' ? 'Weekly' : $kind eq 'month' ? 'Monthly' : 'Period';
    my ($F, $TDs, $MO) = ("font-family:Segoe UI,Arial,Helvetica,sans-serif;", "padding:6px 8px;", "font-family:Consolas,Menlo,monospace;font-size:12px;");
    my $hh = sub { my $s = shift // ''; $s =~ s/&/&amp;/g; $s =~ s/</&lt;/g; $s =~ s/>/&gt;/g; $s =~ s/"/&quot;/g; $s };
    my $acol = sub { my $v = shift; return '#5f6b7a' unless defined $v; return $v >= 99.9 ? '#2f855a' : $v >= 99 ? '#b7791f' : '#c53030' };

    # totals over all sites
    my (%tot, $peak, $peak_site, $outn);
    for my $s (@{ $o->{sites} }) {
        my $st = $s->{stats};
        $outn += @{ $st->{outages} };
        if ($st->{wifi} && (!defined $peak || $st->{wifi}{peak} > $peak)) { $peak = $st->{wifi}{peak}; $peak_site = $s->{title} }
        for my $k (qw(ap dev)) { next unless defined $st->{avail}{$k}; $tot{$k}[0] += $st->{avail}{$k}; $tot{$k}[1]++ }
    }
    my %avg = map { ($_ => $tot{$_} ? $tot{$_}[0] / $tot{$_}[1] : undef) } qw(ap dev);
    my $subject = "$word report $per: " . join(', ', grep { $_ }
        (defined $avg{ap} ? 'APs ' . fmt_pct($avg{ap}) : ''), (defined $avg{dev} ? 'devices ' . fmt_pct($avg{dev}) : ''),
        ($outn // 0) . ' outage' . (($outn // 0) == 1 ? '' : 's'), (defined $peak ? "Wi-Fi peak $peak" : ''));

    my (@txt, $html);
    push @txt, "MT-Mon " . lc($word) . " report - $o->{title}", "Period: $per (" . fmt_time($o->{from}) . " - " . fmt_time($o->{to}) . ")", '=' x 72, '';
    my @tiles = (
        [ fmt_pct($avg{ap}),  'access points online' . ($multi ? ' (average)' : ''), $acol->($avg{ap}),  '#eef1f4' ],
        [ fmt_pct($avg{dev}), 'devices responding' . ($multi ? ' (average)' : ''),   $acol->($avg{dev}), '#eef1f4' ],
        [ $outn // 0,         'outages',                                             ($outn ? '#c53030' : '#2f855a'), ($outn ? '#fdecec' : '#e8f5ec') ],
    );
    push @tiles, [ $peak, 'Wi-Fi clients at peak' . ($multi && $peak_site ? " ($peak_site)" : ''), '#2b6cb0', '#e8f0fa' ] if defined $peak;
    @tiles = grep { $_->[0] ne '-' } @tiles;
    my $c = html_tiles(\@tiles);
    my $sec = sub { my ($t, $sub) = @_; qq{<tr><td style="padding:22px 24px 0 24px;"><div style="font-size:16px;font-weight:600;">@{[ $hh->($t) ]}</div>}
                                        . (defined $sub ? qq{<div style="font-size:13px;color:#5f6b7a;padding-top:2px;">@{[ $hh->($sub) ]}</div>} : '') . qq{</td></tr>\n} };
    my $table = sub {
        my ($head, $rows, $right) = @_;
        my %r = map { $_ => 1 } @{ $right || [] };
        my $x = qq{<tr><td style="padding:10px 24px 0 24px;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size:13px;border-collapse:collapse;">\n}
              . qq{<tr style="background:#f4f6f8;color:#5f6b7a;">} . join('', map { qq{<td style="$TDs font-weight:600;@{[ $r{$_} ? 'text-align:right;' : '' ]}">$head->[$_]</td>} } 0 .. $#$head) . "</tr>\n";
        for my $row (@$rows) {
            $x .= qq{<tr style="border-bottom:1px solid #e4e8ec;">} . join('', map {
                my $v = $row->[$_]; my $st = ref $v ? $v->[1] : ''; $v = ref $v ? $v->[0] : $hh->($v);
                qq{<td style="$TDs$st@{[ $r{$_} ? 'text-align:right;' : '' ]}">$v</td>} } 0 .. $#$row) . "</tr>\n";
        }
        return $x . "</table></td></tr>\n";
    };
    my $ttab = sub { my ($head, $rows, $w) = @_; my $f = join(' ', map { "%-${_}s" } @$w);
                     return join('', map { '  ' . sprintf($f, map { ref $_ ? $_->[2] // strip_tags($_->[0]) : $_ // '' } @$_) =~ s/\s+$//r . "\n" } $head, @$rows) };
    my $kname = { ap => 'Access point', dev => 'Device', ctl => 'Controller', site => 'Site' };

    if ($multi) {
        my @rows;
        for my $s (@{ $o->{sites} }) {
            my $st = $s->{stats};
            my $site_up = $st->{secs} ? 100 * (1 - ((grep { $_->{kind} eq 'site' } @{ $st->{items} })[0] || { down => 0 })->{down} / $st->{secs}) : undef;
            push @rows, [ $s->{title}, [ fmt_pct($site_up), "color:" . $acol->($site_up) . ";" ], [ fmt_pct($st->{avail}{ap}), "color:" . $acol->($st->{avail}{ap}) . ";" ],
                          [ fmt_pct($st->{avail}{dev}), "color:" . $acol->($st->{avail}{dev}) . ";" ], scalar @{ $st->{outages} },
                          $st->{wifi} ? $st->{wifi}{peak} : '-' ];
        }
        $c .= $sec->('Sites', scalar(@{ $o->{sites} }) . ' site(s)') . $table->([ 'Site', 'Reporting', 'APs online', 'Devices', 'Outages', 'Wi-Fi peak' ], \@rows, [ 1, 2, 3, 4, 5 ]);
        push @txt, 'SITES', $ttab->([ 'Site', 'Reporting', 'APs online', 'Devices', 'Outages', 'Wi-Fi peak' ],
                                   [ map { [ $_->[0], map { ref $_ ? $_->[0] : $_ } @$_[1 .. 5] ] } @rows ], [ 28, 10, 11, 9, 8, 10 ]), '';
    }
    for my $s (@{ $o->{sites} }) {
        my $st = $s->{stats};
        my $pre = $multi ? "$s->{title}: " : '';
        if ($multi) { $c .= qq{<tr><td style="padding:26px 24px 0 24px;"><div style="border-top:2px solid #1f3a5f;padding-top:12px;font-size:18px;font-weight:700;">@{[ $hh->($s->{title}) ]}</div></td></tr>\n}; push @txt, '-' x 72, uc($s->{title}), '' }
        my @least = grep { $_->{down} > 0 && $_->{kind} ne 'site' } @{ $st->{items} };
        if (@least) {
            my @r = map { [ $_->{name} // '-', $_->{where} // '', $_->{n}, fmt_dur_long($_->{down}), [ fmt_pct($_->{avail}), "font-weight:600;color:" . $acol->($_->{avail}) . ";" ] ] } @least[0 .. ($#least > 9 ? 9 : $#least)];
            $c .= $sec->('Least available', 'access points, devices and controllers with outages in this period') . $table->([ 'Name', 'Where', 'Outages', 'Down', 'Available' ], \@r, [ 2, 3, 4 ]);
            push @txt, 'LEAST AVAILABLE', $ttab->([ 'Name', 'Where', 'Outages', 'Down', 'Available' ], [ map { [ @$_[0 .. 3], $_->[4][0] ] } @r ], [ 26, 22, 8, 12, 10 ]), '';
        } else {
            $c .= qq{<tr><td style="padding:20px 24px 0 24px;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#e8f5ec;border-left:4px solid #2f855a;border-radius:4px;"><tr><td style="padding:10px 12px;font-size:13px;"><b style="color:#2f855a;">No outages</b> &nbsp;All access points, controllers and devices were available the whole period.</td></tr></table></td></tr>\n};
            push @txt, "${pre}No outages - everything was available the whole period.", '';
        }
        if (my @o = @{ $st->{outages} }) {
            my @r = map { [ $_->{name} // '-', $kname->{ $_->{kind} } // '', fmt_time($_->{start} > $st->{from} ? $_->{start} : $st->{from}),
                            $_->{end} ? fmt_dur_long($_->{dur}) : [ fmt_dur_long($_->{dur}) . ' (still down)', 'color:#c53030;', fmt_dur_long($_->{dur}) . ' (still down)' ] ] } @o[0 .. ($#o > 14 ? 14 : $#o)];
            $c .= $sec->('Longest outages', scalar(@o) . ' in total' . ($st->{maint_outages} ? ", plus $st->{maint_outages} during maintenance" : '')) . $table->([ 'Name', 'Type', 'Start', 'Duration' ], \@r, [ 3 ]);
            push @txt, 'LONGEST OUTAGES (' . scalar(@o) . ' in total)', $ttab->([ 'Name', 'Type', 'Start', 'Duration' ], \@r, [ 26, 13, 17, 20 ]), '';
        }
        if (my $w = $st->{wifi}) {
            my @top = sort { $w->{ssids}{$b} <=> $w->{ssids}{$a} } keys %{ $w->{ssids} };
            my $line = "Peak $w->{peak} clients" . ($w->{peak_t} ? ' (' . fmt_time($w->{peak_t}) . ')' : '') . ", average $w->{avg}";
            $c .= $sec->('Wi-Fi clients', $line) . (@top ? $table->([ 'SSID', 'Peak' ], [ map { [ $_, $w->{ssids}{$_} ] } @top[0 .. ($#top > 7 ? 7 : $#top)] ], [ 1 ]) : '');
            push @txt, 'WI-FI CLIENTS', "  $line", (map { sprintf("    %-30s %s", $_, $w->{ssids}{$_}) } @top[0 .. ($#top > 7 ? 7 : $#top)]), '';
        }
        if (my @f = @{ $st->{flaps} }) {
            my @r = map { [ $_->{name} // '-', $_->{where} // '', $_->{n} ] } @f[0 .. ($#f > 9 ? 9 : $#f)];
            $c .= $sec->('Unstable (flapping)', 'dropped again and again') . $table->([ 'Name', 'Where', 'Times' ], \@r, [ 2 ]);
            push @txt, 'UNSTABLE (FLAPPING)', $ttab->([ 'Name', 'Where', 'Times' ], \@r, [ 26, 24, 6 ]), '';
        }
        if (my @b = @{ $st->{reboots} }) {
            my @r = map { [ $_->{name} // '-', $_->{ip} // '', fmt_time($_->{t}) ] } @b;
            $c .= $sec->('Restarts', 'devices that restarted (SNMP uptime)') . $table->([ 'Device', 'IP', 'Time' ], \@r);
            push @txt, 'RESTARTS', $ttab->([ 'Device', 'IP', 'Time' ], \@r, [ 26, 16, 17 ]), '';
        }
        if (my @v = @{ $st->{versions} }) {
            my @r = map { [ $_->{name} // '-', $_->{text} // '', fmt_time($_->{t}) ] } @v;
            $c .= $sec->('Firmware changes') . $table->([ 'Device', 'Version', 'Seen' ], \@r);
            push @txt, 'FIRMWARE CHANGES', $ttab->([ 'Device', 'Version', 'Seen' ], \@r, [ 26, 26, 17 ]), '';
        }
        if (my @ce = grep { defined $_->{days} && $_->{days} <= 30 } @{ $s->{certs} || [] }) {
            my @r = map { [ $_->{name}, $_->{target} // '', [ $_->{days} < 0 ? 'expired' : "$_->{days} days", 'font-weight:600;color:' . ($_->{days} <= 7 ? '#c53030' : '#b7791f') . ';',
                                                              $_->{days} < 0 ? 'expired' : "$_->{days} days" ] ] } sort { $a->{days} <=> $b->{days} } @ce;
            $c .= $sec->('Certificates expiring within 30 days') . $table->([ 'Name', 'Target', 'Left' ], \@r, [ 2 ]);
            push @txt, 'CERTIFICATES EXPIRING WITHIN 30 DAYS', $ttab->([ 'Name', 'Target', 'Left' ], \@r, [ 26, 34, 10 ]), '';
        }
        if (my @mm = @{ $s->{mismatch} || [] }) {
            my @r = map { [ $_->{name} // '-', $_->{model} // '', $_->{version} // '', $_->{mismatch} ] } @mm[0 .. ($#mm > 14 ? 14 : $#mm)];
            $c .= $sec->('Version mismatch', scalar(@mm) . ' device(s) run another version than the others of the same model') . $table->([ 'Device', 'Model', 'Version', 'Note' ], \@r);
            push @txt, 'VERSION MISMATCH', $ttab->([ 'Device', 'Model', 'Version', 'Note' ], \@r, [ 24, 18, 14, 24 ]), '';
        }
        if (my @m = @{ $st->{maint} }) {
            my @r = map { [ $_->{name} // '', fmt_time($_->{t}), $_->{text} // '', $_->{reason} // '' ] } @m;
            $c .= $sec->('Maintenance windows') . $table->([ 'Target', 'Set', 'Window', 'Reason' ], \@r);
            push @txt, 'MAINTENANCE WINDOWS', $ttab->([ 'Target', 'Set', 'Window', 'Reason' ], \@r, [ 20, 17, 24, 20 ]), '';
        }
    }
    push @txt, '', $o->{footer} // '';
    my $hdr = qq{<tr><td style="background:#1f3a5f;border-radius:8px 8px 0 0;padding:20px 24px;">}
            . qq{<div style="font-size:12px;letter-spacing:1px;color:#9fb3c8;text-transform:uppercase;">MT-Mon @{[ lc $word ]} report</div>}
            . qq{<div style="font-size:22px;font-weight:600;color:#ffffff;padding-top:2px;">@{[ $hh->($o->{title}) ]}</div>}
            . qq{<div style="font-size:13px;color:#c5d3e0;padding-top:4px;">@{[ $hh->($per) ]} &nbsp;&middot;&nbsp; @{[ fmt_time($o->{from}) ]} &ndash; @{[ fmt_time($o->{to}) ]}</div></td></tr>\n};
    $html = qq{<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>@{[ $hh->($subject) ]}</title>\n</head>\n}
          . qq{<body style="margin:0;padding:0;background:#eef1f4;">\n<div style="display:none;max-height:0;overflow:hidden;">@{[ $hh->($subject) ]}</div>\n}
          . qq{<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#eef1f4;"><tr><td align="center" style="padding:24px 12px;">\n}
          . qq{<table role="presentation" width="680" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:680px;background:#ffffff;border-radius:8px;${F}color:#1f2933;">\n}
          . $hdr . $c
          . qq{<tr><td style="padding:24px;font-size:11px;color:#8a96a3;"><div style="border-top:1px solid #e4e8ec;padding-top:12px;">@{[ $hh->($o->{footer} // '') ]}</div></td></tr>\n}
          . qq{</table></td></tr></table>\n</body>\n</html>\n};
    return ($subject, join("\n", @txt) . "\n", $html);
}

sub strip_tags { my $s = shift // ''; $s =~ s/<[^>]*>//g; $s =~ s/&nbsp;/ /g; $s =~ s/&amp;/&/g; return $s }

sub vcmp_ver {
    my @a = split /[.\-\s]/, $_[0]; my @b = split /[.\-\s]/, $_[1];
    for my $i (0 .. ($#a > $#b ? $#a : $#b)) {
        my ($x, $y) = ($a[$i] // 0, $b[$i] // 0);
        my $c = ($x =~ /^\d+$/ && $y =~ /^\d+$/) ? $x <=> $y : $x cmp $y;
        return $c if $c;
    }
    return 0;
}

sub manual_page {
    my ($c, $pkg, $lang, $al, @dirs) = @_;
    $lang = ($al // '') =~ /^\s*sl\b/i ? 'sl' : 'en' unless ($lang // '') =~ /^(?:sl|en)$/;
    my @names = map { $_ eq 'sl' ? "$pkg-navodila-sl.html" : "$pkg-manual-en.html" } ($lang, $lang eq 'sl' ? 'en' : 'sl');
    my ($file) = grep { -r } map { my $d = $_; map { "$d/$_" } @names } @dirs;
    return web_reply($c, 404, 'text/plain; charset=utf-8', "The manual is not installed (looked for $names[0] in " . join(', ', @dirs) . ").\n") unless $file;
    open(my $fh, '<:raw', $file) or return web_reply($c, 500, 'text/plain', "Cannot read $file: $!\n");
    local $/;
    my $html = <$fh>;
    close $fh;
    return web_reply($c, 200, 'text/html; charset=utf-8', $html, 'Cache-Control: no-cache',
        "Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:");
}

sub sys_read1 { open(my $fh, '<', $_[0]) or return undef; my $v = <$fh>; close $fh; chomp $v if defined $v; return $v }

sub sys_cgroup {
    open(my $fh, '<', '/proc/self/cgroup') or return undef;
    while (my $l = <$fh>) {
        next unless $l =~ m{^0::(/\S*)};
        my $d = '/sys/fs/cgroup' . ($1 eq '/' ? '' : $1);
        return $d if -r "$d/memory.current" && -r "$d/cpu.stat";
    }
    return undef;
}

sub sys_usage {
    my ($prog) = @_;
    my %u;
    if (my $cg = sys_cgroup()) {
        my $cur = sys_read1("$cg/memory.current") // 0;
        my %ms;
        if (open(my $fh, '<', "$cg/memory.stat")) { while (<$fh>) { $ms{$1} = $2 if /^(\w+) (\d+)/ } close $fh }
        $u{cache} = $ms{file} // 0;
        $u{mem} = $cur - $u{cache};
        $u{mem} = $cur if $u{mem} < 0;
        if (open(my $fh, '<', "$cg/cpu.stat")) { while (<$fh>) { $u{cpu_us} = $1 if /^usage_usec (\d+)/ } close $fh }
        $u{tasks} = sys_read1("$cg/pids.current");
        $u{src} = 'cgroup';
    }
    if (!defined $u{mem} || !defined $u{cpu_us}) {
        # no cgroup v2 (container without it, old system): the processes of this program
        my $tck = eval { POSIX::sysconf(POSIX::_SC_CLK_TCK()) } || 100;
        my ($mem, $cpu, $n) = (0, 0, 0);
        opendir(my $d, '/proc') or return \%u;
        for my $p (grep { /^\d+$/ } readdir $d) {
            my @st = stat "/proc/$p" or next;
            next unless $st[4] == $>;
            my $cmd = sys_read1("/proc/$p/cmdline") // next;
            next unless $cmd =~ /mtmon/i;
            my $is_center = $cmd =~ /mtmon-(?:admin-)?center/i;
            next if ($prog // 'mtmon') eq 'mtmon' ? $is_center : !$is_center;
            my $sm = sys_read1("/proc/$p/statm") // next;
            my $s  = sys_read1("/proc/$p/stat") // next;
            $s =~ s/^.*\)\s+//s;                                   # after "pid (name) "
            my @f = split ' ', $s;                                 # f[11..14] = utime stime cutime cstime
            $mem += (split ' ', $sm)[1] * 4096;
            $cpu += $f[11] + $f[12] + $f[13] + $f[14];
            $n++;
        }
        closedir $d;
        %u = (mem => $mem, cache => undef, cpu_us => int($cpu * 1e6 / $tck), tasks => $n, src => 'proc');
    }
    $_ += 0 for grep { defined } @u{qw(mem cache cpu_us tasks)};
    return \%u;
}

sub sys_df {
    my ($dir) = @_;
    my $pid = open(my $p, '-|') // return undef;
    if (!$pid) { open(STDERR, '>', '/dev/null'); exec('df', '-Pk', $dir) or POSIX::_exit(127) }
    my @l = <$p>;
    close $p;
    my @f = split ' ', ($l[-1] // '');
    return undef unless @f >= 6 && $f[1] =~ /^\d+$/;
    return { fs => $f[0], total => $f[1] * 1024, used => $f[2] * 1024, avail => $f[3] * 1024, mount => $f[5] };
}

sub sys_du_walk {
    my ($p) = @_;
    my @st = lstat $p or return 0;
    my $n = ($st[12] // 0) * 512;
    if (-d _) {
        opendir(my $d, $p) or return $n;
        my @e = grep { $_ ne '.' && $_ ne '..' } readdir $d;
        closedir $d;
        $n += sys_du_walk("$p/$_") for @e;
    }
    return $n;
}

sub sys_du {
    my ($root) = @_;
    my (%top, %sub);
    opendir(my $d, $root) or return { top => {}, sub => {} };
    my @e = grep { $_ ne '.' && $_ ne '..' } readdir $d;
    closedir $d;
    for my $e (@e) {
        my $p = "$root/$e";
        my @st = lstat $p or next;
        if (-d _) {
            my $tot = ($st[12] // 0) * 512;
            if (opendir(my $d2, $p)) {
                for my $c (grep { $_ ne '.' && $_ ne '..' } readdir $d2) { my $s = sys_du_walk("$p/$c"); $sub{$e}{$c} = $s; $tot += $s }
                closedir $d2;
            }
            $top{$e} = $tot;
        } else {
            $top{$e} = ($st[12] // 0) * 512;
        }
    }
    return { top => \%top, sub => \%sub };
}

sub server_sample {
    my ($file, $root, $warn, $now, $prog) = @_;
    my $old = jread($file) || {};
    my $u = sys_usage($prog);
    my %s = %$old;
    $s{started} = $^T + 0;
    if (defined $u->{cpu_us} && $old->{cpu_t} && $now > $old->{cpu_t} && $u->{cpu_us} >= ($old->{cpu_us} // 0)) {
        $s{cpu_pct} = sprintf('%.1f', ($u->{cpu_us} - $old->{cpu_us}) / ($now - $old->{cpu_t}) / 1e4) + 0;
        $s{cpu_win} = $now - $old->{cpu_t};
    }
    @s{qw(cpu_t cpu_us)} = ($now + 0, $u->{cpu_us});
    if (!$old->{du_t} || $now - $old->{du_t} >= 600 || $now < $old->{du_t}) {
        my $du = sys_du($root);
        @s{qw(du_t du)} = ($now + 0, $du);
    }
    my $df = sys_df($root);
    $s{df} = $df if $df;
    my $trans;
    if ($df && $df->{total} && $warn) {
        my $free = 100 * $df->{avail} / ($df->{used} + $df->{avail} || 1);
        if ($free < $warn && !$s{low_since})       { $s{low_since} = $now + 0; $trans = 'low' }
        elsif ($free >= $warn + 1 && $s{low_since}) { delete $s{low_since}; $trans = 'ok' }
    } elsif (!$warn) {
        delete $s{low_since};
    }
    return (\%s, $trans, sub { jwrite($file, \%s) });
}

sub server_cpus {
    open(my $fh, '<', '/proc/cpuinfo') or return 1;
    my $n = grep { /^processor\s*:/ } <$fh>;
    return $n || 1;
}

sub server_info {
    my ($file, $root, $warn, $program, $version) = @_;
    my $s = (ref $file ? $file : jread($file)) || {};
    my $u = sys_usage($program);
    my $now = time;
    my %mi;
    if (open(my $fh, '<', '/proc/meminfo')) { while (<$fh>) { $mi{$1} = $2 * 1024 if /^(MemTotal|MemAvailable):\s+(\d+)/ } close $fh }
    my ($load) = split ' ', (sys_read1('/proc/loadavg') // '');
    my ($cpu, $win) = ($s->{cpu_pct}, $s->{cpu_win});
    if (defined $u->{cpu_us} && $s->{cpu_t} && $now - $s->{cpu_t} >= 20 && $u->{cpu_us} >= ($s->{cpu_us} // 0)) {
        $cpu = sprintf('%.1f', ($u->{cpu_us} - $s->{cpu_us}) / ($now - $s->{cpu_t}) / 1e4) + 0;
        $win = $now - $s->{cpu_t};
    }
    my $df = $s->{df} || sys_df($root);
    my $top = ($s->{du} || {})->{top} || {};
    my $tot = 0;
    $tot += $_ for values %$top;
    my @items = server_groups($top);
    return {
        program => $program, version => $version, host => hostname(), started => ($s->{started} // $^T) + 0,
        mem => $u->{mem}, cache => $u->{cache}, tasks => $u->{tasks}, cpu_time => (defined $u->{cpu_us} ? int($u->{cpu_us} / 1e6) : undef),
        cpu_pct => $cpu, cpu_win => $win, cpus => server_cpus(), load => (defined $load ? $load + 0 : undef),
        sys_mem => $mi{MemTotal}, sys_avail => $mi{MemAvailable}, src => $u->{src},
        ($df ? (disk => { %$df, free_pct => ($df->{used} + $df->{avail} ? sprintf('%.1f', 100 * $df->{avail} / ($df->{used} + $df->{avail})) + 0 : undef) }) : ()),
        data => { path => $root, total => $tot, items => \@items, scanned => $s->{du_t} },
        disk_warn => $warn + 0, (($s->{low_since} && $warn) ? (disk_low => $s->{low_since} + 0) : ()),
    };
}

sub server_groups {
    my ($top) = @_;
    my @G = ([ qr/^history/, 'Availability history' ], [ qr/^clientsap/, 'Wi-Fi clients per access point' ], [ qr/^clients/, 'Wi-Fi clients per SSID' ],
             [ qr/^devstats/, 'Device statistics (SNMP)' ], [ qr/^events/, 'Events' ], [ qr/^report-cache/, 'Report cache' ],
             [ qr/^central-queue/, 'Waiting for the centre' ], [ qr/^sites$/, 'Sites' ]);
    my %g;
    for my $f (keys %$top) {
        my ($l) = map { $_->[1] } grep { $f =~ $_->[0] } @G;
        $l //= 'State and settings';
        $g{$l}{bytes} += $top->{$f};
        $g{$l}{files}++;
    }
    return map { { name => $_, bytes => $g{$_}{bytes} + 0, files => $g{$_}{files} } } sort { $g{$b}{bytes} <=> $g{$a}{bytes} || $a cmp $b } keys %g;
}

sub server_print {
    my ($i) = @_;
    my $d = $i->{disk} || {};
    my $up = time - $i->{started};
    printf "%s %s on %s, running for %s\n", $i->{program}, $i->{version}, $i->{host}, fmt_dur($up);
    printf "  Memory     %s%s%s\n", fmt_bytes($i->{mem}), (defined $i->{cache} ? ' (+ ' . fmt_bytes($i->{cache}) . ' file cache)' : ''),
        ($i->{sys_mem} ? ' - server: ' . fmt_bytes($i->{sys_mem}) . ', ' . fmt_bytes($i->{sys_avail}) . ' available' : '');
    printf "  CPU        %s%s, %s in total; server load %s, %d core(s)\n", (defined $i->{cpu_pct} ? "$i->{cpu_pct} % of one core" : 'not measured yet'),
        ($i->{cpu_win} ? ' over the last ' . fmt_dur($i->{cpu_win}) : ''), (defined $i->{cpu_time} ? fmt_dur($i->{cpu_time}) : '-'), $i->{load} // '-', $i->{cpus};
    printf "  Processes  %s\n", $i->{tasks} // '-';
    printf "  Disk       %s: %s free of %s (%s %%)%s\n", $d->{mount} // '?', fmt_bytes($d->{avail}), fmt_bytes(($d->{used} // 0) + ($d->{avail} // 0)), $d->{free_pct} // '?',
        ($i->{disk_warn} ? ", alert below $i->{disk_warn} %" . ($i->{disk_low} ? ' - LOW since ' . fmt_time($i->{disk_low}) : '') : ', alert off');
    printf "  Data       %s: %s%s\n", $i->{data}{path}, fmt_bytes($i->{data}{total}),
        ($i->{data}{scanned} ? ' (counted ' . fmt_time($i->{data}{scanned}) . ')' : ' (not counted yet - the service counts it every 10 min)');
    printf "    %-34s %10s\n", $_->{name}, fmt_bytes($_->{bytes}) for @{ $i->{data}{items} };
    return 0;
}

sub fmt_bytes {
    my ($b) = @_;
    return '-' unless defined $b;
    my @u = ('B', 'kB', 'MB', 'GB', 'TB');
    my $i = 0;
    while ($b >= 1024 && $i < $#u) { $b /= 1024; $i++ }
    return $i ? sprintf($b < 10 ? '%.1f %s' : '%.0f %s', $b, $u[$i]) : "$b B";
}

sub cfg_sec_key {                                       # "[capsman main]" -> "capsman", "[Web Users]" -> "web users"
    my ($name) = @_;
    $name = lc $name;
    $name =~ s/^\s+|\s+$//g;
    return $1 if $name =~ /^(capsman|msm|cnpilot)\b/;
    $name =~ s/[\s_]+/ /g;
    return $name;
}

sub cfg_is_keyline {                                    # "# key = value" (an option), not a sentence
    my ($l) = @_;
    return $1 if $l =~ /^\s*([A-Za-z][\w.:-]*)\s*=/;
    return $1 if $l =~ /^#\s*([a-z][a-z0-9_]*)\s*=\s*(\S+(?:\s+\S+){0,2})\s*$/ && $l !~ /->|:\s/ && length $l < 90;
    return undef;
}

sub cfg_sections {
    my ($lines, $template) = @_;
    my (@sec, $cur);
    for my $i (0 .. $#$lines) {
        my $l = $lines->[$i];
        if ($l =~ /^\s*\[\s*([^\]]+?)\s*\]\s*$/) { $cur = { key => cfg_sec_key($1), head => $i, lines => [] }; push @sec, $cur; next }
        if ($l =~ /^#\s*\[\s*([^\]]+?)\s*\]\s*$/) {
            # an example section that is commented out: part of the template's documentation
            $cur = $template ? { key => cfg_sec_key($1), head => $i, lines => [], commented => 1 } : undef;
            push @sec, $cur if $cur;
            next;
        }
        push @{ $cur->{lines} }, $i if $cur;
    }
    return \@sec;
}

sub config_upgrade {
    my ($file, $tpl, $product, $version, $dry, $list_secs) = @_;
    open(my $fh, '<:raw', $file) or die "Cannot read $file: $!\n";
    my @u = <$fh>; close $fh;
    open($fh, '<:raw', $tpl) or die "Cannot read $tpl: $!\n";
    my @t = <$fh>; close $fh;
    chomp(@u, @t);
    my $crlf = grep { /\r$/ } @u;
    s/\r$// for @u, @t;

    # the template: options per section, each with the comment lines right above it
    my (%topt, %torder, %tsec_head);
    # what the previous template (FILE.dist of the last upgrade) already had is not new: an option
    # you deleted on purpose does not come back
    my %old;
    my $have_dist = -r "$file.dist";
    if (open(my $dh, '<:raw', "$file.dist")) {
        my @d = <$dh>; close $dh; chomp @d; s/\r$// for @d;
        for my $s (@{ cfg_sections(\@d, 1) }) { for my $i (@{ $s->{lines} }) { my $k = cfg_is_keyline($d[$i]); $old{ $s->{key} }{ lc $k } = 1 if defined $k } }
    }
    for my $s (@{ cfg_sections(\@t, 1) }) {
        my @blk;
        $tsec_head{ $s->{key} } //= $s;
        next if $s->{commented} && $s->{key} =~ /^(capsman|msm|cnpilot)$/;     # examples of other ways to connect
        for my $i (@{ $s->{lines} }) {
            my $l = $t[$i];
            if ($l =~ /^\s*$/) { @blk = (); next }
            my $k = cfg_is_keyline($l);
            if (!defined $k) { push @blk, $l; next }
            $k = lc $k;
            if (my $al = $list_secs->{ $s->{key} }) { if (!grep { $_ eq $k } @$al) { @blk = (); next } }
            if (!$topt{ $s->{key} }{$k}) {
                (my $line = $l) =~ s/^\s*(?!#)/# /;           # always commented out: nothing changes until it is set
                $topt{ $s->{key} }{$k} = [ @blk, $line ];
                push @{ $torder{ $s->{key} } }, $k;
            }
            @blk = ();
        }
    }

    # the active config: which options each section has (set or commented out)
    my $usec = cfg_sections(\@u, 0);
    my %have_sec = map { ($_->{key} => 1) } @$usec;
    my (%ins, @added);                                     # line index -> lines to insert after it
    for my $s (@$usec) {
        my %have;
        my $last = $s->{head};                            # after the last option of the section (set or commented out)
        for my $i (@{ $s->{lines} }) {
            my $k = cfg_is_keyline($u[$i]);
            next unless defined $k;
            $have{ lc $k } = 1;
            $last = $i;
        }
        # the repeated sections ([capsman NAME] ...) only get what is new since the previous template
        # (FILE.dist): without it, which of the example options are new is not known
        next if $s->{key} =~ /^(capsman|msm|cnpilot)$/ && !$have_dist;
        my @new = grep { !$have{$_} && !$old{ $s->{key} }{$_} } @{ $torder{ $s->{key} } || [] };
        next unless @new;
        push @{ $ins{$last} }, '', "# --- new in $product $version ---", map { @{ $topt{ $s->{key} }{$_} } } @new;
        push @added, grep { my $x = $_; !grep { $_ eq $x } @added } map { "[$s->{key}] $_" } @new;
    }
    # sections the config does not have at all (not the repeated ones, e.g. [capsman NAME]): at the end,
    # with every option commented out - an empty section means the defaults, as before
    my (@tail, %seen);
    for my $k (grep { !$have_sec{$_} && !/^(capsman|msm|cnpilot)$/ && !$tsec_head{$_}{commented} } map { $_->{key} } grep { !$_->{commented} } @{ cfg_sections(\@t, 1) }) {
        next if $seen{$k}++;
        push @tail, '', "# --- new in $product $version ---", $t[ $tsec_head{$k}{head} ], map { @{ $topt{$k}{$_} } } @{ $torder{$k} || [] };
        push @added, "[$k] (whole section)";
    }

    my @out;
    for my $i (0 .. $#u) { push @out, $u[$i]; push @out, @{ $ins{$i} } if $ins{$i} }
    push @out, @tail;
    # the version line
    my $vl = "# Template from $product $version - keep this line, it shows which version the file belongs to";
    my $old_ver;
    if (my ($i) = grep { $out[$_] =~ /^# Template from \Q$product\E (\S+)/ } 0 .. $#out) { ($old_ver) = $out[$i] =~ /^# Template from \Q$product\E (\S+)/; $out[$i] = $vl }
    else { splice @out, (@out && $out[0] =~ /^#/ ? 1 : 0), 0, $vl }

    my $txt = join("\n", @out) . "\n";
    $txt =~ s/\n/\r\n/g if $crlf;
    my $orig = join("\n", @u) . "\n";
    $orig =~ s/\n/\r\n/g if $crlf;
    return { changed => 0, added => [], old => $old_ver } if $txt eq $orig;
    return { changed => 1, added => \@added, old => $old_ver, text => $txt } if $dry;

    my @st = stat $file;
    my $bak = "$file.bak-" . ($old_ver // 'old');
    $bak .= '-' . strftime('%Y%m%d-%H%M%S', localtime) if -e $bak;
    for my $w ([ $bak, $orig ], [ "$file.dist", join("\n", @t) . "\n" ], [ "$file.new.$$", $txt ]) {
        open(my $o, '>:raw', $w->[0]) or die "Cannot write $w->[0]: $!\n";
        print {$o} $w->[1];
        close $o or die "Writing $w->[0] failed: $!\n";
        chmod $st[2] & 07777, $w->[0];
        chown $st[4], $st[5], $w->[0];
    }
    rename("$file.new.$$", $file) or die "Cannot replace $file: $!\n";
    return { changed => 1, added => \@added, old => $old_ver, backup => $bak, dist => "$file.dist" };
}

sub config_upgrade_cli {
    my ($file, $tpl, $product, $version, $dry, $list_secs) = @_;
    die "--config-upgrade: template $tpl not found (use --template FILE)\n" unless -r $tpl;
    my $r = config_upgrade($file, $tpl, $product, $version, $dry, $list_secs);
    if (!$r->{changed}) { print "$file is up to date (version $version).\n"; return 0 }
    if ($dry) {
        print "Would update $file" . ($r->{old} ? " from version $r->{old}" : '') . " to $version.\n";
        print @{ $r->{added} } ? "New settings (added commented out, with their explanation):\n" . join('', map { "  $_\n" } @{ $r->{added} })
                               : "No new settings - only the version line.\n";
        print "\n--- the file after the upgrade ---\n$r->{text}" if $ENV{MTMON_SHOW};
        return 0;
    }
    print "Updated $file" . ($r->{old} ? " ($r->{old} -> $version)" : " (-> $version)") . ".\n";
    print @{ $r->{added} } ? "New settings, added commented out with their explanation (set them if you need them):\n" . join('', map { "  $_\n" } @{ $r->{added} })
                           : "No new settings - only the version line changed.\n";
    print "The previous file: $r->{backup}\nThe new template:  $r->{dist}\n";
    return 0;
}

