#!/usr/bin/perl
#
# mtmon - MikroTik CAPsMAN (remote CAP access points) and switch availability monitor
#
#  * connects to one or more MikroTik CAPsMAN controllers over SSH with a public
#    key (optionally over the RouterOS API), reads the list of remote-cap devices
#    and records it in a state file (JSON),
#  * on every check compares it with the last state and reports missing /
#    recovered / new access points by e-mail (identity, IP, MAC),
#  * pings a list of switches (any vendor) and reports unreachable ones,
#  * runs as a systemd daemon (interval from the config) or once (--once).
#
# Supported: RouterOS v6 (/caps-man), v7 wifi (/interface/wifi/capsman),
#            v7 wifiwave2 (/interface/wifiwave2/capsman).
#
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 IPC::Open3 qw(open3);
use Symbol ();
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);
use Fcntl qw(:flock);
use File::Basename qw(dirname);
use File::Temp qw(tempfile);
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 HTTP::Tiny;
use POSIX qw(:sys_wait_h);
use Time::Local ();

our $VERSION = '13.13.0';
our ($AGENT, %AGENT_ENV);      # 13.9: mtmon --agent (no disk; config and mails through the centre)
# the mtmon-admin-center this mtmon needs for everything it sends; an older centre takes
# the status and skips what it does not know (--version, --test-central)
our $CENTER_FULL = '6.0.0';
our @CENTER_FEATURES = ([ '4.1.0', 'compressed reports' ], [ '5.1.0', 'Wi-Fi clients per access point' ], [ '6.0.0', 'switch statistics (device report)' ], [ '7.4.0', 'the server of the site (memory, CPU, disk) in the Server view' ], [ '7.6.0', 'ports and VLANs of access points in the device details and on the wall' ], [ '7.13.0', 'mtmon --agent: configuration, mails and state through the centre' ], [ '7.21.0', 'the whole history to the centre (first contact, --central-resend)' ]);
# process name in ps / top / ss / netstat (instead of "perl"); the web server is "mtmon-web"
$0 = 'mtmon';

# remote-cap paths; the one(s) that exist on a device are remembered
my @CAPS_PATHS = (
    '/interface/wifi/capsman/remote-cap',        # RouterOS 7.13+ (wifi)
    '/interface/wifiwave2/capsman/remote-cap',   # RouterOS 7.x wifiwave2 (<7.13)
    '/caps-man/remote-cap',                      # RouterOS 6 / v7 legacy wireless
);
my %PATH_CACHE;   # device name -> [valid paths]

binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';
$| = 1;
STDERR->autoflush(1);    # the :encoding layer buffers - log lines must reach journald at once

my %opt = (config => '/etc/mtmon/mtmon.conf');
GetOptions(\%opt,
    'config|c=s', 'once', 'dry-run|n', 'test-mail', 'show', 'check', 'discover',
    'forget=s', 'reset', 'report', 'web', 'debug|d', 'help|h', 'version|V', 'changelog:s', 'clients', 'hash-password', 'rename-ssid', 'new-api-key=s', 'test-central', 'central-resend',
    'mute=s', 'unmute=s', 'mutes', 'inventory', 'csv', 'certs', 'period-report=s', 'push-list', 'push-remove=s', 'server', 'config-upgrade', 'template=s', 'ap-ports:s', 'topology', 'agent',
) or usage(1);
usage(0) if $opt{help};
if ($opt{version}) {
    print "mtmon $VERSION\n", "with [central]: mtmon-admin-center $CENTER_FULL or newer for everything\n",
          map { sprintf("  needs centre %-7s %s\n", @$_) } @CENTER_FEATURES;
    exit 0;
}
exit show_changelog($opt{changelog}) if defined $opt{changelog};
exit hash_password_cli() if $opt{'hash-password'};
exit new_api_key_cli($opt{'new-api-key'}) if defined $opt{'new-api-key'};
# 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/mtmon.conf.template', 'mtmon', $VERSION, $opt{'dry-run'}, {
    'web users' => [], 'api keys' => [], certificates => [qw(enabled warn_days web check_hours timeout)],
    switches => [qw(title enabled snmp snmp_version community snmp_user snmp_auth_proto snmp_auth_pass snmp_priv_proto snmp_priv_pass snmp_timeout snmp_retries error_rate poe_warn temp_warn)] })
    if $opt{'config-upgrade'};

my $DEBUG   = $opt{debug};
my $running = 1;   # 0 = SIGTERM/SIGINT
my $reload  = 0;   # 1 = SIGHUP
drop_privileges();
# 13.9: the agent takes its configuration from the centre (MTMON_CENTRAL, MTMON_KEY) into MTMON_DATA
$opt{config} = agent_bootstrap() if $opt{agent} || ($ENV{MTMON_AGENT} // '') =~ /^(1|yes|true|on)$/i;
my $cfg = load_config($opt{config});

# --------------------------------------------------------------------------
# CLI commands
# --------------------------------------------------------------------------
if ($opt{'test-mail'}) {
    my $msg = "This is a test message from MT-Mon at $cfg->{general}{location} (host " . hostname() . ").\n"
            . "If you can read it, mail delivery is configured correctly.\n";
    my $html = $cfg->{mail}{format} eq 'html'
        ? html_frame($cfg, time, 'Test message',
              qq{<tr><td style="padding:24px 24px 0 24px;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" }
            . qq{style="background:#e8f5ec;border-left:4px solid #2f855a;border-radius:4px;"><tr><td style="padding:12px 14px;font-size:14px;">}
            . qq{<div style="font-weight:700;color:#2f855a;">Test message</div>}
            . qq{<div style="padding-top:4px;">@{[ h("This is a test message from MT-Mon at $cfg->{general}{location} (host " . hostname() . ").") ]}</div>}
            . qq{<div style="padding-top:4px;color:#5f6b7a;">If you can read it, mail delivery and HTML formatting are configured correctly.</div>}
            . qq{</td></tr></table></td></tr>\n})
        : undef;
    send_mail($cfg, 'Test message', $msg, $html);
    if ($AGENT) { logmsg('info', 'Agent: test message handed to the centre'); exit(central_push($cfg, 1) ? 0 : 2) }
    logmsg('info', 'Test message sent.');
    exit 0;
}
if ($opt{check})  { exit(check_devices($cfg) ? 0 : 2) }
if ($opt{discover}) { exit(discover($cfg) ? 0 : 2) }
if ($opt{clients})  { exit(show_clients($cfg) ? 0 : 2) }
if ($opt{'test-central'}) { exit test_central($cfg) }
if ($opt{'central-resend'}) { exit central_resend_cli($cfg) }
if (defined $opt{mute})   { exit maint_cli($cfg, decode('UTF-8', $opt{mute}), map { decode('UTF-8', $_) } @ARGV) }
if (defined $opt{unmute}) { exit unmute_cli($cfg, decode('UTF-8', $opt{unmute})) }
if ($opt{mutes})          { exit maint_list_cli($cfg) }
if ($opt{'push-list'})    { exit push_list_cli($cfg) }
if (defined $opt{'ap-ports'}) { exit ap_ports_cli($cfg, $opt{'ap-ports'}) }
if ($opt{topology}) { exit topo_cli($cfg) }
if ($opt{server}) {
    my $g = $cfg->{general};
    my $f = data_file($g, 'server.json');
    # the service's last sample; counted now if it has none yet
    my $ss = jread($f);
    $ss = (server_sample($f, dirname($g->{state_file}), 0, time, 'mtmon'))[0] if !$ss || !$ss->{du_t};
    exit server_print(server_info($ss, dirname($g->{state_file}), $g->{disk_warn}, 'mtmon', $VERSION));
}
if (defined $opt{'push-remove'}) { exit push_remove_cli($cfg, $opt{'push-remove'}) }
if ($opt{inventory})      { exit inventory_cli($cfg, $opt{csv}) }
if ($opt{certs})          { exit certs_cli($cfg) }
if (defined $opt{'period-report'}) { exit period_report_cli($cfg, $opt{'period-report'}) }
if ($opt{'rename-ssid'}) {
    die "Usage: mtmon --rename-ssid OLD NEW [CONTROLLER]\n" unless @ARGV >= 2 && @ARGV <= 3;
    exit rename_ssid($cfg, map { decode('UTF-8', $_) } @ARGV);
}
if ($opt{web})      { web_main($cfg) }      # dashboard in the foreground (testing)
if ($opt{report}) { send_report($cfg); exit 0 }
if ($opt{show})   { show_state($cfg); show_maint_tail($cfg); exit 0 }
if ($opt{forget}) { forget_cap($cfg, $opt{forget}); exit 0 }
if ($opt{reset})  { reset_state($cfg);             exit 0 }

if ($opt{once}) {
    my $ok = run_cycle($cfg);
    exit($ok ? 0 : 2);
}

# --------------------------------------------------------------------------
# Daemon loop
# --------------------------------------------------------------------------
$SIG{TERM} = $SIG{INT} = sub { $running = 0 };
$SIG{HUP}  = sub { $reload = 1 };

my $n_msm = grep { $_->{method} eq 'msm' } @{ $cfg->{capsman} };
my $n_cnp = grep { $_->{method} eq 'cnpilot' } @{ $cfg->{capsman} };
logmsg('info', "mtmon $VERSION started for '$cfg->{general}{location}'; interval $cfg->{general}{interval} s, "
    . (@{ $cfg->{capsman} } - $n_msm - $n_cnp) . " CAPsMAN, "
    . ($n_msm ? "$n_msm HP MSM, " : '')
    . ($n_cnp ? "$n_cnp cnPilot group(s), " : '')
    . scalar(@{ $cfg->{switches} }) . " switches");

web_start($cfg);
while ($running) {
    my $t0 = time;
    eval { run_cycle($cfg); 1 } or logmsg('error', "Error in check cycle: $@");

    while ($running && !$reload && time < $t0 + $cfg->{general}{interval}) {
        sleep 1;
        web_check($cfg);
        # 13.5: maintenance set or ended between the checks (on this page or by the centre): report it now
        my $cn = data_file($cfg->{general}, 'central-now');
        if (-e $cn) {
            unlink $cn;
            eval { central_push($cfg) if $cfg->{central}{enabled}; 1 } or logmsg('debug', "Central: report after maintenance failed: $@");
        }
    }
    if ($reload) {
        $reload = 0;
        my $new = eval { load_config($opt{config}) };
        if ($new) { $cfg = $new; logmsg('info', 'Configuration reloaded.') }
        else      { logmsg('error', "Configuration reload failed, keeping the previous one: $@") }
        web_stop();
        web_start($cfg);
    }
}
web_stop();
logmsg('info', 'mtmon stopped.');
exit 0;

# ==========================================================================
# Main cycle
# ==========================================================================
sub run_cycle {
    my ($cfg) = @_;
    my $g   = $cfg->{general};
    my $now = time;
    my $dry = $opt{'dry-run'};

    my $lock  = lock_state($cfg);
    my $state = load_state($g->{state_file});
    $state->{capsman}  ||= {};
    $state->{switches} ||= {};

    # maintenance windows: the ones that are over are removed, the active ones mute their targets
    eval { maint_prune($cfg, $now) unless $dry; 1 } or logmsg('warn', "Maintenance windows: $@");
    my $M = eval { maint_ctx($cfg, $now) } || { now => $now, list => [] };
    local $cfg->{_M} = $M;
    local $g->{_M} = $M;
    local $g->{_inv_due} = inventory_due($cfg, $now);
    # 13.6: what is behind what (topology.json) and what is down in this check
    local $g->{_T} = topo_load($g);
    local $g->{_down} = {};
    local $g->{_dep} = [];
    local $g->{_depn} = {};

    my (@sections, @silent, @subject);

    # One common reminder for everything still missing / unreachable: at most one
    # per remind_hours, due once the oldest outstanding problem is remind_hours old.
    local $g->{_remind_due} = 0;
    local $g->{_reminded}   = 0;
    if ($g->{remind_hours}) {
        my $R = $g->{remind_hours} * 3600;
        my @since = (
            (map { $_->{hidden} ? () : ($_->{missing_since} // ()) } map { values %{ $_->{caps} || {} } } values %{ $state->{capsman} }),
            (map { $_->{muted} || $_->{hidden} ? () : ($_->{down_since} // ()) } values %{ $state->{switches} }),
        );
        my ($oldest) = sort { $a <=> $b } @since;
        $g->{_remind_due} = 1
            if defined $oldest && $now - $oldest >= $R && $now - ($state->{last_reminder} || 0) >= $R;
    }

    # ---- Switches first (13.6): an access point or a controller behind a switch that is down is not reported on its own
    my ($sw_sec, $sw_sil);
    my @sw = @{ $cfg->{switches} };
    if (@sw) {
        ($sw_sec, $sw_sil) = process_switches($g, \@sw, $state->{switches}, $now, \@subject);
    } else {
        %{ $state->{switches} } = ();
    }
    return 0 if interrupted();
    $g->{_down}{"ctl:$_->{name}"} = 1 for grep { ($state->{capsman}{ $_->{name} } || {})->{down_since} } @{ $cfg->{capsman} };

    # ---- CAPsMAN ---------------------------------------------------------
    my %cm_in_conf;
    my @answered;     # [cm, result] of the controllers that answered (for the Wi-Fi clients)
    for my $cm (@{ $cfg->{capsman} }) {
        return 0 if interrupted();
        my $name = $cm->{name};
        $cm_in_conf{$name} = 1;
        my $cs = $state->{capsman}{$name} ||= { caps => {}, fails => 0 };
        my $mu = m_ctl($M, $cm);
        my %head = (title => dev_title($cm, $cs), heading => dev_heading($cm), label => $cm->{label}, name => $name, host => $cm->{host});

        my $res = eval { fetch_caps($cm) };
        return 0 if interrupted();
        if (!$res) {
            my $err = $@ || 'unknown error';
            chomp $err;
            $cs->{fails}++;
            $g->{_down}{"ctl:$name"} = 1;
            my $dep = $mu ? undef : dep_behind($g, "ctl:$name");
            logmsg('warn', "$cm->{label} '$name' ($cm->{host}): $err (consecutive failures: $cs->{fails})" . ($dep ? " - behind $dep, which is down" : ''));
            if (!$cs->{down_since} && $cs->{fails} >= $g->{fail_threshold}) {
                $cs->{down_since} = $now;
                my $sec = { type => 'cm_down', %head, identity => $cs->{identity}, err => $err };
                if ($mu)     { $cs->{down_hidden} = 1; push @silent, { %$sec, maint => 1 } }
                elsif ($dep) { $cs->{down_hidden} = 'dep'; $cs->{behind} = $dep; push @silent, { %$sec, behind => $dep };
                               push @{ $g->{_dep} }, { behind => $dep, kind => $cm->{label} // 'controller', name => $head{heading} // $name, ip => $cm->{host} } }
                else         { push @sections, $sec; push @subject, "$cm->{label} $name unreachable" }
            } elsif ($cs->{down_since} && $cs->{down_hidden} && !$mu) {
                if ($dep) { $cs->{down_hidden} = 'dep'; $cs->{behind} = $dep; next }
                # went down during a maintenance window that is over now / the device in front of it is back
                my $was = $cs->{down_hidden};
                delete @$cs{qw(down_hidden behind)};
                push @sections, { type => 'cm_down', ($was eq 'dep' ? (after_dep => 1) : (after_maint => 1)), %head, identity => $cs->{identity}, err => $err };
                push @subject, "$cm->{label} $name still unreachable" . ($was eq 'dep' ? '' : ' after maintenance');
            }
            next;
        }

        my $caps = $res->{caps};
        push @answered, [ $cm, $res ];
        delete $g->{_down}{"ctl:$name"};
        $cs->{identity} = $res->{identity} if defined $res->{identity} && length $res->{identity};

        if ($cs->{down_since}) {
            my $sec = { type => 'cm_up', %head, title => dev_title($cm, $cs), identity => $cs->{identity}, since => $cs->{down_since} };
            my $bh = delete $cs->{behind};
            if (my $hd = delete $cs->{down_hidden}) { push @silent, { %$sec, ($hd eq 'dep' ? (behind => $bh) : (maint => 1)) } }
            else { push @sections, $sec; push @subject, "$cm->{label} $name OK again" }
        }
        $cs->{fails} = 0;
        delete $cs->{down_since};

        # CAPsMAN log: disconnect lines for the flapping detection (MikroTik only)
        my $logd;
        if ($g->{flap_count} && $g->{flap_log} && !is_snmp_ctl($cm)) {
            my $lines = eval { fetch_caps_log($cm) };
            if ($lines) { $logd = log_drops($cs, $lines, { %{ $cs->{caps} || {} }, %$caps }) }
            else        { logmsg('debug', "$cm->{label} '$name': CAPsMAN log not readable: " . ($@ =~ s/\s+$//r)) }
            return 0 if interrupted();
        }

        logmsg('debug', "$cm->{label} '$name': " . scalar(keys %$caps) . ($cm->{method} eq 'msm' ? " running AP" : $cm->{method} eq 'cnpilot' ? " AP(s) answering" : " remote-cap"));
        my ($sec, $sil) = process_caps($g, $cm, $cs, $caps, $now, \@subject, $logd);
        push @sections, $sec if $sec;
        push @silent, $sil if $sil;
    }
    delete $state->{capsman}{$_} for grep { !$cm_in_conf{$_} } keys %{ $state->{capsman} };

    return 0 if interrupted();

    # ---- Switches (checked above, in the mail after the controllers) ------
    push @sections, $sw_sec if $sw_sec;
    push @silent, $sw_sil if $sw_sil;

    # ---- Certificates (once per check_hours) -----------------------------
    my $cert_commit;
    if (!$dry) {
        my ($csec, $csil);
        my $ok = eval { ($csec, $csil, $cert_commit) = certs_cycle($cfg, $now, \@subject); 1 };
        logmsg('warn', "Certificates: $@") unless $ok;
        push @sections, $csec if $csec;
        push @silent, $csil if $csil;
    }

    # ---- this server: memory / CPU sample, folder sizes, free disk space --
    my $srv_commit;
    if (!$dry) {
        my ($ss, $tr);
        my $ok = eval { ($ss, $tr, $srv_commit) = server_sample(data_file($g, 'server.json'), dirname($g->{state_file}), $g->{disk_warn}, $now, 'mtmon'); 1 };
        logmsg('warn', "Server sample: $@") unless $ok;
        if ($tr) {
            push @sections, server_section($ss, $tr, $g->{disk_warn}, dirname($g->{state_file}));
            push @subject, $tr eq 'low' ? 'Disk almost full on ' . hostname() : 'Disk space OK again on ' . hostname();
        }
    }

    $state->{last_reminder} = $now if $g->{_reminded};
    $state->{last_check}    = $now;

    # ---- 13.6: what is not reported on its own because a device in front of it is down - in the mail
    # (and the push) of that device: everything now behind each device this mail reports as down
    if (@sections) {
        my %cause;
        my $ck = sub { my ($n, $ip) = @_; $ip //= ''; $ip =~ s/:\d+$//; ($n // '') . (length $ip && $ip ne ($n // '') ? " ($ip)" : '') };
        for my $sec (@sections) {
            $cause{ $ck->($sec->{heading} // $sec->{name}, $sec->{host}) } = 1 if $sec->{type} eq 'cm_down';
            for my $gr (@{ $sec->{groups} || [] }) {
                next unless $gr->{kind} =~ /^(missing|down)/;
                $cause{ $ck->($_->{desc} // $_->{identity} // $_->{name}, $_->{host} // $_->{ip}) } = 1 for @{ $gr->{items} };
            }
        }
        my %seen;
        my @dl = grep { !$seen{"$_->{behind}|$_->{name}|" . ($_->{ip} // '')}++ } (@{ $g->{_dep} }, grep { $cause{ $_->{behind} } } dep_all($cfg, $state));
        if (@dl) {
            push @sections, { type => 'dep', items => \@dl };
            push @subject, '+' . scalar(@dl) . ' behind it';
            $g->{_depn}{ $_->{behind} }++ for @dl;
        }
    }

    # ---- Mail + save state ----------------------------------------------
    if (@sections) {
        my $subj = join(' | ', @subject) || 'Status change';
        my $text = render_text($g, $now, \@sections);
        my $html = $cfg->{mail}{format} eq 'html' ? render_html($cfg, $now, \@sections, $subj) : undef;

        my $sent = eval { send_mail($cfg, $subj, $text, $html); 1 };
        if (!$sent) {
            # state is not saved -> the next cycle detects the events again and retries
            logmsg('error', "Sending mail failed, state not saved: $@");
            return 0;
        }
        logmsg('info', "Report sent: $subj");
    }

    if ($dry) {
        logmsg('info', 'Dry run: state not saved.');
    } else {
        save_state($g->{state_file}, $state);
        eval { $cert_commit->() if $cert_commit; 1 } or logmsg('warn', "Writing certificates.json failed: $@");
        eval { $srv_commit->() if $srv_commit; 1 } or logmsg('warn', "Writing server.json failed: $@");
        eval { record_events($g, \@sections, $now, \@silent); record_history($cfg, $state, $now); 1 }
            or logmsg('warn', "Writing dashboard history failed: $@");
    }
    close $lock;
    return 1 if $dry;
    # 13.4.2: something happened - the centre gets it right now (its push to the phones), not only after
    # the Wi-Fi clients, the inventory and the ports of the access points have been read (that can take minutes)
    if ($cfg->{central}{enabled} && (@sections || @silent)) {
        eval { central_push($cfg) } or logmsg('debug', 'Central: early report failed' . ($@ ? ": $@" : ''));
    }
    # inventory (models, versions; the controllers are asked once per inventory_hours)
    eval { inventory_build($cfg, $state, $now, $g->{_inv_due}); 1 } or logmsg('warn', "Inventory: $@");
    # Wi-Fi clients for the dashboard - after the check, outside the state lock
    if (grep { client_enabled($cfg, $_) } @{ $cfg->{capsman} }) {
        eval { collect_clients($cfg, \@answered, $now); 1 } or logmsg('warn', "Wi-Fi clients: $@");
    }
    # ports and VLANs of the access points (every ap_ports_minutes)
    eval { ap_ports_collect($cfg, $state, $now); 1 } or logmsg('warn', "AP ports: $@");
    # status to the mtmon-admin-center (never affects the check itself)
    if ($cfg->{central}{enabled}) {
        my $pushed = eval { central_push($cfg) };
        logmsg('warn', "Central: $@") if $@;
        eval { central_resend_run($cfg); 1 } or logmsg('warn', "Central: history: $@") if $pushed;
    }
    # weekly / monthly report
    eval { report_check($cfg, time); 1 } or logmsg('warn', "Report: $@");
    # 13.6: what is behind what - every topology_hours, in the background
    eval { topo_maybe($cfg, time); 1 } or logmsg('warn', "Topology: $@");
    return 1;
}

sub inventory_due {
    my ($cfg, $now) = @_;
    my $h = $cfg->{general}{inventory_hours} or return 0;
    my $i = jread(data_file($cfg->{general}, 'inventory.json')) || {};
    return $now - ($i->{refreshed} // 0) >= $h * 3600 ? 1 : 0;
}

# SIGHUP/SIGTERM during a cycle: the cycle is aborted without saving state,
# so the interruption is not counted as a device failure
sub interrupted {
    return 0 if $running && !$reload;
    logmsg('info', $reload ? 'SIGHUP received - aborting current check, reloading configuration.'
                           : 'Stopping - aborting current check.');
    return 1;
}

# --------------------------------------------------------------------------
# Compare access points with the last state -> (mail section, silent section)
# The silent one carries what is only recorded as events (maintenance, flapping ended, ...)
# --------------------------------------------------------------------------
sub process_caps {
    my ($g, $cm, $cs, $caps, $now, $subject, $logd) = @_;
    my $M = $g->{_M} || { list => [] };
    my $known = $cs->{caps} ||= {};
    my $first = !$cs->{initialized};

    my $count_active = sub { scalar grep { !$known->{$_}{missing_since} } keys %$known };
    my $prev = $count_active->();

    my (@missing, @back, @new, @remind, @am, @ad, @flap);            # mailed
    $g->{_down}{"ap:$cm->{name}:$_"} = 1 for grep { !$caps->{$_} } keys %$known;   # 13.6
    my (@s_missing, @s_back, @s_new, @s_flap, @flap_end, @forgot);   # events only
    my %raw;                                                          # missed in this check, after being seen

    # access points currently present
    for my $k (keys %$caps) {
        my $c = $caps->{$k};
        if (my $e = $known->{$k}) {
            # 13.5.2: back while still muted - not mailed, and not pushed either (maint)
            if ($e->{missing_since}) {
                my $bh = delete $e->{behind};
                if (my $hd = delete $e->{hidden}) { push @s_back, { %$e, ($hd eq 'dep' ? (behind => $bh) : (_maint => 1)) } } else { push @back, { %$e } }
            }
            $e->{$_} = $c->{$_} for keys %$c;
            $e->{last_seen}  = $now;
            $e->{miss_count} = 0;
            delete @$e{qw(missing_since last_alert)};
        } else {
            $known->{$k} = { %$c, first_seen => $now, last_seen => $now, miss_count => 0 };
            push @{ m_ap($M, $cm, $c) ? \@s_new : \@new }, $known->{$k} unless $first;
        }
    }

    # missing access points
    for my $k (keys %$known) {
        next if $caps->{$k};
        my $e = $known->{$k};
        my $mu = m_ap($M, $cm, $e);
        my $dep = $mu ? undef : dep_behind($g, "ap:$cm->{name}:$k");
        if ($e->{missing_since}) {
            if ($g->{forget_after_days}
                && $now - $e->{missing_since} >= $g->{forget_after_days} * 86400) {
                logmsg('info', "$cm->{label} '$cm->{name}': forgetting access point $e->{identity} ($k), "
                             . "missing for more than $g->{forget_after_days} days");
                push @forgot, { %$e };
                delete $known->{$k};
                next;
            }
            if ($e->{hidden} && !$mu && $dep) { @$e{qw(hidden behind)} = ('dep', $dep); next }   # 13.6: still behind a device that is down
            if ($e->{hidden} && !$mu) {                   # went missing during maintenance, still missing after it
                my $was = delete $e->{hidden};            # (13.6: or the device in front of it is back, this one is not)
                delete $e->{behind};
                $e->{last_alert} = $now;
                push @{ $was eq 'dep' ? \@ad : \@am }, $e;
                next;
            }
            if ($g->{_remind_due} && !$e->{hidden} && !$mu) {
                $e->{last_alert} = $now;
                push @remind, $e;
                $g->{_reminded}++;
            }
            next;
        }
        $e->{miss_count}++;
        $raw{$k} = 1 if $e->{miss_count} == 1;
        if ($e->{miss_count} >= $g->{cap_miss_threshold}) {
            $e->{missing_since} = $now;
            $e->{last_alert}    = $now;
            if ($mu)     { $e->{hidden} = 1; push @s_missing, $e }
            elsif ($dep) { @$e{qw(hidden behind)} = ('dep', $dep); push @s_missing, $e;
                           push @{ $g->{_dep} }, { behind => $dep, kind => 'access point', name => $e->{identity} || $e->{ip} || $k, ip => $e->{ip} } }
            else         { push @missing, $e }
        }
    }

    # flapping: drops from the CAPsMAN log (when readable) or missed checks
    for my $k (sort keys %$known) {
        my $e = $known->{$k};
        my $n = $raw{$k} ? 1 : 0;                        # a missed check, or more disconnects in the log
        $n = $logd->{$k} if $logd && ($logd->{$k} // 0) > $n;
        my $r = flap_track($g, $e, $n, $now) or next;
        my $item = { %$e, flap_text => ($e->{flap_n} // 0) . " drops in $g->{flap_window} min" };
        if ($r eq 'start') { push @{ m_ap($M, $cm, $e) ? \@s_flap : \@flap }, $item }
        else { push @flap_end, $item }
    }

    $cs->{initialized} = 1;
    my $cur      = $count_active->();
    my $miss_all = scalar(keys %$known) - $cur;
    my %sec = (type => 'caps', title => dev_title($cm, $cs), heading => dev_heading($cm), label => $cm->{label}, col4 => col4($cm),
               name => $cm->{name}, host => $cm->{host}, identity => $cs->{identity});

    if (!$g->{notify_new_caps}) { push @s_new, @new; @new = () }
    if (!$g->{notify_recovery}) { push @s_back, @back; @back = () }
    my @sg;
    push @sg, { kind => 'missing',  maint => 1, items => [ map { { %$_ } } @s_missing ] } if @s_missing;
    push @sg, { kind => 'back',     items => [ map { { %$_ } } @s_back ] } if @s_back;
    push @sg, { kind => 'new',      items => [ map { { %$_ } } @s_new ] } if @s_new;
    push @sg, { kind => 'flap',     maint => 1, items => \@s_flap } if @s_flap;
    push @sg, { kind => 'flap_end', items => \@flap_end } if @flap_end;
    push @sg, { kind => 'forgot',   items => \@forgot } if @forgot;
    my $silent = @sg ? { %sec, groups => \@sg } : undef;

    if ($first) {
        push @$subject, "$cm->{name}: baseline $cur APs";
        return ({ %sec, first => 1, cur => $cur, list => [ map { { %$_ } } values %$known ] }, $silent);
    }
    return (undef, $silent) unless @missing || @back || @new || @remind || @am || @ad || @flap;

    my @groups;
    if (@missing) {
        push @$subject, "$cm->{name}: " . scalar(@missing) . " AP missing";
        push @groups, { kind => 'missing', items => [ map { { %$_ } } @missing ] };
    }
    if (@am) {
        push @$subject, "$cm->{name}: " . scalar(@am) . " AP still missing after maintenance";
        push @groups, { kind => 'missing_am', items => [ map { { %$_ } } @am ] };
    }
    if (@ad) {
        push @$subject, "$cm->{name}: " . scalar(@ad) . " AP still missing";
        push @groups, { kind => 'missing_ad', items => [ map { { %$_ } } @ad ] };
    }
    if (@remind) {
        push @$subject, "$cm->{name}: " . scalar(@remind) . " AP still missing";
        push @groups, { kind => 'remind', items => [ map { { %$_ } } @remind ] };
    }
    if (@flap) {
        push @$subject, "$cm->{name}: " . scalar(@flap) . " AP unstable";
        push @groups, { kind => 'flap', items => \@flap };
    }
    if (@back) {
        push @$subject, "$cm->{name}: " . scalar(@back) . " AP back";
        push @groups, { kind => 'back', items => \@back };
    }
    if (@new) {
        push @$subject, "$cm->{name}: " . scalar(@new) . " new AP";
        push @groups, { kind => 'new', items => [ map { { %$_ } } @new ] };
    }
    return ({ %sec, prev => $prev, cur => $cur, miss_all => $miss_all, groups => \@groups }, $silent);
}

# ==========================================================================
# Report rendering (text and HTML from the same data)
# ==========================================================================
# group kind -> label, time column, colour
my (%GROUP, %TIME_LABEL, $FONT, $TD, $MONO);
BEGIN {   # set at compile time: the main program runs before this point in the file
%GROUP = (
    missing => { text => 'MISSING ACCESS POINTS',      html => 'Missing access points',  time => 'last_seen',     color => '#c53030' },
    remind  => { text => 'STILL MISSING - reminder',   html => 'Still missing - reminder', time => 'last_seen',   color => '#b7791f' },
    back    => { text => 'ACCESS POINTS BACK ONLINE',  html => 'Back online',            time => 'missing_since', color => '#2f855a' },
    new     => { text => 'NEW ACCESS POINTS',          html => 'New access points',      time => undef,           color => '#2b6cb0' },
    down    => { text => 'NOT RESPONDING',             html => 'Not responding',         time => 'last_ok',       color => '#c53030' },
    sremind => { text => 'STILL UNREACHABLE - reminder', html => 'Still unreachable - reminder', time => 'last_ok', color => '#b7791f' },
    up      => { text => 'REACHABLE AGAIN',            html => 'Reachable again',        time => 'down_since',    color => '#2f855a' },
    # baseline (first run / after --reset)
    b_down    => { text => 'NOT RESPONDING', html => 'Not responding', time => 'last_ok', color => '#c53030' },
    b_ok      => { text => 'RESPONDING',     html => 'Responding',     time => 'last_ok', color => '#1f3a5f' },
    # --report
    r_missing => { text => 'MISSING',     html => 'Missing',     time => 'last_seen',     color => '#c53030' },
    r_online  => { text => 'ONLINE',      html => 'Online',      time => undef,           color => '#2f855a' },
    r_down    => { text => 'UNREACHABLE', html => 'Unreachable', time => 'down_since',    color => '#c53030' },
    r_ok      => { text => 'OK',          html => 'OK',          time => 'last_ok',       color => '#2f855a' },
    # 11.0: maintenance, flapping, switch ports (SNMP), certificates
    missing_am => { text => 'STILL MISSING AFTER MAINTENANCE', html => 'Still missing after maintenance', time => 'last_seen', color => '#c53030' },
    down_am    => { text => 'STILL NOT RESPONDING AFTER MAINTENANCE', html => 'Still not responding after maintenance', time => 'last_ok', color => '#c53030' },
    # 13.6: was behind a device that was down; that one is back, this one is not
    missing_ad => { text => 'STILL MISSING - THE DEVICE IN FRONT OF IT IS BACK', html => 'Still missing - the device in front of it is back', time => 'last_seen', color => '#c53030' },
    down_ad    => { text => 'STILL NOT RESPONDING - THE DEVICE IN FRONT OF IT IS BACK', html => 'Still not responding - the device in front of it is back', time => 'last_ok', color => '#c53030' },
    flap       => { text => 'UNSTABLE - DROPPING AGAIN AND AGAIN', html => 'Unstable (flapping)', time => 'flap_text', color => '#b7791f' },
    dflap      => { text => 'UNSTABLE - DROPPING AGAIN AND AGAIN', html => 'Unstable (flapping)', time => 'flap_text', color => '#b7791f' },
    port       => { text => 'PORT / SNMP PROBLEMS', html => 'Port and SNMP problems', time => 'text', color => '#c53030', cols => [ 'Address', 'Device', 'Problem' ] },
    portok     => { text => 'RESOLVED',             html => 'Resolved',               time => 'text', color => '#2f855a', cols => [ 'Address', 'Device', 'Was' ] },
    reboot     => { text => 'RESTARTED',            html => 'Restarted',              time => 'text', color => '#2b6cb0', cols => [ 'Address', 'Device', 'Note' ] },
    c_exp      => { text => 'CERTIFICATES EXPIRING', html => 'Expiring certificates', time => 'text', color => '#c53030', cols => [ 'Certificate', 'Where', 'Status' ], certs => 1 },
    c_ren      => { text => 'CERTIFICATES RENEWED',  html => 'Renewed certificates',  time => 'text', color => '#2f855a', cols => [ 'Certificate', 'Where', 'Status' ], certs => 1 },
    # 13.3: this server
    d_low      => { text => 'DISK ALMOST FULL',      html => 'Disk almost full',      time => 'text', color => '#c53030', cols => [ 'Server', 'Disk', 'Free' ], certs => 1 },
    d_ok       => { text => 'DISK SPACE OK AGAIN',   html => 'Disk space OK again',   time => 'text', color => '#2f855a', cols => [ 'Server', 'Disk', 'Free' ], certs => 1 },
);
%TIME_LABEL = (last_seen => 'Last seen', missing_since => 'Missing since',
               last_ok => 'Last reply', down_since => 'Unreachable since', flap_text => 'Drops', text => 'Problem');
# HTML for mail clients: table layout and inline styles only (Outlook renders
# HTML with the Word engine and ignores most modern CSS)
$FONT = "font-family:Segoe UI,Arial,Helvetica,sans-serif;";
$TD   = "padding:7px 8px;";
$MONO = "font-family:Consolas,Menlo,monospace;font-size:12px;";
}

sub by_identity { sort { lc($a->{identity} // '') cmp lc($b->{identity} // '') } @_ }

# value of the last table column: a time, or a text (flapping, port problem, certificate)
sub tcell {
    my ($x, $f) = @_;
    return $x->{state} || '-' unless $f;
    return $x->{$f} // '-' if $f eq 'text' || $f eq 'flap_text';
    return fmt_time($x->{$f});
}
# rows of a 3-column group: switches (address, description) or certificates (name, target)
sub row3 { my ($G, $x) = @_; return $G->{certs} ? ($x->{name}, $x->{target}) : ($x->{host}, $x->{desc}) }

# ---- text -----------------------------------------------------------------
sub render_text {
    my ($g, $now, $sections) = @_;
    my @out;
    for my $s (@$sections) {
        if ($s->{type} eq 'cm_down') {
            push @out, "$s->{title} IS " . ($s->{after_maint} ? "STILL UNREACHABLE AFTER THE MAINTENANCE WINDOW" : $s->{after_dep} ? "STILL UNREACHABLE (THE DEVICE IN FRONT OF IT IS BACK)" : "UNREACHABLE") . "\n"
                     . "  Error: $s->{err}\n"
                     . "  Access point status could not be checked.\n";
        } elsif ($s->{type} eq 'cm_up') {
            push @out, "$s->{title} is reachable again (unreachable since " . fmt_time($s->{since}) . ").\n";
        } elsif ($s->{type} eq 'caps' && $s->{first}) {
            push @out, "$s->{title}\n"
                     . "  First run - baseline recorded: $s->{cur} active access points.\n\n"
                     . cap_table($s->{list}, undef, $s->{col4});
        } elsif ($s->{type} eq 'caps') {
            my $diff = $s->{cur} - $s->{prev};
            my $o = "$s->{title}\n"
                  . sprintf("  Active access points: before %d, now %d (%s%d)", $s->{prev}, $s->{cur}, ($diff >= 0 ? '+' : ''), $diff)
                  . ($s->{miss_all} ? ", $s->{miss_all} missing in total" : '') . "\n\n";
            for my $gr (@{ $s->{groups} }) {
                my $G = $GROUP{ $gr->{kind} };
                $o .= "  $G->{text} (" . scalar(@{ $gr->{items} }) . "):\n" . cap_table($gr->{items}, $G->{time}, $s->{col4}) . "\n";
            }
            push @out, $o;
        } elsif ($s->{type} eq 'dep') {
            my %by;
            push @{ $by{ $_->{behind} } }, $_ for @{ $s->{items} };
            my $o = "NOT REACHABLE BEHIND A DEVICE THAT IS DOWN (" . scalar(@{ $s->{items} }) . ") - not reported one by one\n";
            for my $bh (sort keys %by) {
                $o .= "\n  behind $bh:\n";
                $o .= sprintf("    %-30s %-15s %s\n", $_->{name} // '-', $_->{ip} // '', $_->{kind}) for sort { lc($a->{name} // '') cmp lc($b->{name} // '') } @{ $by{$bh} };
            }
            push @out, $o;
        } elsif ($s->{type} eq 'switches' || $s->{type} eq 'certs' || $s->{type} eq 'server') {
            my $fmt = "    %-15s %-34s %s\n";
            my $o = ($s->{heading} // "SWITCHES / DEVICES (ping)") . "\n"
                  . ($s->{first} ? "  First run - baseline recorded: $s->{count} devices, $s->{ok} responding.\n" : '') . "\n";
            for my $gr (@{ $s->{groups} }) {
                my $G = $GROUP{ $gr->{kind} };
                my @h = @{ $G->{cols} || [ 'Address', 'Description', $TIME_LABEL{ $G->{time} } ] };
                my $f = $G->{certs} ? "    %-24s %-34s %s\n" : $fmt;
                $o .= "  $G->{text} (" . scalar(@{ $gr->{items} }) . "):\n" . sprintf($f, @h);
                $o .= sprintf($f, row3($G, $_), tcell($_, $G->{time})) for @{ $gr->{items} };
                $o .= "\n";
            }
            push @out, $o;
        }
    }
    return "MT-Mon report $g->{location}, " . fmt_time($now) . "\n"
         . ('=' x 72) . "\n\n"
         . join("\n" . ('-' x 72) . "\n\n", @out);
}

# 4th table column: model for CAPsMAN, location for HP MSM
sub col4 { (($_[0] || {})->{method} // '') eq 'msm' ? 'Location' : 'Model' }

sub cap_table {
    my ($list, $timefield, $col4) = @_;
    my $out = sprintf("    %-26s %-15s %-17s %-14s %s\n",
        'Identity', 'IP', 'MAC', ($col4 // 'Model'), ($timefield ? $TIME_LABEL{$timefield} : 'State'));
    for my $c (by_identity(@$list)) {
        $out .= sprintf("    %-26s %-15s %-17s %-14s %s\n",
            $c->{identity} || '-', $c->{ip} || '-', $c->{mac} || '-', $c->{board} || '-', tcell($c, $timefield));
    }
    return $out;
}

# ---- HTML -----------------------------------------------------------------

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

sub html_frame {
    my ($cfg, $now, $subject, $content, $kicker, $timelabel) = @_;
    $kicker //= 'MT-Mon report';
    $timelabel = defined $timelabel ? "$timelabel " : '';
    my $g   = $cfg->{general};
    my $int = $g->{interval} % 60 ? "$g->{interval} s" : ($g->{interval} / 60) . " min";
    return <<"HTML";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@{[ h($subject) ]}</title>
</head>
<body style="margin:0;padding:0;background:#eef1f4;">
<div style="display:none;max-height:0;overflow:hidden;">@{[ h($subject) ]}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#eef1f4;">
<tr><td align="center" style="padding:24px 12px;">
<table role="presentation" width="640" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:640px;background:#ffffff;border-radius:8px;${FONT}color:#1f2933;">
<tr><td style="background:#1f3a5f;border-radius:8px 8px 0 0;padding:20px 24px;">
<div style="font-size:12px;letter-spacing:1px;color:#9fb3c8;text-transform:uppercase;">@{[ h($kicker) ]}</div>
<div style="font-size:22px;font-weight:600;color:#ffffff;padding-top:2px;">@{[ h($g->{location}) ]}</div>
<div style="font-size:13px;color:#c5d3e0;padding-top:4px;">$timelabel@{[ fmt_time($now) ]} &nbsp;&middot;&nbsp; check every $int</div>
</td></tr>
$content
<tr><td style="padding:24px;font-size:11px;color:#8a96a3;">
<div style="border-top:1px solid #e4e8ec;padding-top:12px;">mtmon $VERSION on @{[ h(hostname()) ]} &nbsp;&middot;&nbsp; <span style="$MONO">mtmon --show</span> for full status</div>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>
HTML
}

sub render_html {
    my ($cfg, $now, $sections, $subject) = @_;

    # summary tiles
    my %n = map { $_ => 0 } qw(missing down cmdown msmdown cnpdown back new base sbase unstable port reboot cert disk resolved);
    for my $s (@$sections) {
        $n{ { 'HP MSM' => 'msmdown', cnPilot => 'cnpdown' }->{ $s->{label} // '' } // 'cmdown' }++ if $s->{type} eq 'cm_down';
        $n{back}++   if $s->{type} eq 'cm_up';
        $n{base} += $s->{cur} if $s->{type} eq 'caps' && $s->{first};
        $n{sbase} += $s->{count} if $s->{type} eq 'switches' && $s->{first};
        for my $gr (@{ $s->{groups} || [] }) {
            my $c = scalar @{ $gr->{items} };
            my $k = { missing => 'missing', remind => 'missing', missing_am => 'missing', missing_ad => 'missing', down => 'down', sremind => 'down', down_am => 'down', down_ad => 'down',
                      back => 'back', up => 'back', new => 'new', flap => 'unstable', dflap => 'unstable', port => 'port',
                      reboot => 'reboot', c_exp => 'cert', c_ren => 'resolved', portok => 'resolved', d_low => 'disk', d_ok => 'resolved' }->{ $gr->{kind} } or next;   # baseline groups: own tile
            $n{$k} += $c;
        }
    }
    my @tiles = grep { $_->[0] } (
        [ $n{missing}, 'APs missing',          '#c53030', '#fdecec' ],
        [ $n{down},    'switches down',        '#c53030', '#fdecec' ],
        [ $n{cmdown},  'CAPsMAN unreachable',  '#c53030', '#fdecec' ],
        [ $n{msmdown}, 'HP MSM unreachable',   '#c53030', '#fdecec' ],
        [ $n{cnpdown}, 'cnPilot APs silent',   '#c53030', '#fdecec' ],
        [ $n{port},    'port / SNMP problems', '#c53030', '#fdecec' ],
        [ $n{unstable},'unstable (flapping)',  '#b7791f', '#fdf6e3' ],
        [ $n{cert},    'certificates expiring','#c53030', '#fdecec' ],
        [ $n{disk},    'disk almost full',     '#c53030', '#fdecec' ],
        [ $n{back},    'back online',          '#2f855a', '#e8f5ec' ],
        [ $n{resolved},'resolved',             '#2f855a', '#e8f5ec' ],
        [ $n{reboot},  'restarted',            '#2b6cb0', '#e8f0fa' ],
        [ $n{new},     'new APs',              '#2b6cb0', '#e8f0fa' ],
        [ $n{base},    'APs recorded',         '#1f3a5f', '#eef1f4' ],
        [ $n{sbase},   'devices recorded',     '#1f3a5f', '#eef1f4' ],
    );
    my $html = html_tiles(\@tiles);

    my $first_block = 1;
    for my $s (@$sections) {
        my $sep = $first_block ? '' : 'border-top:1px solid #e4e8ec;padding-top:18px;';
        $first_block = 0;
        if ($s->{type} =~ /^cm_(down|up)$/) {
            my $down = $1 eq 'down';
            my ($fg, $bg) = $down ? ('#c53030', '#fdecec') : ('#2f855a', '#e8f5ec');
            $html .= html_heading($s, $sep)
                   . qq{<tr><td style="padding:10px 24px 0 24px;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:$bg;border-left:4px solid $fg;border-radius:4px;"><tr><td style="padding:10px 12px;font-size:13px;">\n}
                   . ($down
                        ? qq{<div style="font-weight:700;color:$fg;">@{[ h($s->{label} // 'CAPsMAN') ]} @{[ $s->{after_maint} ? 'still unreachable after the maintenance window' : $s->{after_dep} ? 'still unreachable - the device in front of it is back' : 'unreachable' ]}</div>\n}
                        . qq{<div style="padding-top:4px;">@{[ h($s->{err}) ]}</div>\n}
                        . qq{<div style="padding-top:4px;color:#5f6b7a;">Access point status could not be checked.</div>\n}
                        : qq{<div style="font-weight:700;color:$fg;">@{[ h($s->{label} // 'CAPsMAN') ]} reachable again</div>\n}
                        . qq{<div style="padding-top:4px;color:#5f6b7a;">Unreachable since @{[ fmt_time($s->{since}) ]}</div>\n})
                   . "</td></tr></table></td></tr>\n";
        } elsif ($s->{type} eq 'caps' && $s->{first}) {
            $html .= html_heading($s, $sep, "First run - baseline recorded: $s->{cur} active access points")
                   . html_group('Access points', '#1f3a5f', $s->{list}, undef, $s->{col4});
        } elsif ($s->{type} eq 'caps') {
            my $diff = $s->{cur} - $s->{prev};
            my $dcol = $diff < 0 ? '#c53030' : $diff > 0 ? '#2f855a' : '#5f6b7a';
            my $sub = "active APs: before $s->{prev}, now $s->{cur} "
                    . qq{<span style="color:$dcol;font-weight:600;">(} . ($diff > 0 ? '+' : $diff < 0 ? '&minus;' : '&plusmn;') . abs($diff) . ')</span>'
                    . ($s->{miss_all} ? " &nbsp;&middot;&nbsp; $s->{miss_all} missing in total" : '');
            $html .= html_heading($s, $sep, $sub, 1);
            for my $gr (@{ $s->{groups} }) {
                my $G = $GROUP{ $gr->{kind} };
                $html .= html_group($G->{html}, $G->{color}, $gr->{items}, $G->{time}, $s->{col4});
            }
        } elsif ($s->{type} eq 'dep') {
            my %by;
            push @{ $by{ $_->{behind} } }, $_ for @{ $s->{items} };
            $html .= qq{<tr><td style="padding:24px 24px 0 24px;"><div style="$sep"><div style="font-size:16px;font-weight:600;">Not reachable behind a device that is down (@{[ scalar @{ $s->{items} } ]})</div>}
                   . qq{<div style="font-size:13px;color:#5f6b7a;padding-top:2px;">Not reported one by one - they come back with it. If one does not, you get a mail for it then.</div></div></td></tr>\n};
            for my $bh (sort keys %by) {
                $html .= qq{<tr><td style="padding:10px 24px 0 24px;font-size:13px;"><div style="font-weight:600;color:#5f6b7a;">behind @{[ h($bh) ]}</div>}
                       . join('', map { qq{<div style="padding:2px 0 0 12px;">@{[ h($_->{name} // '-') ]} <span style="color:#5f6b7a;">@{[ h(join ', ', grep { length } $_->{ip} // '', $_->{kind}) ]}</span></div>} }
                                  sort { lc($a->{name} // '') cmp lc($b->{name} // '') } @{ $by{$bh} })
                       . "</td></tr>\n";
            }
        } elsif ($s->{type} eq 'switches' || $s->{type} eq 'certs' || $s->{type} eq 'server') {
            $html .= $s->{first}
                ? qq{<tr><td style="padding:24px 24px 0 24px;"><div style="$sep"><div style="font-size:16px;font-weight:600;">@{[ h($s->{heading} // 'Switches (ping)') ]}</div>}
                . qq{<div style="font-size:13px;color:#5f6b7a;padding-top:2px;">First run - baseline recorded: $s->{count} devices, $s->{ok} responding</div></div></td></tr>\n}
                : qq{<tr><td style="padding:24px 24px 0 24px;"><div style="font-size:16px;font-weight:600;$sep">@{[ h($s->{heading} // 'Switches (ping)') ]}</div></td></tr>\n};
            for my $gr (@{ $s->{groups} }) {
                $html .= html_switch_group($GROUP{ $gr->{kind} }, $gr->{items});
            }
        }
    }
    return html_frame($cfg, $now, $subject, $html);
}

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 html_heading {
    my ($s, $sep, $sub, $sub_is_html) = @_;
    my $line = h($s->{host}) . ($s->{identity} ? ' &middot; ' . h($s->{identity}) : '');
    $line .= ' &nbsp;&middot;&nbsp; ' . ($sub_is_html ? $sub : h($sub)) if defined $sub;
    return qq{<tr><td style="padding:24px 24px 0 24px;"><div style="$sep">}
         . qq{<div style="font-size:16px;font-weight:600;">@{[ h($s->{heading} // (($s->{label} // 'CAPsMAN') . " $s->{name}")) ]}</div>}
         . qq{<div style="font-size:13px;color:#5f6b7a;padding-top:2px;">$line</div></div></td></tr>\n};
}

sub html_label {
    my ($label, $color, $count) = @_;
    return qq{<div style="font-size:12px;font-weight:700;color:$color;letter-spacing:.5px;padding-bottom:6px;text-transform:uppercase;">&#9679; @{[ h($label) ]} ($count)</div>\n};
}

sub html_th { join '', map { qq{<td style="$TD font-weight:600;">$_</td>} } @_ }

sub html_group {
    my ($label, $color, $items, $timefield, $col4) = @_;
    my $o = qq{<tr><td style="padding:14px 24px 0 24px;">\n} . html_label($label, $color, scalar @$items)
          . qq{<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;">}
          . html_th('Identity', 'IP', 'MAC', ($col4 // 'Model'), $timefield ? $TIME_LABEL{$timefield} : 'State') . "</tr>\n";
    for my $c (by_identity(@$items)) {
        $o .= qq{<tr style="border-bottom:1px solid #e4e8ec;">}
            . qq{<td style="$TD font-weight:600;">@{[ h($c->{identity} || '-') ]}</td>}
            . qq{<td style="$TD">@{[ h($c->{ip} || '-') ]}</td>}
            . qq{<td style="$TD $MONO">@{[ h($c->{mac} || '-') ]}</td>}
            . qq{<td style="$TD">@{[ h($c->{board} || '-') ]}</td>}
            . qq{<td style="$TD">@{[ h(tcell($c, $timefield)) ]}</td></tr>\n};
    }
    return $o . "</table>\n</td></tr>\n";
}

sub html_switch_group {
    my ($G, $items) = @_;
    my @h = @{ $G->{cols} || [ 'Address', 'Description', $TIME_LABEL{ $G->{time} } ] };
    my $o = qq{<tr><td style="padding:12px 24px 0 24px;">\n} . html_label($G->{html}, $G->{color}, scalar @$items)
          . qq{<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;">} . html_th(@h) . "</tr>\n";
    for my $x (@$items) {
        my ($a, $b) = row3($G, $x);
        $o .= qq{<tr style="border-bottom:1px solid #e4e8ec;"><td style="$TD">@{[ h($a) ]}</td>}
            . qq{<td style="$TD">@{[ h($b) ]}</td><td style="$TD">@{[ h(tcell($x, $G->{time})) ]}</td></tr>\n};
    }
    return $o . "</table>\n</td></tr>\n";
}

# ==========================================================================
# --report: full status mail - checks all devices now (like --check) and adds
# the access points that are missing from the recorded state. Changes nothing.
# ==========================================================================
sub send_report {
    my ($cfg) = @_;
    my $g = $cfg->{general};
    my $lock  = lock_state($cfg);
    my $state = load_state($g->{state_file});
    close $lock;
    my $now = time;

    my (@sections, %n);
    $n{$_} = 0 for qw(online missing cmdown msmdown cnpdown swok swdown);
    for my $cm (@{ $cfg->{capsman} }) {
        my $cs    = $state->{capsman}{ $cm->{name} } || {};
        my $known = $cs->{caps} || {};
        my $res   = eval { fetch_caps($cm) };
        my $err   = $res ? undef : ($@ || 'unknown error');
        chomp $err if defined $err;
        my (@online, @missing);
        if ($res) {
            @online  = values %{ $res->{caps} };
            @missing = map { $known->{$_} } grep { !$res->{caps}{$_} } keys %$known;
        } else {     # not reachable now: show what was known at the last successful check
            @online  = grep { !$_->{missing_since} } values %$known;
            @missing = grep {  $_->{missing_since} } values %$known;
            $n{ { msm => 'msmdown', cnpilot => 'cnpdown' }->{ $cm->{method} } // 'cmdown' }++;
        }
        $n{online}  += @online;
        $n{missing} += @missing;
        my $id = ($res && $res->{identity}) || $cs->{identity};
        my @groups;
        push @groups, { kind => 'r_missing', items => \@missing } if @missing;
        push @groups, { kind => 'r_online',  items => \@online }  if @online;
        push @sections, { type => 'caps', report => 1, title => dev_title($cm, { identity => $id }), heading => dev_heading($cm),
                          label => $cm->{label}, col4 => col4($cm),
                          name => $cm->{name}, host => $cm->{host}, identity => $id,
                          cur => scalar @online, miss_all => scalar @missing,
                          err => $err, last_check => $state->{last_check}, groups => \@groups };
    }
    my (@sw_down, @sw_ok);
    if (my @sw = @{ $cfg->{switches} }) {
        my $ping = ping_hosts([ map { $_->[0] } @sw ], $g);
        for my $s (@sw) {
            my $st = $state->{switches}{ $s->[0] } || {};
            if ($ping->{ $s->[0] }) {
                push @sw_ok, { host => $s->[0], desc => $s->[1], last_ok => $now };
            } else {
                push @sw_down, { host => $s->[0], desc => $s->[1], down_since => $st->{down_since},
                                 muted => $st->{muted} };
            }
        }
    }
    $n{swdown} = @sw_down;
    $n{swok}   = @sw_ok;
    if (@sw_down || @sw_ok) {
        my @groups;
        push @groups, { kind => 'r_down', items => \@sw_down } if @sw_down;
        push @groups, { kind => 'r_ok',   items => \@sw_ok }   if @sw_ok;
        push @sections, { type => 'switches', heading => $g->{_switches_title}, groups => \@groups };
    }

    my $subject = "Status report: $n{online} APs online"
                . ($n{missing} ? ", $n{missing} missing" : '')
                . ($n{cmdown}  ? ", $n{cmdown} CAPsMAN unreachable" : '')
                . ($n{msmdown} ? ", $n{msmdown} HP MSM unreachable" : '')
                . ($n{cnpdown} ? ", $n{cnpdown} cnPilot group(s) silent" : '')
                . (@{ $cfg->{switches} } ? ", $n{swok}/" . ($n{swok} + $n{swdown}) . " switches OK" : '');

    # text
    my @out;
    for my $s (@sections) {
        my $o;
        if ($s->{type} eq 'caps') {
            $o = "$s->{title}\n  Access points: $s->{cur} online"
               . ($s->{miss_all} ? ", $s->{miss_all} missing" : '') . "\n";
            $o .= "  " . uc($s->{label}) . " UNREACHABLE NOW: $s->{err}\n"
                . "  Access point list is from the last successful check" . ($s->{last_check} ? " (" . fmt_time($s->{last_check}) . ")" : '') . ".\n"
                if defined $s->{err};
            $o .= "\n";
            for my $gr (@{ $s->{groups} }) {
                my $G = $GROUP{ $gr->{kind} };
                $o .= "  $G->{text} (" . scalar(@{ $gr->{items} }) . "):\n" . cap_table($gr->{items}, $G->{time}, $s->{col4}) . "\n";
            }
        } else {
            my $fmt = "    %-15s %-34s %s\n";
            $o = ($s->{heading} // "SWITCHES / DEVICES (ping)") . "\n\n";
            for my $gr (@{ $s->{groups} }) {
                my $G = $GROUP{ $gr->{kind} };
                $o .= "  $G->{text} (" . scalar(@{ $gr->{items} }) . "):\n"
                    . sprintf($fmt, 'Address', 'Description', $TIME_LABEL{ $G->{time} });
                $o .= sprintf($fmt, $_->{host}, $_->{desc},
                              fmt_time($_->{ $G->{time} }) . ($_->{muted} ? ' (reminders stopped)' : ''))
                    for @{ $gr->{items} };
                $o .= "\n";
            }
        }
        push @out, $o;
    }
    my $text = "MT-Mon status report $g->{location}, " . fmt_time($now) . "\n"
             . ('=' x 72) . "\n\n"
             . join("\n" . ('-' x 72) . "\n\n", @out);

    # HTML
    my $html;
    if ($cfg->{mail}{format} eq 'html') {
        my @tiles = grep { $_->[0] } (
            [ $n{online},  'APs online',          '#2f855a', '#e8f5ec' ],
            [ $n{missing}, 'APs missing',         '#c53030', '#fdecec' ],
            [ $n{cmdown},  'CAPsMAN unreachable', '#c53030', '#fdecec' ],
            [ $n{msmdown}, 'HP MSM unreachable',  '#c53030', '#fdecec' ],
            [ $n{cnpdown}, 'cnPilot APs silent',  '#c53030', '#fdecec' ],
            [ $n{swok},    'switches OK',         '#2f855a', '#e8f5ec' ],
            [ $n{swdown},  'switches down',       '#c53030', '#fdecec' ],
        );
        my $c = html_tiles(\@tiles);
        my $first = 1;
        for my $s (@sections) {
            my $sep = $first ? '' : 'border-top:1px solid #e4e8ec;padding-top:18px;';
            $first = 0;
            if ($s->{type} eq 'caps') {
                $c .= html_heading($s, $sep, "$s->{cur} online" . ($s->{miss_all} ? ", $s->{miss_all} missing" : ''));
                $c .= qq{<tr><td style="padding:10px 24px 0 24px;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#fdecec;border-left:4px solid #c53030;border-radius:4px;"><tr><td style="padding:10px 12px;font-size:13px;">}
                    . qq{<div style="font-weight:700;color:#c53030;">@{[ h($s->{label}) ]} unreachable now</div>}
                    . qq{<div style="padding-top:4px;">@{[ h($s->{err}) ]}</div>}
                    . qq{<div style="padding-top:4px;color:#5f6b7a;">The access point list below is from the last successful check}
                    . ($s->{last_check} ? ' (' . fmt_time($s->{last_check}) . ')' : '') . qq{.</div></td></tr></table></td></tr>\n}
                    if defined $s->{err};
                for my $gr (@{ $s->{groups} }) {
                    my $G = $GROUP{ $gr->{kind} };
                    $c .= html_group($G->{html}, $G->{color}, $gr->{items}, $G->{time}, $s->{col4});
                }
            } else {
                $c .= qq{<tr><td style="padding:24px 24px 0 24px;"><div style="font-size:16px;font-weight:600;$sep">@{[ h($s->{heading} // 'Switches (ping)') ]}</div></td></tr>\n};
                for my $gr (@{ $s->{groups} }) {
                    my $G = $GROUP{ $gr->{kind} };
                    my @items = map { { %$_, desc => $_->{desc} . ($_->{muted} ? ' (reminders stopped)' : '') } } @{ $gr->{items} };
                    $c .= html_switch_group($G, \@items);
                }
            }
        }
        $html = html_frame($cfg, $now, $subject, $c, 'MT-Mon status report');
    }
    send_mail($cfg, $subject, $text, $html);
    logmsg('info', "Status report sent: $subject");
}

# --------------------------------------------------------------------------
# Switches (ping)
# --------------------------------------------------------------------------
sub process_switches {
    my ($g, $sw, $st_all, $now, $subject) = @_;
    my $M = $g->{_M} || { list => [] };
    my $res = ping_hosts([ map { $_->[0] } @$sw ], $g);
    $g->{_down}{"dev:$_->[0]"} = 1 for grep { !$res->{ $_->[0] } } @$sw;    # 13.6
    my (@down, @up, @remind, @am, @ad, @flap, @port, @portok, @reboot);    # mailed
    my (@s_down, @s_up, @s_flap, @s_port, @s_portok, @s_reboot, @flap_end); # events only
    my $first = !%$st_all;      # first run or after --reset: list every device in the baseline mail

    # SNMP of the devices that answer the ping (one process per device, in parallel)
    my @ask = map { $_->[2] } grep { $_->[2]{snmp} && $res->{ $_->[0] } } @$sw;
    for my $s (@$sw) {                        # VLANs per port: read again after an hour
        my $sn = ($st_all->{ $s->[0] } || {})->{snmp} || {};
        $s->[2]{_vlan} = !$sn->{vlans_t} || $now - $sn->{vlans_t} >= 3600 ? 1 : 0;
    }
    my $snmp = @ask ? snmp_collect($g, \@ask, $g->{_inv_due}) : {};

    for my $s (@$sw) {
        my ($h, $desc, $o) = @$s;
        my $st = $st_all->{$h} ||= { fails => 0 };
        $st->{desc} = $desc;
        my $mu = m_dev($M, $h, $desc);
        my $dep = !$mu && !$res->{$h} ? dep_behind($g, "dev:$h") : undef;
        my $drop = 0;
        if ($res->{$h}) {
            if ($st->{down_since}) {
                push @{ $st->{hidden} ? \@s_up : \@up }, { host => $h, desc => $desc, down_since => $st->{down_since},
                                                           (($st->{hidden} // '') eq 'dep' ? (behind => $st->{behind}) : ()) };
            }
            $st->{fails}   = 0;
            $st->{last_ok} = $now;
            delete @$st{qw(down_since last_alert muted hidden behind)};
            if ($o->{snmp} && $snmp->{$h}) {
                my ($new, $fixed, $reboot) = switch_alerts($g, $o, $st, $snmp->{$h}, $now);
                my %b = (host => $h, desc => $desc);
                push @{ $mu ? \@s_port : \@port },     map { { %b, text => $_->{text}, since => $_->{since} } } @$new;
                push @{ $mu ? \@s_portok : \@portok }, map { { %b, text => "$_->{text} - OK again", since => $_->{since} } } @$fixed;
                push @{ $mu ? \@s_reboot : \@reboot }, { %b, text => 'restarted ' . fmt_dur($reboot) . ' ago (uptime)' } if defined $reboot;
            } elsif (!$o->{snmp}) {
                delete @$st{qw(snmp alerts speed_max)};
            }
        } else {
            $drop = 1 unless $st->{fails};               # the first missed ping after a good one
            $st->{fails}++;
            logmsg('debug', "Switch $h ($desc) not responding (consecutive: $st->{fails})");
            if (!$st->{down_since}) {
                if ($st->{fails} >= $g->{fail_threshold}) {
                    $st->{down_since} = $now;
                    $st->{last_alert} = $now;
                    my $x = { host => $h, desc => $desc, last_ok => $st->{last_ok} };
                    if ($mu)     { $st->{hidden} = 1; push @s_down, $x }
                    elsif ($dep) { $st->{hidden} = 'dep'; $st->{behind} = $dep; push @s_down, { %$x, behind => $dep };
                                   push @{ $g->{_dep} }, { behind => $dep, kind => 'device', name => $desc, ip => $h } }
                    else         { push @down, $x }
                }
            } elsif ($st->{hidden} && !$mu && $dep) {    # 13.6: still behind a device that is down
                @$st{qw(hidden behind)} = ('dep', $dep);
            } elsif ($st->{hidden} && !$mu) {            # went down during maintenance, still down after it
                my $was = delete $st->{hidden};          # (13.6: or the device in front of it is back, this one is not)
                delete $st->{behind};
                $st->{last_alert} = $now;
                push @{ $was eq 'dep' ? \@ad : \@am }, { host => $h, desc => $desc, last_ok => $st->{last_ok} };
            } elsif ($g->{forget_after_days}
                     && $now - $st->{down_since} >= $g->{forget_after_days} * 86400) {
                # forget_after_days for switches: stop reminding, keep it marked unreachable
                # (it stays in the config, so deleting it would just raise a new alert)
                if (!$st->{muted}) {
                    $st->{muted} = 1;
                    logmsg('info', "Switch $h ($desc): unreachable for more than "
                                 . "$g->{forget_after_days} days - reminders stopped");
                }
            } elsif ($g->{_remind_due} && !$st->{hidden} && !$mu) {
                $st->{last_alert} = $now;
                push @remind, { host => $h, desc => $desc, last_ok => $st->{last_ok} };
                $g->{_reminded}++;
            }
        }
        if (my $r = flap_track($g, $st, $drop, $now)) {
            my $x = { host => $h, desc => $desc, flap_text => ($st->{flap_n} // 0) . " drops in $g->{flap_window} min" };
            if ($r eq 'start') { push @{ $mu ? \@s_flap : \@flap }, $x } else { push @flap_end, $x }
        }
    }
    my %in = map { $_->[0] => 1 } @$sw;
    delete $st_all->{$_} for grep { !$in{$_} } keys %$st_all;

    if (!$g->{notify_recovery}) { push @s_up, @up; @up = (); push @s_portok, @portok; @portok = () }
    my @sg;
    push @sg, { kind => 'down',      maint => 1, items => \@s_down }   if @s_down;
    push @sg, { kind => 'up',        maint => 1, items => \@s_up }     if @s_up;
    push @sg, { kind => 'dflap',     maint => 1, items => \@s_flap }   if @s_flap;
    push @sg, { kind => 'dflap_end', items => \@flap_end }             if @flap_end;
    push @sg, { kind => 'port',      maint => 1, items => \@s_port }   if @s_port;
    push @sg, { kind => 'portok',    maint => 1, items => \@s_portok } if @s_portok;
    push @sg, { kind => 'reboot',    maint => 1, items => \@s_reboot } if @s_reboot;
    my $silent = @sg ? { type => 'switches', heading => $g->{_switches_title}, groups => \@sg } : undef;

    my @extra;      # port / restart / flapping groups (also in the baseline mail)
    if (@flap) {
        push @$subject, scalar(@flap) . " device(s) unstable";
        push @extra, { kind => 'dflap', items => \@flap };
    }
    if (@port) {
        push @$subject, scalar(@port) . " switch port / SNMP problem(s)";
        push @extra, { kind => 'port', items => \@port };
    }
    if (@reboot) {
        push @$subject, scalar(@reboot) . " device(s) restarted";
        push @extra, { kind => 'reboot', items => \@reboot };
    }
    if (@portok) {
        push @$subject, scalar(@portok) . " port problem(s) resolved";
        push @extra, { kind => 'portok', items => \@portok };
    }

    if ($first) {
        my @ok   = map { { host => $_->[0], desc => $_->[1], last_ok => $now } } grep {  $res->{ $_->[0] } } @$sw;
        my @fail = map { { host => $_->[0], desc => $_->[1] } }                  grep { !$res->{ $_->[0] } } @$sw;
        push @$subject, "baseline " . scalar(@$sw) . " devices" . (@fail ? ", " . scalar(@fail) . " not responding" : '');
        my @groups;
        push @groups, { kind => 'b_down', items => \@fail } if @fail;
        push @groups, { kind => 'b_ok',   items => \@ok }   if @ok;
        return ({ type => 'switches', first => 1, heading => $g->{_switches_title},
                  count => scalar(@$sw), ok => scalar(@ok), groups => [ @groups, @extra ] }, $silent);
    }

    return (undef, $silent) unless @down || @up || @remind || @am || @ad || @extra;

    my @groups;
    if (@down) {
        push @$subject, scalar(@down) . " switch(es) not responding";
        push @groups, { kind => 'down', items => \@down };
    }
    if (@am) {
        push @$subject, scalar(@am) . " switch(es) still down after maintenance";
        push @groups, { kind => 'down_am', items => \@am };
    }
    if (@ad) {
        push @$subject, scalar(@ad) . " device(s) still not responding";
        push @groups, { kind => 'down_ad', items => \@ad };
    }
    if (@remind) {
        push @$subject, scalar(@remind) . " switch(es) still unreachable";
        push @groups, { kind => 'sremind', items => \@remind };
    }
    push @groups, grep { $_->{kind} ne 'portok' } @extra;
    if (@up) {
        push @$subject, scalar(@up) . " switch(es) OK again";
        push @groups, { kind => 'up', items => \@up };
    }
    push @groups, grep { $_->{kind} eq 'portok' } @extra;
    return ({ type => 'switches', heading => $g->{_switches_title}, groups => \@groups }, $silent);
}

# parallel ping using the ping command (iputils), in batches of ping_parallel
sub ping_hosts {
    my ($hosts, $g) = @_;
    my %res;
    my @queue = @$hosts;
    while (@queue) {
        my @batch = splice(@queue, 0, $g->{ping_parallel});
        my %fh;
        for my $h (@batch) {
            my $pid = open(my $fh, '-|', 'ping', '-n', '-q', '-c', $g->{ping_count},
                           '-i', '0.5', '-W', $g->{ping_timeout}, $h);
            if (!$pid) { logmsg('error', "Cannot run ping for $h: $!"); $res{$h} = 0; next }
            $fh{$h} = $fh;
        }
        for my $h (keys %fh) {
            my $fh = $fh{$h};
            local $/;
            my $out = <$fh>;          # drain the pipe
            close $fh;
            $res{$h} = ($? == 0) ? 1 : 0;
        }
    }
    return \%res;
}

# --------------------------------------------------------------------------
# Reading remote-cap from CAPsMAN
# --------------------------------------------------------------------------
sub fetch_caps {
    my ($cm) = @_;
    return fetch_caps_msm($cm) if $cm->{method} eq 'msm';
    return fetch_caps_cnpilot($cm) if $cm->{method} eq 'cnpilot';
    return $cm->{method} eq 'api' ? fetch_caps_api($cm) : fetch_caps_ssh($cm);
}

# which paths to try: configured, remembered, or all
sub caps_paths {
    my ($cm) = @_;
    return ([ $cm->{path} ], 0)             if $cm->{path};
    return ($PATH_CACHE{ $cm->{name} }, 0)  if $PATH_CACHE{ $cm->{name} };
    return ([ @CAPS_PATHS ], 1);
}

# one remote-cap record (from API or terse output) -> (key, data)
sub cap_record {
    my ($r) = @_;
    my $addr = $r->{address} // '';
    my ($ip) = $addr =~ /(\d{1,3}(?:\.\d{1,3}){3})/;
    my $mac  = uc($r->{'base-mac'} // '');
    if (!$mac && $addr =~ /([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5})/) { $mac = uc $1 }
    my $key = $mac || $r->{'common-name'} || $r->{identity} || $r->{'.id'};
    return ($key, {
        identity => $r->{identity} // $r->{name} // '',
        ip       => $ip // '',
        mac      => $mac,
        board    => $r->{board} // $r->{'board-name'} // '',
        version  => $r->{version} // '',
        state    => $r->{state} // '',
        serial   => $r->{serial} // $r->{'serial-number'} // '',
    });
}

# ---- SSH (default) --------------------------------------------------------
sub fetch_caps_ssh {
    my ($cm) = @_;
    my ($paths, $discover) = caps_paths($cm);
    my (%caps, @valid, @errs, $identity);

    for my $p (@$paths) {
        (my $cli = $p) =~ s{(?<=.)/}{ }g;            # /caps-man/remote-cap -> /caps-man remote-cap
        my ($rc, $out) = ssh_exec($cm, ":put [/system identity get name]; $cli print terse without-paging");
        my @lines = grep { /\S/ } map { s/\r//gr } split /\n/, $out;

        if ($rc == 255) {
            my @e = grep { !/^\*\*|^\s*\*\*|WARNING|vulnerable to .*store now, decrypt later|upgraded/i } @lines;
            die "SSH to $cm->{host}:$cm->{port} failed: " . ($e[0] // $lines[0] // "exit code $rc") . "\n";
        }
        if (my ($err) = grep { /\(line \d+ column \d+\)|^(?:bad command name|syntax error|expected end of command|no such command)/i } @lines) {
            push @errs, "$p: $err";
            logmsg('debug', "$cm->{name}: $p -> $err");
            next;
        }
        if (my ($err) = grep { /not enough permissions|^failure:/i } @lines) {
            die "MikroTik rejected the command ($p): $err\n";
        }
        push @valid, $p;
        my $id = shift(@lines) // '';
        $identity //= RosAPI::_dec($id);
        for my $l (@lines) {
            my $r = parse_terse($l);
            next unless %$r;
            my ($k, $c) = cap_record($r);
            $caps{$k} = $c if defined $k;
        }
    }

    if (!@valid) {
        delete $PATH_CACHE{ $cm->{name} };
        die "No CAPsMAN remote-cap found on the device (" . join('; ', @errs) . ")\n";
    }
    $PATH_CACHE{ $cm->{name} } = \@valid if $discover;
    return { caps => \%caps, identity => $identity, paths => \@valid };
}

# runs a command on the MikroTik via the OpenSSH client; returns (exit code, output)
sub ssh_exec {
    my ($cm, $remote) = @_;
    my @cmd = ('ssh', '-F', '/dev/null', '-T',
        '-i', $cm->{key}, '-p', $cm->{port}, '-l', $cm->{user} . $cm->{user_suffix},
        '-o', 'BatchMode=yes',
        '-o', 'IdentitiesOnly=yes',
        '-o', 'PasswordAuthentication=no',
        '-o', 'KbdInteractiveAuthentication=no',
        '-o', "ConnectTimeout=$cm->{timeout}",
        '-o', "StrictHostKeyChecking=$cm->{host_key_check}",
        '-o', "UserKnownHostsFile=$cm->{known_hosts}",
        '-o', 'GlobalKnownHostsFile=/dev/null',
        '-o', 'LogLevel=ERROR',
        '-o', 'ServerAliveInterval=5',
        '-o', 'ServerAliveCountMax=2',
        (map { ('-o', $_) } @{ $cm->{extra_options} }),
        '--', $cm->{host}, $remote);
    logmsg('debug', "$cm->{name}: ssh $cm->{user}$cm->{user_suffix}\@$cm->{host}:$cm->{port} '$remote'");

    # stderr kept separate: OpenSSH warnings (e.g. post-quantum kex in OpenSSH 10.1+)
    # must not be mixed with the MikroTik output
    my ($in, $out, $err);
    $err = Symbol::gensym();
    my $pid = open3($in, $out, $err, @cmd);
    close $in;
    binmode $out;
    binmode $err;
    my ($buf, $ebuf) = ('', '');
    my $ok = eval {
        local $SIG{ALRM} = sub { die "timeout\n" };
        # reload/stop must also interrupt waiting for a device
        local $SIG{HUP}  = sub { $reload  = 1; die "signal\n" };
        local $SIG{TERM} = local $SIG{INT} = sub { $running = 0; die "signal\n" };
        die "signal\n" if $reload || !$running;
        alarm($cm->{timeout} * 2 + 5);
        local $/;
        $buf  = <$out> // '';
        $ebuf = <$err> // '';
        alarm 0;
        1;
    };
    alarm 0;
    if (!$ok) {
        my $why = $@;
        kill 'TERM', $pid;
        waitpid($pid, 0);
        die "SSH to $cm->{host}: interrupted\n" if $why eq "signal\n";
        die "SSH to $cm->{host}: timeout\n";
    }
    close $out;
    close $err;
    waitpid($pid, 0);
    my $rc = $? >> 8;
    for my $w (grep { /\S/ } split /\r?\n/, $ebuf) {
        logmsg('debug', "$cm->{name}: ssh: $w");   # otherwise every cycle would flood the journal
    }
    # on a connection error (255) return the ssh message
    return ($rc, $rc == 255 ? $ebuf . $buf : $buf);
}

# RouterOS "print terse": 0 X key=value key="value" key=value with spaces ...
# RouterOS quotes only some values; an unquoted value may contain spaces and runs until the
# next " key=" (e.g. ssid=Koper Wi-Free mac-address=...). Non-ASCII is printed as \C4\8D.
sub parse_terse {
    my ($line) = @_;
    my %r;
    while ($line =~ /(?:^|\s)([A-Za-z0-9.\-]+)=/g) {
        my $k = $1;
        my $v;
        if ($line =~ /\G"((?:[^"\\]|\\.)*)"(?=\s|$)/gc) { $v = $1 }
        else { $line =~ /\G(.*?)(?=\s+[A-Za-z0-9.\-]+=|\s*$)/gcs; $v = $1 // '' }
        $v =~ s/\\([0-9A-Fa-f]{2}|.)/length($1) == 2 ? chr(hex $1) : $1/ge;
        $r{$k} = RosAPI::_dec($v);
    }
    return \%r;
}

# ---- RouterOS API (optional: method = api) -------------------------------
sub fetch_caps_api {
    my ($cm) = @_;
    my ($paths, $discover) = caps_paths($cm);
    my $api = RosAPI->new(%$cm);
    my (%caps, @valid, @errs);
    for my $p (@$paths) {
        my ($re, $trap) = $api->cmd("$p/print");
        if (defined $trap) { push @errs, "$p: $trap"; logmsg('debug', "$cm->{name}: $p -> $trap"); next }
        push @valid, $p;
        for my $r (@$re) {
            my ($k, $c) = cap_record($r);
            $caps{$k} = $c if defined $k;
        }
    }
    my ($idr) = $api->cmd('/system/identity/print');
    $api->close;
    if (!@valid) {
        delete $PATH_CACHE{ $cm->{name} };
        die "No CAPsMAN remote-cap found on the device (" . join('; ', @errs) . ")\n";
    }
    $PATH_CACHE{ $cm->{name} } = \@valid if $discover;
    return { caps => \%caps, identity => ($idr->[0]{name} // ''), paths => \@valid };
}

# title = ... in a [capsman]/[msm]/[cnpilot] section replaces the section heading in mails
sub has_title { defined $_[0]{title} && $_[0]{title} =~ /\S/ }

sub dev_title {
    my ($cm, $cs) = @_;
    my $id = $cs && $cs->{identity} ? ", $cs->{identity}" : '';
    return "$cm->{title} ($cm->{host}$id)" if has_title($cm);
    return ($cm->{label} || 'CAPsMAN') . " '$cm->{name}' ($cm->{host}$id)";
}

sub dev_heading {
    my ($cm) = @_;
    return has_title($cm) ? $cm->{title} : (($cm->{label} || 'CAPsMAN') . " $cm->{name}");
}

# ==========================================================================
# HP MSM720 / Colubris controller over SNMP (net-snmp command line tools)
# Reads COLUBRIS-DEVICE-MIB::coDeviceDiscoveryTable with numeric OIDs, one walk
# per column (the MSM agent skips entries when walking larger subtrees), with
# -Cc (no increasing-OID check); bulk walk first, plain walk if bulk is empty.
# ==========================================================================
my ($MSM_BASE, %MSM_COLS, %MSM_STATES);
BEGIN {
    $MSM_BASE = '1.3.6.1.4.1.8744.5.23.1.2.1.1';    # coDeviceDiscoveryEntry
    # only the columns mtmon uses - every extra walk is load on an agent that easily gives up
    %MSM_COLS = (
        3  => 'mac',         # coDevDisMacAddress
        4  => 'ip',          # coDevDisIpAddress
        5  => 'state',       # coDevDisState
        6  => 'name',        # coDevDisSystemName
        7  => 'location',    # coDevDisLocation
    );
    %MSM_STATES = (1 => 'disconnected', 2 => 'authorized', 3 => 'join', 4 => 'firmware',
                   5 => 'security', 6 => 'configuration', 7 => 'running');
}

# runs a command with a time limit; returns (exit code, stdout, stderr)
sub run_cmd {
    my ($limit, @cmd) = @_;
    my ($in, $out, $err) = (undef, undef, Symbol::gensym());
    # (the error text must not contain the command line - it would leak the community into mails)
    my $pid = eval { open3($in, $out, $err, @cmd) }
        or die "Cannot run $cmd[0]: "
             . ($@ =~ /No such file/ ? ($cmd[0] =~ /^snmp/ ? "not installed (Debian: apt install snmp, RHEL: dnf install net-snmp-utils)" : "not installed")
                                     : "start failed") . "\n";
    close $in;
    my ($o, $e) = ('', '');
    my $ok = eval {
        local $SIG{ALRM} = sub { die "timeout\n" };
        local $SIG{HUP}  = sub { $reload  = 1; die "signal\n" };
        local $SIG{TERM} = local $SIG{INT} = sub { $running = 0; die "signal\n" };
        die "signal\n" if $reload || !$running;
        alarm $limit;
        local $/;
        $o = <$out> // '';
        $e = <$err> // '';
        alarm 0;
        1;
    };
    alarm 0;
    if (!$ok) {
        my $why = $@;
        kill 'TERM', $pid;
        waitpid($pid, 0);
        die "$cmd[0] to $cmd[-2]: " . ($why eq "signal\n" ? "interrupted" : "timeout") . "\n";
    }
    waitpid($pid, 0);
    return ($? >> 8, decode('UTF-8', $o, Encode::FB_DEFAULT), decode('UTF-8', $e, Encode::FB_DEFAULT));
}

sub msm_auth {
    my ($cm) = @_;
    my @a = ('-t', $cm->{timeout}, '-r', $cm->{retries});
    if ($cm->{snmp_version} eq '3') {
        my $lvl = length $cm->{priv_pass} ? 'authPriv' : length $cm->{auth_pass} ? 'authNoPriv' : 'noAuthNoPriv';
        push @a, '-v3', '-l', $lvl, '-u', $cm->{user};
        push @a, '-a', $cm->{auth_proto}, '-A', $cm->{auth_pass} if $lvl ne 'noAuthNoPriv';
        push @a, '-x', $cm->{priv_proto}, '-X', $cm->{priv_pass} if $lvl eq 'authPriv';
    } else {
        push @a, "-v$cm->{snmp_version}", '-c', $cm->{community};
    }
    return @a;
}

# one column walk -> ('ok', \@lines) | ('refused', undef, why) | ('error', undef, why)
# 'refused' = the agent answered without data ("No Such Object", nothing): worth retrying later
sub msm_walk {
    my ($cm, $oid) = @_;
    my $limit = ($cm->{timeout} || 1) * ($cm->{retries} + 1) * 2 + 10;
    # SNMPv1 has no GETBULK -> plain walk. With v2c/v3 a plain walk is tried only when the bulk
    # walk returned nothing at all (not when the agent said "No Such Object" - that only adds load).
    my @tools = $cm->{snmp_version} eq '1' ? ('snmpwalk') : ('snmpbulkwalk', 'snmpwalk');
    my $why = 'empty answer';
    for my $tool (@tools) {
        my @cmd = ($tool, '-On', '-Oe', ($cm->{_ox} ? '-Ox' : ()), '-Cc', msm_auth($cm), $cm->{host}, $oid);
        my ($rc, $out, $err) = run_cmd($limit, @cmd);
        logmsg('debug', "$cm->{name}: $tool $cm->{host} $oid (rc=$rc)" . ($err =~ /\S/ ? " stderr: " . ($err =~ s/\s+/ /gr) : ''));
        if ($rc != 0 && $out !~ /\S/) {
            my $msg = (grep { /\S/ } split /\n/, $err)[0] // "exit code $rc";
            return ('error', undef, "SNMP to $cm->{host} failed: $msg");
        }
        # keep the lines of this column, including continuation lines of a wrapped value
        my ($keep, @lines) = (0);
        for my $l (split /\n/, $out) {
            $keep = ((my $x = $l) =~ s/^\.//r) =~ /^\Q$oid\E\./ ? 1 : 0 if $l =~ /^\.?[\d.]+\s*=/;
            push @lines, $l if $keep;
        }
        return ('ok', \@lines) if @lines;
        if ($out =~ /No Such (?:Object|Instance)|No more variables/i) { $why = 'agent answered "No Such Object"'; last }
    }
    return ('refused', undef, $why);
}

# joins continuation lines (a long Hex-STRING wraps) -> list of [oid, type, value]
sub msm_parse {
    my @merged;
    for my $l (@_) {
        if ($l =~ /^\.?[\d.]+\s*=/) { push @merged, $l }
        elsif (@merged)             { $merged[-1] .= ' ' . ($l =~ s/^\s+|\s+$//gr) }
    }
    my @r;
    for my $l (@merged) {
        next unless $l =~ /^\.?([\d.]+)\s*=\s*(?:([\w-]+):\s*)?(.*)$/;
        my ($oid, $type, $val) = ($1, $2 // '', $3);    # copy before the next regex resets $1..$3
        $val =~ s/^\s+|\s+$//g;
        push @r, [ $oid, $type, $val ];
    }
    return @r;
}

sub msm_mac {
    my ($type, $v) = @_;
    $v =~ s/^\s*"?|"?\s*$//g;
    my @p = split ' ', $v;
    return uc join ':', @p if @p == 6 && !grep { !/^[0-9A-Fa-f]{2}$/ } @p;    # "84 34 97 B6 EE 96"
    return uc join ':', map { sprintf '%02x', ord } split //, $v
        if $type eq 'STRING' && length($v) == 6;                              # printable bytes
    $v =~ s/-/:/g if $v =~ /^(?:[0-9A-Fa-f]{2}-){5}[0-9A-Fa-f]{2}$/;
    return uc $v;
}

sub msm_int { $_[0] =~ /\((\d+)\)|(-?\d+)/ ? ($1 // $2) : $_[0] }   # "running(7)" or "7"

sub msm_column {
    my ($cm, $col, $lines) = @_;
    my $field = $MSM_COLS{$col};
    my $oid = "$MSM_BASE.$col";
    my %v;
    for my $r (msm_parse(@$lines)) {
        my ($o, $type, $val) = @$r;
        next unless $o =~ /^\Q$oid\E\.(.+)$/;
        my $idx = $1;
        if    ($field eq 'mac')   { $val = msm_mac($type, $val) }
        elsif ($field eq 'state') { my $n = msm_int($val); $val = $MSM_STATES{$n} // $val }
        else                      { $val =~ s/^"(.*)"$/$1/s }
        $v{$idx} = $val;
    }
    return \%v;
}

# Reads the table column by column. The MSM agent often answers "No Such Object" or stops
# in the middle of a walk, so only the failed or incomplete columns are read again, with
# growing pauses, until all are complete or max_wait runs out. An incomplete table is an
# error (the check counts as failed) - it must never look like missing access points.
sub msm_read_table {
    my ($cm) = @_;
    my @cols  = sort { $a <=> $b } keys %MSM_COLS;
    my $delay = $cm->{retry_delay};
    my $t0    = time;
    my (%data, $any_ok, $last_why);
    my $round = 0;
    my @todo  = @cols;
    while (1) {
        $round++;
        for my $col (@todo) {
            my ($st, $lines, $why) = msm_walk($cm, "$MSM_BASE.$col");
            if ($st eq 'ok') { $data{$col} = msm_column($cm, $col, $lines); $any_ok = 1; next }
            die "$why\n" if $st eq 'error' && !$any_ok;     # unreachable: report at once, no retries
            delete $data{$col};
            $last_why = $why;
        }
        # a column with fewer rows than the others was cut off in the middle of the walk
        my ($max) = sort { $b <=> $a } map { scalar keys %{ $data{$_} } } keys %data;
        my @partial = grep { $data{$_} && keys %{ $data{$_} } < $max } @cols;
        if (@partial) { delete $data{$_} for @partial; $last_why //= 'incomplete answer' }
        my @again = grep { !$data{$_} } @cols;
        return (\%data, $round - 1) unless @again;

        my $waited = time - $t0;
        if ($waited + $delay > $cm->{max_wait} || $round >= 12) {
            die "SNMP to $cm->{host}: no complete answer from coDeviceDiscoveryTable within ${waited}s "
              . "($round attempts, last: $last_why)\n";
        }
        logmsg('debug', "$cm->{name}: columns " . join(',', @again) . " not complete ($last_why), retry in ${delay}s");
        sleep $delay;
        die "SNMP to $cm->{host}: interrupted\n" if $reload || !$running;
        $delay = $delay * 2 > 15 ? 15 : $delay * 2;
        @todo = @again;
        $last_why = undef;
    }
}

my %MSM_ID;   # controller name (sysName) cache: one request less per cycle
sub fetch_caps_msm {
    my ($cm) = @_;
    my ($data, $retries) = msm_read_table($cm);
    my %ap;
    for my $col (keys %$data) {
        $ap{$_}{ $MSM_COLS{$col} } = $data->{$col}{$_} for keys %{ $data->{$col} };
    }
    die "SNMP to $cm->{host}: coDeviceDiscoveryTable returned no access points\n"
        unless grep { defined $_->{mac} && defined $_->{state} } values %ap;

    # controller name (sysName.0) - optional, only for display
    my $identity = $MSM_ID{ $cm->{name} } // '';
    if (!length $identity) {
        my ($rc, $out) = eval { run_cmd(($cm->{timeout} || 1) * ($cm->{retries} + 1) + 10,
                                        'snmpget', '-On', '-Oqv', msm_auth($cm), $cm->{host}, '1.3.6.1.2.1.1.5.0') };
        if (defined $rc && $rc == 0) { ($identity = (split /\n/, $out)[0] // '') =~ s/^"|"\s*$//g }
        $identity = '' if $identity =~ /No Such/i;
        $MSM_ID{ $cm->{name} } = $identity if length $identity;
    }

    # an AP counts as present only while the controller reports it as running
    my (%caps, @other);
    for my $idx (sort keys %ap) {
        my $x = $ap{$idx};
        my $key = $x->{mac} || "idx$idx";
        my $rec = {
            identity => (length($x->{name} // '') ? $x->{name} : ($x->{mac} || "index $idx")),
            ip       => $x->{ip} // '',
            mac      => $x->{mac} // '',
            board    => $x->{location} // '',       # shown in the "Location" column for HP MSM
            version  => '',
            state    => $x->{state} // '',
        };
        if (($x->{state} // '') eq 'running') { $caps{$key} = $rec }
        else                                  { push @other, $rec }
    }
    my %names = map { $_ => (length($ap{$_}{name} // '') ? $ap{$_}{name} : ($ap{$_}{mac} || "AP $_")) } keys %ap;
    return { caps => \%caps, identity => $identity, other => \@other, ap_names => \%names,
             paths => [ 'coDeviceDiscoveryTable (SNMP v' . $cm->{snmp_version} . ')'
                        . ($retries ? ", $retries retr" . ($retries == 1 ? 'y' : 'ies') . " needed" : '') ] };
}

# ==========================================================================
# Cambium cnPilot E-series access points over SNMP (no controller needed)
# Every AP listed in [cnpilot NAME] host = ... is asked directly, in parallel,
# with CAMBIUM-NETWORKS cnPilot E MIB (1.3.6.1.4.1.17713.22). The section works
# like a CAPsMAN: an AP that stops answering is "missing", all of them silent =
# the section is unreachable. The same answers give the Wi-Fi clients per SSID.
# ==========================================================================
my ($CNP_BASE, %CNP_SYS);
BEGIN {
    $CNP_BASE = '1.3.6.1.4.1.17713.22.1';
    # cambiumAPSystem scalars (.1.1.N.0)
    %CNP_SYS = (1 => 'mac', 2 => 'name', 3 => 'ip', 4 => 'serial', 5 => 'model', 6 => 'cpu',
                7 => 'mem', 8 => 'version', 9 => 'uptime', 12 => 'cloud', 14 => 'clients');
}

sub is_snmp_ctl { (($_[0] || {})->{method} // '') =~ /^(msm|cnpilot)$/ }
sub ctl_kind {
    my $m = ($_[0] || {})->{method} // '';
    return $m eq 'msm' ? 'HP MSM' : $m eq 'cnpilot' ? 'Cambium cnPilot' : 'MikroTik';
}

# "10.32.0.30-40" -> 10.32.0.30 .. 10.32.0.40 (last octet only), other entries as they are
sub expand_hosts {
    my @out;
    for my $h (@_) {
        if ($h =~ /^(\d+\.\d+\.\d+\.)(\d+)-(\d+)$/ && $2 <= $3 && $3 <= 255) { push @out, map { "$1$_" } $2 .. $3 }
        else { push @out, $h }
    }
    return @out;
}

# one AP (runs in its own process): system scalars, radios, WLANs, clients
sub cnp_ap {
    my ($cm, $host) = @_;
    my %a = (%$cm, host => $host, name => "$cm->{name}/$host");
    my $limit = ($a{timeout} || 1) * ($a{retries} + 1) * 2 + 10;
    my @oids = map { "$CNP_BASE.1.1.$_.0" } sort { $a <=> $b } keys %CNP_SYS;
    my ($rc, $out, $err) = run_cmd($limit, 'snmpget', '-On', '-Oe', msm_auth(\%a), $host, @oids);
    my %v = map { $_->[0] => $_->[2] } msm_parse(split /\n/, $out);
    my %s;
    for my $n (keys %CNP_SYS) {
        my $x = $v{"$CNP_BASE.1.1.$n.0"};
        next if !defined $x || $x =~ /No Such/i;
        $s{ $CNP_SYS{$n} } = msm_str($x);
    }
    if (!length($s{mac} // '')) {
        my $msg = (grep { /\S/ } split /\n/, $err)[0] // ($rc ? "exit code $rc" : 'not a cnPilot E (no cambiumAPMACAddress)');
        $msg =~ s/^Timeout: No Response from .*/no answer (timeout) - check community \/ SNMP access/;
        die "$msg\n";
    }
    $s{mac} = msm_mac('STRING', $s{mac});
    $s{uptime} = int((snmp_num($s{uptime}) // 0) / 100) if defined $s{uptime};
    $s{$_} = snmp_num($s{$_}) for grep { defined $s{$_} } qw(cpu mem clients);

    # tables: index -> column -> value (details only - a failed walk leaves them empty)
    my $table = sub {
        my ($t) = @_;
        my $oid = "$CNP_BASE.$t.1";
        my ($st, $lines) = msm_walk(\%a, $oid);
        return {} unless $st eq 'ok';
        my %r;
        for (msm_parse(@$lines)) {
            my ($o, $ty, $val) = @$_;
            next unless $o =~ /^\Q$oid\E\.(\d+)\.(.+)$/;
            $r{$2}{$1} = msm_str($val);
        }
        return \%r;
    };
    my $rad = $table->(2);
    my $wl  = $table->(4);
    my $cl  = ($s{clients} // 1) ? $table->(3) : {};
    my (@radios, @wlans, @clients);
    for my $i (sort { $a <=> $b } keys %$rad) {
        my $r = $rad->{$i};
        push @radios, { idx => $r->{1} // $i, band => $r->{3} // '', clients => snmp_num($r->{5}) // 0, channel => $r->{6} // '' };
    }
    for my $i (sort { $a <=> $b } keys %$wl) {
        my $w = $wl->{$i};
        next unless length($w->{2} // '');
        push @wlans, { ssid => $w->{2}, vlan => snmp_num($w->{4}) // '', clients => snmp_num($w->{7}) // 0 };
    }
    # client radio column is 1-based, the radio table index 0-based
    my %band = map { ($_->{idx} + 1) => $_->{band} } @radios;
    for my $i (keys %$cl) {
        my $c = $cl->{$i};
        next unless length($c->{2} // '');
        my $ip = $c->{3} // '';
        $ip = '' if $ip eq '0.0.0.0';
        my $hn = $c->{4} // '';
        $hn = '' if $hn eq 'NA';
        push @clients, { mac => msm_mac('STRING', $c->{2}), ip => $ip, host => $hn, ssid => $c->{5} // '',
                         band => $band{ snmp_num($c->{8}) // -1 } // '' };
    }
    return { sys => \%s, radios => \@radios, wlans => \@wlans, clients => \@clients };
}

# all APs of a [cnpilot] section, at most 16 SNMP processes at a time
sub cnp_collect {
    my ($cm) = @_;
    my %res;
    my @q = @{ $cm->{aps} };
    my $par = $cm->{parallel} || 16;
    while (@q) {
        last if $reload || !$running;
        my @b = splice(@q, 0, $par);
        my %fh;
        for my $h (@b) {
            my $pid = open(my $fh, '-|');
            if (!defined $pid) { $res{$h} = { err => "cannot start: $!" }; next }
            if (!$pid) {
                $SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { POSIX::_exit(1) };
                my $r = eval { cnp_ap($cm, $h) } || { err => (($@ // '') =~ s/\s+$//r) || 'unknown error' };
                binmode STDOUT;
                print JSON::PP->new->utf8->encode($r);
                close STDOUT;
                POSIX::_exit(0);
            }
            $fh{$h} = $fh;
        }
        for my $h (keys %fh) {
            my $fh = $fh{$h};
            binmode $fh;
            local $/;
            my $j = <$fh>;
            close $fh;
            $res{$h} = eval { JSON::PP->new->utf8->decode($j // '') } || { err => 'no answer from the SNMP process' };
        }
    }
    return \%res;
}

sub fetch_caps_cnpilot {
    my ($cm) = @_;
    my $all = cnp_collect($cm);
    die "interrupted\n" if $reload || !$running;
    my (%caps, %names, @err);
    for my $h (@{ $cm->{aps} }) {
        my $r = $all->{$h} || { err => 'not asked' };
        if ($r->{err}) { push @err, "$h: $r->{err}"; next }
        my $s = $r->{sys};
        my $key = $s->{mac};
        $caps{$key} = {
            identity => (length($s->{name} // '') ? $s->{name} : $h),
            ip       => $s->{ip} || $h,
            mac      => $s->{mac},
            board    => $s->{model} // '',
            version  => $s->{version} // '',
            serial   => $s->{serial} // '',
            uptime   => $s->{uptime},
            clients  => $s->{clients},
        };
        $names{$h} = $caps{$key}{identity};
    }
    logmsg('debug', "$cm->{name}: no SNMP answer from " . join('; ', @err)) if @err;
    die "SNMP: none of the " . scalar(@{ $cm->{aps} }) . " cnPilot access point(s) answered ("
        . ($err[0] // 'no answer') . ")\n" unless %caps;
    return { caps => \%caps, identity => '', ap_names => \%names, _cnp => $all,
             silent => [ map { (split /: /, $_, 2)[0] } @err ],
             paths => [ 'cnPilot E MIB (SNMP v' . $cm->{snmp_version} . '), ' . scalar(keys %caps) . ' of '
                        . scalar(@{ $cm->{aps} }) . ' AP(s) answered' ] };
}

# clients come with the AP answers of the check - no second round of SNMP requests
sub fetch_clients_cnpilot {
    my ($cm, $res) = @_;
    my $all = $res->{_cnp} or die "no cnPilot answers of this check\n";
    my @clients;
    for my $h (sort keys %$all) {
        my $r = $all->{$h};
        next if $r->{err};
        my $ap = length($r->{sys}{name} // '') ? $r->{sys}{name} : $h;
        my %vlan = map { $_->{ssid} => $_->{vlan} } @{ $r->{wlans} || [] };
        my %listed;
        for my $c (@{ $r->{clients} || [] }) {
            $listed{ $c->{ssid} }++;
            push @clients, { mac => $c->{mac}, ssid => (length $c->{ssid} ? $c->{ssid} : '(no SSID)'), ap => $ap,
                             ip => $c->{ip}, host => $c->{host}, user => '', auth => '', band => $c->{band},
                             signal => undef, uptime => undef, vlan => $vlan{ $c->{ssid} } // '' };
        }
        # the AP counts more clients per WLAN than its client table lists (table not readable,
        # or changed between the two reads): count the rest without details
        for my $w (@{ $r->{wlans} || [] }) {
            my $miss = ($w->{clients} || 0) - ($listed{ $w->{ssid} } || 0);
            push @clients, map { { mac => '', ssid => $w->{ssid}, ap => $ap, ip => '', host => '', user => '', auth => '',
                                   band => '', signal => undef, uptime => undef, vlan => $w->{vlan} } } 1 .. $miss if $miss > 0;
        }
    }
    return \@clients;
}


# ==========================================================================
# Wi-Fi clients per SSID - only for the web dashboard ([web] clients = yes).
# Collected after every check from the controllers that answered; a failure here
# never affects monitoring, mails or the recorded state.
# ==========================================================================
my (%MSM_CLI, %MSM_CACHE, %MSM_USERS);
BEGIN {
    # COLUBRIS-DEVICE-WIRELESS-MIB::coDeviceWirelessClientStatusEntry, index = AP (coDevDisIndex).radio.station
    %MSM_CLI = (
        base => '1.3.6.1.4.1.8744.5.25.1.7.1.1',
        cols => { 2 => 'mac', 3 => 'vsc', 4 => 'uptime', 5 => 'signal', 12 => 'dot1x', 17 => 'ip' },
        count => '1.3.6.1.4.1.8744.5.25.1.7.2.0',          # coDevWirNbAssociatedStation
        vsc_map => '1.3.6.1.4.1.8744.5.25.1.5.1.1.2',      # coDevWirVscStaMscVscIndex (AP.radio.vsc -> VSC config)
        vsc_ssid => '1.3.6.1.4.1.8744.5.22.1.1.1.1.3',     # COLUBRIS-VSC-MIB::coVscCfgSSID
        pa_name => '1.3.6.1.4.1.8744.5.1.1.3.6.1.6',       # COLUBRIS-PUBLIC-ACCESS-MIB::publicAccessUserName
        pa_mac  => '1.3.6.1.4.1.8744.5.1.1.3.6.1.15',      # publicAccessUserStationMacAddress
    );
}

# net-snmp quoted STRING value: strip the quotes, undo the escaping of " and backslash
sub msm_str { my $v = shift; return $v unless $v =~ /^"(.*)"$/s; ($v = $1) =~ s/\\(["\\])/$1/g; $v }

# "10.1.0.1", "10.1.0.1:2222", "router.example:2222", "[fd00::1]:2222", "fd00::1" -> (host, port or undef)
sub host_port {
    my ($v, $what) = @_;
    my ($h, $p);
    if    ($v =~ /^\[([0-9A-Fa-f:.]+)\](?::(\d+))?$/) { ($h, $p) = ($1, $2) }
    elsif ($v =~ /^([^:\s]+):(\d+)$/)                  { ($h, $p) = ($1, $2) }
    else                                                { $h = $v }
    die "$what: invalid address '$v'\n" if $h =~ /^-/ || $h =~ /[\s\[\]]/;
    die "$what: invalid port in '$v' (1-65535)\n" if defined $p && ($p < 1 || $p > 65535);
    return ($h, $p);
}

# RouterOS durations: 1w2d3h4m5s, 3h4m5s700ms, 1d02:03:04, 00:12:34
sub ros_seconds {
    my ($v) = @_;
    return undef unless defined $v && length $v;
    my $s = 0;
    my %u = (w => 604800, d => 86400, h => 3600, m => 60, s => 1);
    (my $x = $v) =~ s/(\d+)ms//g;
    $s += $1 * $u{$2} while $x =~ s/(\d+)([wdhms])//;
    $s += $1 * 3600 + $2 * 60 + $3 if $x =~ /(\d+):(\d+):(\d+)/;
    return $s;
}

sub client_record {
    my ($r, $lease) = @_;
    my $mac = uc($r->{'mac-address'} // '');
    my $l   = $lease->{$mac} || {};
    my ($sig) = ($r->{signal} // $r->{'rx-signal'} // '') =~ /(-?\d+)/;
    my $user = $r->{'eap-username'};
    $user = $r->{'eap-identity'} unless defined $user && length $user;
    return {
        mac    => $mac,
        ssid   => $r->{ssid} // '',
        ap     => $r->{interface} // '',
        ip     => $r->{'dhcp-address'} || $r->{'last-ip'} || $l->{ip} || '',
        host   => $r->{'dhcp-hostname'} || $l->{host} || '',
        user   => $user // '',
        auth   => $r->{'auth-type'} // '',
        band   => $r->{band} // '',
        signal => (defined $sig ? $sig + 0 : undef),
        uptime => ros_seconds($r->{uptime}),
        vlan   => $r->{'vlan-id'} // '',
    };
}

sub lease_record {
    my ($r, $lease) = @_;
    return if defined $r->{status} && $r->{status} ne 'bound';
    my $mac = uc($r->{'active-mac-address'} || $r->{'mac-address'} || '');
    return unless $mac;
    $lease->{$mac} = { ip => $r->{'active-address'} || $r->{address} || '', host => $r->{'host-name'} // '' };
}

# registration table path that belongs to a remote-cap path that worked
sub reg_path { my $p = shift; $p =~ s{/capsman/remote-cap$}{/registration-table}; $p =~ s{^/caps-man/remote-cap$}{/caps-man/registration-table}; $p }
# radio and interface lists that belong to a registration table (to find the CAP of an interface)
sub radio_paths {
    my $p = shift;
    return ('/caps-man/radio', '/caps-man/interface') if $p =~ m{^/caps-man/};
    (my $b = $p) =~ s{/registration-table$}{};
    return ("$b/radio", $b);
}

my %RADIO_CACHE;     # controller -> {t, radios, ifaces} (SSH only; refreshed every 10 minutes)

# CAPsMAN interface (one per radio and per extra SSID) -> the access point (remote-cap identity)
# radios: /caps-man/radio or /interface/wifi/radio (interface, radio-mac, remote-cap identity)
# ifaces: /caps-man/interface or /interface/wifi (name, master-interface, radio-mac)
sub cap_iface_map {
    my ($radios, $ifaces, $caps) = @_;
    my %bymac = map { (uc($_->{mac} // '') => $_->{identity}) } grep { length($_->{mac} // '') } values %{ $caps || {} };
    my $ident = sub {
        my ($r) = @_;
        for my $k (qw(remote-cap-identity cap-identity cap remote-cap-name remote-cap)) {
            my $v = $r->{$k} // next;
            next unless length $v;
            if ($v =~ /([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5})/) { my $i = $bymac{ uc $1 }; return $i if length($i // ''); next }
            return $v;
        }
        return undef;
    };
    my (%map, %rmac);
    for my $r (@{ $radios || [] }) {
        my $id = $ident->($r) // next;
        $map{ $r->{interface} } = $id if length($r->{interface} // '');
        $rmac{ uc $r->{'radio-mac'} } = $id if length($r->{'radio-mac'} // '');
    }
    my %master;
    for my $i (@{ $ifaces || [] }) {
        my $n = $i->{name} // next;
        $map{$n} //= $rmac{ uc $i->{'radio-mac'} } if length($i->{'radio-mac'} // '') && $rmac{ uc $i->{'radio-mac'} };
        $master{$n} = $i->{'master-interface'} if length($i->{'master-interface'} // '') && $i->{'master-interface'} ne 'none';
    }
    for my $n (keys %master) {                         # extra SSIDs: the radio of their master interface
        my $m = $master{$n};
        for (1 .. 4) { last if defined $map{$m} || !defined $master{$m}; $m = $master{$m} }
        $map{$n} //= $map{$m} if defined $map{$m};
    }
    return \%map;
}

sub fetch_clients {
    my ($cm, $res) = @_;
    return fetch_clients_msm($cm, $res) if $cm->{method} eq 'msm';
    return fetch_clients_cnpilot($cm, $res) if $cm->{method} eq 'cnpilot';
    my @paths = map { reg_path($_) } @{ $res->{paths} || [] };
    die "no registration table path known\n" unless @paths;
    my (@clients, %lease, @radios, @ifaces);
    if ($cm->{method} eq 'api') {
        my $api = RosAPI->new(%$cm);
        my ($le) = $api->cmd('/ip/dhcp-server/lease/print');
        lease_record($_, \%lease) for @{ $le || [] };
        for my $p (@paths) {
            my ($re, $trap) = $api->cmd("$p/print");
            die "$p: $trap\n" if defined $trap;
            push @clients, map { client_record($_, \%lease) } @$re;
            my ($rp, $ip) = radio_paths($p);
            my ($ra, $rt) = $api->cmd("$rp/print");
            push @radios, @{ $ra || [] } unless defined $rt;
            my ($ia, $it) = $api->cmd("$ip/print");
            push @ifaces, @{ $ia || [] } unless defined $it;
        }
        $api->close;
    } else {
        # one SSH session: registration table(s), then the bound DHCP leases (IP and host name)
        my $cl = sub { (my $x = $_[0]) =~ s{(?<=.)/}{ }g; $x };
        my $remote = join('', map { qq{:put "--mtmon-reg--"; } . $cl->($_) . qq{ print terse without-paging; } } @paths)
                   . qq{:put "--mtmon-lease--"; /ip dhcp-server lease print terse without-paging where status=bound};
        my ($rc, $out) = ssh_exec($cm, $remote);
        my @lines = grep { /\S/ } map { s/\r//gr } split /\n/, $out;
        die "SSH to $cm->{host}:$cm->{port} failed: " . ($lines[0] // "exit code $rc") . "\n" if $rc == 255;
        if (my ($err) = grep { /\(line \d+ column \d+\)|^(?:bad command name|syntax error|expected end of command|no such command)|not enough permissions|^failure:/i } @lines) {
            die "MikroTik rejected the command: $err\n";
        }
        my ($sec, @reg, %seen) = ('');
        for my $l (@lines) {
            if ($l =~ /^--mtmon-(reg|radio|iface|lease)--$/) { $sec = $1; $seen{$1} = 1; next }
            my $r = parse_terse($l);
            next unless %$r;
            if    ($sec eq 'reg')   { push @reg, $r }
            elsif ($sec eq 'radio') { push @radios, $r }
            elsif ($sec eq 'iface') { push @ifaces, $r }
            elsif ($sec eq 'lease') { lease_record($r, \%lease) }
        }
        die "unexpected answer from the MikroTik (registration table not printed)\n" unless $seen{lease};
        @clients = map { client_record($_, \%lease) } @reg;
        # which CAP an interface belongs to: a separate session (RouterOS checks a whole script
        # before it runs it, so a missing menu must not break the clients), kept 10 minutes
        my $rc_ = $RADIO_CACHE{ $cm->{name} };
        if (!$rc_ || time - $rc_->{t} > 600) {
            my (@ra, @if);
            for my $p (@paths) {
                my ($rp, $ip) = radio_paths($p);
                for my $x ([ $rp, \@ra ], [ $ip, \@if ]) {
                    my ($rc2, $o2) = eval { ssh_exec($cm, $cl->($x->[0]) . ' print terse without-paging') };
                    next unless defined $rc2 && $rc2 == 0 && defined $o2;
                    my @l = grep { /\S/ } map { s/\r//gr } split /\n/, $o2;
                    next if grep { /bad command name|syntax error|no such command|expected end of command/i } @l;
                    push @{ $x->[1] }, grep { %$_ } map { parse_terse($_) } @l;
                }
            }
            $rc_ = $RADIO_CACHE{ $cm->{name} } = { t => time, radios => \@ra, ifaces => \@if };
        }
        @radios = @{ $rc_->{radios} };
        @ifaces = @{ $rc_->{ifaces} };
    }
    @clients = grep { length $_->{mac} } @clients;
    length $_->{ssid} or $_->{ssid} = '(no SSID)' for @clients;
    # the access point is the CAP (one per device), not its radio / SSID interface
    my $map = cap_iface_map(\@radios, \@ifaces, $res->{caps});
    # fallback: interface named after its CAP (provisioning name-format with %I, e.g. "Recepcija-2g")
    my @ids = sort { length($b) <=> length($a) } grep { length } map { $_->{identity} // '' } values %{ $res->{caps} || {} };
    my %idset = map { ($_ => 1) } @ids;
    my ($hit, %miss) = (0);
    for my $c (@clients) {
        my $if = $c->{ap} // '';
        $c->{radio} = $if;
        my $id = $map->{$if};
        if (!defined $id && length $if && !$idset{$if}) {
            ($id) = grep { index(lc $if, lc $_) == 0 && length($if) > length($_) } @ids;
            $map->{$if} = $id if defined $id;
        }
        if (defined $id) { $c->{ap} = $id; $hit++ }
        elsif ($idset{$if}) { $hit++ }                          # already the CAP name
        else { $miss{$if}++ }
    }
    $res->{_ifmap} = { %$map };
    $res->{_ifmiss} = \%miss;
    logmsg('debug', "$cm->{name}: " . scalar(keys %$map) . " CAPsMAN interface(s) mapped to their CAP, $hit of " . scalar(@clients) . " client(s)"
         . (%miss ? '; not assigned: ' . join(', ', sort keys %miss) : ''));
    return \@clients;
}

# HP MSM: client table column by column; the MAC column decides which clients exist.
sub fetch_clients_msm {
    my ($cm, $res) = @_;
    my $base = $MSM_CLI{base};
    my $t0 = time;
    my $delay = $cm->{retry_delay} || 3;
    my %col;
    # MAC column: retried until clients_max_wait; "No Such Object" with 0 stations = no clients
    while (1) {
        my ($st, $lines, $why) = msm_walk($cm, "$base.2");
        if ($st eq 'ok') { $col{2} = $lines; last }
        die "$why\n" if $st eq 'error';
        my ($rc, $out) = eval { run_cmd(($cm->{timeout} || 1) * ($cm->{retries} + 1) + 10,
                                        'snmpget', '-On', '-Oqv', msm_auth($cm), $cm->{host}, $MSM_CLI{count}) };
        return [] if defined $rc && $rc == 0 && ($out // '') =~ /^\s*0\s*$/;
        my $waited = time - $t0;
        die "SNMP to $cm->{host}: no answer from the client table within ${waited}s ($why)\n"
            if $waited + $delay > $cm->{clients_max_wait};
        logmsg('debug', "$cm->{name}: client table not readable ($why), retry in ${delay}s");
        sleep $delay;
        die "SNMP to $cm->{host}: interrupted\n" if $reload || !$running;
        $delay = $delay * 2 > 15 ? 15 : $delay * 2;
    }
    # the other columns are details: one retry each, missing values stay empty
    for my $c (grep { $_ != 2 } sort { $a <=> $b } keys %{ $MSM_CLI{cols} }) {
        for my $try (1, 2) {
            my ($st, $lines) = msm_walk($cm, "$base.$c");
            if ($st eq 'ok') { $col{$c} = $lines; last }
            sleep 2 if $try == 1;
        }
    }
    my %v;    # col -> index -> value
    for my $c (keys %col) {
        for my $r (msm_parse(@{ $col{$c} })) {
            my ($o, $type, $val) = @$r;
            next unless $o =~ /^\Q$base.$c\E\.(.+)$/;
            my $idx = $1;
            $val = msm_str($val);
            $v{$c}{$idx} = $c == 2 ? msm_mac($type, $val) : $val;
        }
    }

    # VSC -> SSID (configuration, cached for an hour)
    my $cache = $MSM_CACHE{ $cm->{name} } ||= {};
    if (!$cache->{t} || time - $cache->{t} > 3600) {
        my %new;
        for my $k ([ map => $MSM_CLI{vsc_map} ], [ ssid => $MSM_CLI{vsc_ssid} ]) {
            my ($st, $lines) = msm_walk($cm, $k->[1]);
            next unless $st eq 'ok';
            for my $r (msm_parse(@$lines)) {
                my ($o, undef, $val) = @$r;
                next unless $o =~ /^\Q$k->[1]\E\.(.+)$/;
                my $idx = $1;
                $val = msm_str($val);
                $new{ $k->[0] }{$idx} = $k->[0] eq 'map' ? msm_int($val) : $val;
            }
        }
        if ($new{ssid}) { %$cache = (%new, t => time) }
    }
    # user names of controller-authenticated sessions (802.1X / HTML / MAC), joined by MAC.
    # Optional: not every MSM has sessions; names are kept for a day if a read fails.
    my $users = $MSM_USERS{ $cm->{name} } ||= {};
    my %pa;
    for my $k ([ name => $MSM_CLI{pa_name} ], [ mac => $MSM_CLI{pa_mac} ]) {
        my ($st, $lines) = msm_walk($cm, $k->[1]);
        next unless $st eq 'ok';
        for my $r (msm_parse(@$lines)) {
            my ($o, $type, $val) = @$r;
            next unless $o =~ /^\Q$k->[1]\E\.(.+)$/;
            my $idx = $1;
            $val = msm_str($val);
            $pa{$idx}{ $k->[0] } = $k->[0] eq 'mac' ? msm_mac($type, $val) : $val;
        }
    }
    for my $p (values %pa) { $users->{ $p->{mac} } = [ $p->{name}, time ] if $p->{mac} && length($p->{name} // '') }
    delete @$users{ grep { time - $users->{$_}[1] > 86400 } keys %$users };

    my $apn = $res->{ap_names} || {};
    my @clients;
    for my $idx (keys %{ $v{2} }) {
        my ($dev, $radio) = split /\./, $idx;
        my $vsc = msm_int($v{3}{$idx} // '');
        my $cfgi = $cache->{map}{"$dev.$radio.$vsc"} // $vsc;
        my $ssid = $cache->{ssid}{$cfgi} // (length $vsc ? "VSC $vsc" : '');
        my $mac = $v{2}{$idx};
        my ($sig) = ($v{5}{$idx} // '') =~ /(-?\d+)/;
        my ($up)  = ($v{4}{$idx} // '') =~ /(\d+)/;
        my $ip = $v{17}{$idx} // '';
        $ip = '' if $ip eq '0.0.0.0';
        push @clients, {
            mac => $mac, ssid => $ssid, ap => $apn->{$dev} // "AP $dev", ip => $ip, host => '',
            user => ($users->{$mac} ? $users->{$mac}[0] : ''),
            auth => (msm_int($v{12}{$idx} // '') eq '1' ? '802.1X' : ''),
            band => '', signal => (defined $sig ? $sig + 0 : undef), uptime => (defined $up ? $up + 0 : undef), vlan => '',
        };
    }
    length $_->{ssid} or $_->{ssid} = '(no SSID)' for @clients;
    return \@clients;
}

# after a check: collect clients of the controllers that answered, write clients.json + history
sub collect_clients {
    my ($cfg, $answered, $now) = @_;
    my $g = $cfg->{general};
    my $file = data_file($g, 'clients.json');
    my $old = eval { open(my $fh, '<:raw', $file) or die; local $/; JSON::PP->new->utf8->decode(<$fh>) } || {};
    my %ctl;
    my %ans = map { $_->[0]{name} => $_ } @$answered;
    for my $cm (grep { client_enabled($cfg, $_) } @{ $cfg->{capsman} }) {
        last if $reload || !$running;
        my $prev = $old->{ctl}{ $cm->{name} };
        my $hit = $ans{ $cm->{name} };
        if (!$hit) {                                            # controller not reachable this cycle
            $ctl{ $cm->{name} } = { %{ $prev || {} }, error => 'controller not reachable', error_t => $now } if $prev;
            next;
        }
        my $t = time;
        my $list = eval { fetch_clients($cm, $hit->[1]) };
        if (!$list) {
            (my $e = $@ || 'unknown error') =~ s/\s+$//;
            logmsg('warn', "$cm->{label} '$cm->{name}': reading Wi-Fi clients failed: $e");
            $ctl{ $cm->{name} } = { %{ $prev || {} }, error => $e, error_t => $now };
            next;
        }
        my (%n, %ap);
        $n{ $_->{ssid} }++ for @$list;
        $ap{ length($_->{ap} // '') ? $_->{ap} : '(unknown AP)' }++ for @$list;
        $ctl{ $cm->{name} } = { t => $now, ssids => \%n, aps => \%ap, clients => [ sort { $a->{ssid} cmp $b->{ssid} || $a->{mac} cmp $b->{mac} } @$list ],
                                ifmap => { %{ ($prev || {})->{ifmap} || {} }, %{ $hit->[1]{_ifmap} || {} } } };
        logmsg('debug', "$cm->{label} '$cm->{name}': " . scalar(@$list) . " Wi-Fi clients ("
            . join(', ', map { "$_ $n{$_}" } sort keys %n) . "), " . (time - $t) . " s");
    }
    my ($fh, $tmp) = tempfile('.clients-XXXXXX', DIR => dirname($file));
    binmode $fh;
    print {$fh} JSON::PP->new->utf8->canonical->encode({ t => $now, ctl => \%ctl });
    close $fh or die "Writing $file failed: $!\n";
    rename($tmp, $file) or die "Cannot rename $tmp to $file: $!\n";
    my %h = map { $_ => $ctl{$_}{ssids} } grep { ($ctl{$_}{t} // 0) == $now } keys %ctl;
    if (%h) {
        append_jsonl($g, 'clients.jsonl', { t => $now, c => \%h });
        central_queue($cfg, 'clients', { t => $now, c => \%h });
        # clients per access point (for the per-AP charts and the client report)
        my $ap = { t => $now, c => { map { ($_ => $ctl{$_}{aps} || {}) } keys %h } };
        append_jsonl($g, 'clientsap.jsonl', $ap);
        central_queue($cfg, 'clientsap', $ap);          # mtmon-admin-center 5.1.0+ (older ones skip it)
    }
    hist_maintain($g, 'clients', $now);
    hist_maintain($g, 'clientsap', $now);
}

sub client_enabled {
    my ($cfg, $cm) = @_;
    return 0 unless ($cfg->{web}{enabled} || $cfg->{central}{enabled}) && $cfg->{web}{clients};
    return !(($cm->{clients} // '') =~ /^(0|no|ne|false|off)$/i);
}

# --rename-ssid OLD NEW [CONTROLLER]: rename an SSID in the Wi-Fi client history (e.g. names
# that were cut at the first space before 8.0.7). If NEW is already there the numbers are added.
sub rename_ssid {
    my ($cfg, $old, $new, $only) = @_;
    my $g = $cfg->{general};
    my $lock = lock_state($cfg);                         # no check writes meanwhile
    my $js = JSON::PP->new->utf8->canonical;
    my $total = 0;
    for my $name (qw(clients.jsonl clients-1h.jsonl clients-1d.jsonl)) {
        my $f = data_file($g, $name);
        next unless -e $f;
        my ($n, @out) = (0);
        for my $l (read_lines($f)) {
            my $rec = eval { $js->decode($l) };
            if (!$rec) { push @out, $l; next }
            for my $k (keys %{ $rec->{c} || {} }) {
                next if defined $only && $k ne $only;
                my $o = $rec->{c}{$k};
                next unless exists $o->{$old};
                my $v = delete $o->{$old};
                if (!exists $o->{$new}) { $o->{$new} = $v }
                elsif (ref $v) { $o->{$new} = [ $o->{$new}[0] + $v->[0], $o->{$new}[1] + $v->[1] ] }
                else           { $o->{$new} += $v }
                $n++;
            }
            push @out, $js->encode($rec) . "\n";
        }
        next unless $n;
        my ($fh, $tmp) = tempfile('.rename-XXXXXX', DIR => dirname($f));
        binmode $fh;
        print {$fh} @out;
        close $fh or die "Writing $f failed: $!\n";
        rename($tmp, $f) or die "Cannot rename $tmp to $f: $!\n";
        printf "%-18s %d record(s) changed\n", $name, $n;
        $total += $n;
    }
    close $lock;
    print $total ? "'$old' renamed to '$new'" . (defined $only ? " for $only" : '') . ".\n"
                 : "No '$old' found" . (defined $only ? " for $only" : '') . " - nothing changed.\n";
    return 0;
}

# --clients: read the clients now and print them (testing, changes nothing)
sub show_clients {
    my ($cfg) = @_;
    my $ok = 1;
    for my $cm (@{ $cfg->{capsman} }) {
        print "== $cm->{name}  [" . ($cm->{method} eq 'msm' ? 'HP MSM' : $cm->{method}) . "] $cm->{host}\n";
        if (($cm->{clients} // '') =~ /^(0|no|ne|false|off)$/i) { print "   clients = no in this section\n\n"; next }
        my $res = eval { fetch_caps($cm) };
        if (!$res) { print "   ERROR: $@\n"; $ok = 0; next }
        my $t = time;
        my $list = eval { fetch_clients($cm, $res) };
        if (!$list) { print "   ERROR reading clients: $@\n"; $ok = 0; next }
        my %n;
        $n{ $_->{ssid} }++ for @$list;
        printf "   clients: %d in %d s   %s\n", scalar @$list, time - $t, join(', ', map { "$_: $n{$_}" } sort keys %n);
        if ($cm->{method} !~ /^(msm|cnpilot)$/) {
            my %ap; $ap{ $_->{ap} }++ for @$list;
            my $miss = $res->{_ifmiss} || {};
            printf "   access points: %d remote CAP(s), clients on %d of them%s\n", scalar(keys %{ $res->{caps} || {} }),
                scalar(grep { !$miss->{$_} } keys %ap),
                (%$miss ? "; interfaces NOT assigned to a CAP: " . join(', ', map { "$_ ($miss->{$_})" } sort keys %$miss)
                        . " - please send the output of: /interface wifi radio print detail  (v6: /caps-man radio print detail)" : '');
        }
        printf "   %-17s %-16s %-24s %-15s %-20s %-12s %5s %s\n", qw(MAC SSID User IP Host/AP Auth Sig Connected) if @$list;
        for my $c (sort { $a->{ssid} cmp $b->{ssid} || ($a->{user} // '') cmp ($b->{user} // '') } @$list) {
            printf "   %-17s %-16s %-24s %-15s %-20s %-12s %5s %s\n", $c->{mac}, $c->{ssid}, $c->{user} || '-', $c->{ip} || '-',
                ($c->{host} ? "$c->{host} \@$c->{ap}" : $c->{ap}) || '-', $c->{auth} || '-',
                $c->{signal} // '-', defined $c->{uptime} ? fmt_dur($c->{uptime}) : '-';
        }
        print "\n";
    }
    print "Note: [web] is disabled - the daemon collects clients only for the dashboard.\n" unless $cfg->{web}{enabled};
    return $ok;
}

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";
}

# /api/clients: current clients per controller (without details when client_details = no)
sub web_clients {
    my ($cfg, $who) = @_;
    my $w = $cfg->{web};
    # names, MAC and IP of the clients: only with client_details = yes and for users with role full
    my $details = $w->{client_details} && (!$who || $who->{role} eq 'full');
    my $cur = eval { open(my $fh, '<:raw', data_file($cfg->{general}, 'clients.json')) or die; local $/; JSON::PP->new->utf8->decode(<$fh>) } || {};
    my @ctl;
    for my $cm (grep { client_enabled($cfg, $_) } @{ $cfg->{capsman} }) {
        my $c = $cur->{ctl}{ $cm->{name} } || {};
        push @ctl, { name => $cm->{name}, heading => dev_heading($cm), label => $cm->{label}, host => $cm->{host},
                     t => $c->{t}, error => $c->{error}, error_t => $c->{error_t}, ssids => $c->{ssids} || {}, aps => $c->{aps} || {},
                     ifmap => $c->{ifmap} || {},
                     ($details ? (clients => [ grep { length($_->{mac} // '') } @{ $c->{clients} || [] } ]) : ()) };
    }
    return { enabled => ($w->{clients} ? JSON::PP::true : JSON::PP::false),
             details => ($details ? JSON::PP::true : JSON::PP::false),
             details_off => (!$w->{client_details} ? 'config' : !$details ? 'role' : ''), t => $cur->{t}, controllers => \@ctl };
}

# ==========================================================================
# --discover: devices from the MikroTik neighbor tables (/ip neighbor = MNDP,
# LLDP, CDP) as ready-to-copy [switches] lines. Changes nothing.
# ==========================================================================
sub fetch_neighbors {
    my ($cm) = @_;
    my @rows;
    if ($cm->{method} eq 'api') {
        my $api = RosAPI->new(%$cm);
        my ($re, $trap) = $api->cmd('/ip/neighbor/print');
        $api->close;
        die "MikroTik rejected /ip neighbor print: $trap\n" if defined $trap;
        @rows = @$re;
    } else {
        my ($rc, $out) = ssh_exec($cm, '/ip neighbor print terse without-paging');
        my @lines = grep { /\S/ } map { s/\r//gr } split /\n/, $out;
        if ($rc == 255) {
            my @e = grep { !/^\*\*|^\s*\*\*|WARNING|vulnerable to .*store now, decrypt later|upgraded/i } @lines;
            die "SSH to $cm->{host}:$cm->{port} failed: " . ($e[0] // $lines[0] // "exit code $rc") . "\n";
        }
        if (my ($err) = grep { /\(line \d+ column \d+\)|not enough permissions|^failure:|^bad command name|^syntax error/i } @lines) {
            die "MikroTik rejected /ip neighbor print: $err\n";
        }
        @rows = grep { %$_ } map { parse_terse($_) } @lines;
    }
    my $ipv4 = qr/^\d{1,3}(?:\.\d{1,3}){3}$/;
    my @n;
    for my $r (@rows) {
        my ($ip) = grep { defined && /$ipv4/ } ($r->{address4}, $r->{address});
        my $desc = $r->{board} || $r->{platform} || '';
        $desc = "$r->{platform} $desc" if $r->{platform} && $r->{board} && $r->{board} !~ /\Q$r->{platform}\E/i;
        if (!$desc && $r->{'system-description'}) {
            ($desc = $r->{'system-description'}) =~ s/\s+/ /g;
            $desc =~ s/,.*//;                                         # "model, firmware" -> model
            $desc = substr($desc, 0, 60) =~ s/\s+\S*$//r if length $desc > 60;
        }
        my ($ver) = ($r->{version} // '') =~ /^(\d[\w.]*)/;
        $desc .= " $ver" if defined $ver && ($r->{platform} // '') =~ /mikrotik/i;
        push @n, {
            ip        => $ip,
            mac       => uc($r->{'mac-address'} // ''),
            identity  => $r->{identity} // '',
            desc      => $desc,
            interface => $r->{interface} // $r->{'interface-name'} // '',
            via       => $r->{'discovered-by'} // '',
        };
    }
    return \@n;
}

sub discover {
    my ($cfg) = @_;
    my @src = grep { !is_snmp_ctl($_) } @{ $cfg->{capsman} };
    if (!@src) {
        print STDERR "No enabled [capsman] MikroTik is configured - nothing to ask for neighbors.\n";
        return 0;
    }

    # what is already monitored: switches, controllers, known access points
    my $state = load_state($cfg->{general}{state_file});
    my (%known, %known_mac);
    $known{ $_->[0] } = 'in [switches]' for @{ $cfg->{switches} };
    $known{ $_->{host} } = "$_->{label} $_->{name}" for @{ $cfg->{capsman} };
    for my $cs (values %{ $state->{capsman} || {} }) {
        for my $c (values %{ $cs->{caps} || {} }) {
            $known{ $c->{ip} } //= 'access point' if $c->{ip};
            $known_mac{ uc $c->{mac} } = 1 if $c->{mac};
        }
    }

    my (%dev, @noip, $ok);
    for my $cm (@src) {
        my $n = eval { fetch_neighbors($cm) };
        if (!$n) { print "# $cm->{name} ($cm->{host}): ERROR $@"; next }
        $ok++;
        for my $d (@$n) {
            if (!$d->{ip}) { push @noip, { %$d, src => $cm->{name} }; next }
            my $e = $dev{ $d->{ip} } ||= { %$d, seen => [] };
            $e->{$_} ||= $d->{$_} for qw(identity desc mac);
            my %via = map { $_ => 1 } grep { length } split /,/, join ',', $e->{via} // '', $d->{via};
            $e->{via} = join ',', sort keys %via;
            push @{ $e->{seen} }, "$cm->{name}" . ($d->{interface} ? " on $d->{interface}" : '');
        }
    }
    return 0 unless $ok;

    my (@new, @have);
    for my $ip (sort { pack('C4', split /\./, $a) cmp pack('C4', split /\./, $b) } keys %dev) {
        my $d = $dev{$ip};
        my $why = $known{$ip} // ($d->{mac} && $known_mac{ $d->{mac} } ? 'access point' : undef);
        if ($why) { push @have, [ $d, $why ] } else { push @new, $d }
    }

    print "# mtmon --discover, " . fmt_time(time) . " - neighbors of: "
        . join(', ', map { "$_->{name} ($_->{host})" } @src) . "\n";
    print "# Review the lines below and copy the ones you want into [switches].\n\n";
    if (@new) {
        print "# ---- new devices (" . scalar(@new) . ") ----\n";
        for my $d (@new) {
            my $name = $d->{identity} || $d->{mac} || $d->{ip};
            my %seen = map { $_ => 1 } @{ $d->{seen} };
            print "# seen by " . join(', ', sort keys %seen) . ($d->{via} ? " ($d->{via})" : '') . "\n";
            print "$d->{ip} = $name" . ($d->{desc} ? " ($d->{desc})" : '') . "\n";
        }
    } else {
        print "# ---- no new devices: everything found is already monitored ----\n";
    }
    if (@have) {
        print "\n# ---- already monitored (" . scalar(@have) . ") ----\n";
        printf "#   %-15s %-28s %s\n", $_->[0]{ip}, ($_->[0]{identity} || '-'), $_->[1] for @have;
    }
    if (@noip) {
        print "\n# ---- neighbors without an IPv4 address (cannot be pinged) ----\n";
        printf "#   %-17s %-28s %s\n", ($_->{mac} || '-'), ($_->{identity} || '-'), "seen by $_->{src}"
            . ($_->{interface} ? " on $_->{interface}" : '') for @noip;
    }
    return 1;
}

# --check: test the connection to every device and print what it sees
sub check_devices {
    my ($cfg) = @_;
    my $all_ok = 1;
    for my $cm (@{ $cfg->{capsman} }) {
        print $cm->{method} eq 'msm'     ? "== $cm->{name}  [HP MSM, SNMP v$cm->{snmp_version}] $cm->{host}\n"
            : $cm->{method} eq 'cnpilot' ? "== $cm->{name}  [cnPilot, SNMP v$cm->{snmp_version}] " . join(', ', @{ $cm->{aps} }) . "\n"
            :                              "== $cm->{name}  [$cm->{method}] $cm->{host}:$cm->{port}\n";
        my $res = eval { fetch_caps($cm) };
        if (!$res) { print "   ERROR: $@\n"; $all_ok = 0; next }
        my @c = values %{ $res->{caps} };
        print "   identity: " . ($res->{identity} || '-') . "\n";
        print "   path:     " . join(', ', @{ $res->{paths} }) . "\n";
        print "   APs:      " . scalar(@c) . ($cm->{method} eq 'msm' ? ' running' : $cm->{method} eq 'cnpilot' ? ' answering' : '') . "\n";
        print cap_table(\@c, undef, col4($cm)) =~ s/^/ /mgr if @c;
        if ($cm->{method} eq 'cnpilot') {
            print "   No SNMP answer: " . join(', ', @{ $res->{silent} }) . "\n" if @{ $res->{silent} || [] };
            my %by;
            for my $r (values %{ $res->{_cnp} || {} }) {
                next if $r->{err};
                $by{ $_->{ssid} } += $_->{clients} for @{ $r->{wlans} || [] };
            }
            my $tot = 0; $tot += $_->{clients} // 0 for @c;
            print "   Wi-Fi clients: $tot" . (%by ? ' (' . join(', ', map { "$_ $by{$_}" } sort keys %by) . ')' : '') . "\n";
            my $listed = 0;
            $listed += @{ $_->{clients} || [] } for grep { !$_->{err} } values %{ $res->{_cnp} || {} };
            print "   Client tables: $listed client(s) listed with MAC/IP"
                . ($listed < $tot ? " - the rest is counted without details" : '') . "\n";
        }
        if (my @o = @{ $res->{other} || [] }) {
            print "   Listed on the controller but not running: " . scalar(@o) . " (not monitored as present)\n";
            print cap_table(\@o, undef, col4($cm)) =~ s/^/ /mgr;
        }
        print "\n";
    }
    if (my @sw = @{ $cfg->{switches} }) {
        my $res = ping_hosts([ map { $_->[0] } @sw ], $cfg->{general});
        print "== Switches (ping)\n";
        printf "   %-15s %-34s %s\n", $_->[0], $_->[1], $res->{ $_->[0] } ? 'OK' : 'NOT RESPONDING' for @sw;
        my @sn = grep { $_->[2]{snmp} } @sw;
        if (@sn) {
            print "\n== Switches (SNMP)\n";
            my $r = snmp_collect($cfg->{general}, [ map { $_->[2] } grep { $res->{ $_->[0] } } @sn ], 1);
            for my $s (@sn) {
                my ($h, $d, $o) = @$s;
                print "   $h  $d\n";
                my $x = $r->{$h};
                if (!$x) { print "      not checked (no ping answer)\n"; next }
                if ($x->{err}) { print "      ERROR: $x->{err}\n"; $all_ok = 0; next }
                my @eth = grep { $_->{eth} } @{ $x->{ports} };
                printf "      %s\n      uptime %s, %d ports (%d up)%s%s\n", substr($x->{descr} || '-', 0, 100), fmt_dur($x->{uptime}), scalar @eth,
                    scalar(grep { $_->{oper} == 1 } @eth),
                    ($x->{poe} ? sprintf(', PoE %s of %s W', $x->{poe}{used}, $x->{poe}{power}) : ''),
                    ($x->{temp} ? ', ' . join(', ', map { "$_->[0] $_->[1] °C" } @{ $x->{temp} }[0 .. ($#{ $x->{temp} } > 2 ? 2 : $#{ $x->{temp} })]) : '');
                for my $u (@{ $o->{uplinks} }) {
                    my $p = uplink_port($x->{ports}, $u->[0]);
                    printf "      uplink %-10s %s\n", $u->[0], !$p ? 'NOT FOUND - use the port name, e.g. ' . join(', ', map { $_->{name} } @eth[0 .. ($#eth > 3 ? 3 : $#eth)])
                        : "-> $p->{name} (ifIndex $p->{i}): " . ($p->{admin} != 1 ? 'disabled' : $p->{oper} == 1 ? 'up, ' . fmt_speed($p->{speed}) : 'DOWN')
                          . (defined $u->[1] ? ', expected ' . fmt_speed($u->[1]) : '');
                }
                print "      inventory: " . join(', ', map { "$_ $x->{inv}{$_}" } grep { $x->{inv}{$_} } qw(model serial version firmware)) . "\n" if $x->{inv} && %{ $x->{inv} };
            }
        }
    }
    return $all_ok;
}

# ==========================================================================
# Mail
# ==========================================================================
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." . time . ".$$\@$host>\n"
            . "MIME-Version: 1.0\n"
            . "X-Mailer: mtmon $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;
}

# ==========================================================================
# Configuration
# ==========================================================================
# ==========================================================================
# --config-upgrade: after a package upgrade, the active config gets the settings that are new in the
# template - each with its explanation, commented out (so nothing changes until you set it) - at the
# end of the section it belongs to, and the version line is updated. Nothing in the file is removed or
# changed. The old file is kept as FILE.bak-OLDVERSION, the new template as FILE.dist.
# Sections that are lists (users, API keys, sites, devices, certificates) only get named options.
# ==========================================================================
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;
}

# parse into sections: [ { key, header line index, lines => [idx...] } ], a commented "# [x]" ends a section
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;
}

sub load_config {
    my ($file) = @_;
    open(my $fh, '<:encoding(UTF-8)', $file) or die "Cannot open $file: $!\n";

    my %c = (
        general => {
            location => '',
            interval => 300, state_file => '/var/lib/mtmon/state.json',
            fail_threshold => 2, cap_miss_threshold => 2, remind_hours => 24,
            forget_after_days => 0, notify_new_caps => 1, notify_recovery => 1,
            ping_count => 3, ping_timeout => 1, ping_parallel => 32,
            flap_count => 4, flap_window => 60, flap_log => 'yes', inventory_hours => 24, disk_warn => 10, ap_ports_minutes => 15, topology_hours => 6,
        },
        report => { enabled => 'yes', weekly => 'yes', monthly => 'yes', time => '07:00', to => '' },
        certs => { enabled => 'yes', warn_days => '30,14,7,3,1', web => 'yes', check_hours => 24, timeout => 10, list => [] },
        snmp => {           # SNMP of the [switches] devices (off unless snmp = yes)
            snmp => 'no', snmp_version => '2c', community => 'public', user => '', auth_proto => 'SHA', auth_pass => '',
            priv_proto => 'AES', priv_pass => '', timeout => 2, retries => 1,
            error_rate => 10, poe_warn => 90, temp_warn => 70,
        },
        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@' . hostname(), to => '', subject_prefix => '[mtmon]', format => 'html',
            sendmail => '/usr/sbin/sendmail',
        },
        web => {
            enabled => 0, listen => '0.0.0.0', port => 8686, allow => '', user => '', password => '',
            refresh => 30, history_days => 30, history_hourly_days => 400, session_hours => 12, max_per_ip => 24, html => '/usr/share/mtmon/dashboard.html',
            clients => 'yes', client_details => 'yes', tls => 'yes', cert_file => '/etc/mtmon/web.crt', key_file => '/etc/mtmon/web.key',
        },
        central => {
            enabled => 'no', url => '', key => '', fingerprint => '', tls_verify => 'yes',
            send_client_details => 'yes', timeout => 20,
        },
        ssh => {
            user => 'mtmon', key => '/etc/mtmon/id_ed25519', port => 22,
            known_hosts => '/var/lib/mtmon/known_hosts', host_key_check => 'accept-new',
            timeout => 15, user_suffix => '+ct', extra_options => '',
        },
        capsman  => [],
        switches => [],
    );

    my ($sec, $cur, @raw);
    while (my $l = <$fh>) {
        $l =~ s/^\s+//;
        $l =~ s/\s+$//;
        next if $l eq '' || $l =~ /^[#;]/;
        if ($l =~ /^\[\s*(.+?)\s*\]$/) {
            $sec = $1;
            if ($sec =~ /^capsman(?:[\s:]+(.+))?$/i) {
                $cur = { name => $1 // 'capsman' . (@raw + 1) };
                push @raw, $cur;
                $sec = 'capsman';
            } elsif ($sec =~ /^msm(?:[\s:]+(.+))?$/i) {      # HP MSM controller (SNMP)
                $cur = { name => $1 // 'msm' . (@raw + 1), _kind => 'msm' };
                push @raw, $cur;
                $sec = 'capsman';
            } elsif ($sec =~ /^cnpilot(?:[\s:]+(.+))?$/i) {  # Cambium cnPilot access points (SNMP, each AP)
                $cur = { name => $1 // 'cnpilot' . (@raw + 1), _kind => 'cnpilot' };
                push @raw, $cur;
                $sec = 'capsman';
            } elsif (lc($sec) =~ /^web[\s_]+users$/) {      # dashboard users: name = password [role=...]
                $sec = 'web_users';
            } elsif (lc($sec) =~ /^api[\s_]+keys$/) {       # API keys: name = {SHA256}... [role=...] [allow=...]
                $sec = 'api_keys';
            } elsif (($sec = lc $sec) !~ /^(general|mail|ssh|switches|web|central|report|certificates)$/) {
                die "$file:$.: unknown section [$sec]\n";
            }
            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 'switches' && lc $k eq 'title') {
            $c{general}{_switches_title} = $v;
        }
        elsif ($sec eq 'switches' && lc $k eq 'enabled') {
            $c{general}{_switches_enabled} = $v;
        }
        elsif ($sec eq 'switches' && $k =~ /^(snmp|snmp_version|community|snmp_user|snmp_auth_proto|snmp_auth_pass|snmp_priv_proto|snmp_priv_pass|snmp_timeout|snmp_retries|error_rate|poe_warn|temp_warn)$/i) {
            (my $sk = lc $k) =~ s/^snmp_(?!version)//;
            $c{snmp}{$sk} = $v;
        }
        elsif ($sec eq 'switches') {
            die "$file:$.: invalid address '$k'\n" if $k =~ /^-/ || $k =~ /\s/;
            # "description | uplinks=49,50 community=x snmp=no": options for this device after a |
            my %o;
            if ($v =~ s/\s*\|\s*(.*)$//) {
                my $opt = $1;
                while ($opt =~ /\G\s*([A-Za-z_]+)\s*=\s*("[^"]*"|\S+)/gc) { my ($k2, $x) = ($1, $2); $x =~ s/^"|"$//g; $o{ lc $k2 } = $x }
                die "$file:$.: $k: cannot read the options after | (expected key=value)\n" if ($opt =~ /\G\s*(\S.*)$/gc);
            }
            push @{ $c{switches} }, [ $k, $v ne '' ? $v : $k, \%o, $. ];
        }
        elsif ($sec eq 'certificates' && $k =~ /^(enabled|warn_days|web|check_hours|timeout)$/i) { $c{certs}{ lc $k } = $v }
        elsif ($sec eq 'certificates') { push @{ $c{certs}{list} }, [ $k, $v, $. ] }
        elsif ($sec eq 'capsman') { $cur->{lc $k} = $v }
        elsif ($sec eq 'api_keys') {
            die "$file:$.: API key '$k' defined twice\n" if $c{api_keys}{ lc $k };
            $c{api_keys}{ lc $k } = [ $k, $v, $. ];
        }
        elsif ($sec eq 'web_users') {
            die "$file:$.: user '$k' defined twice in [web users]\n" if $c{web_users}{ lc $k };
            $c{web_users}{ lc $k } = [ $k, $v, $. ];
        }
        else                      { $c{$sec}{lc $k} = $v }
    }
    close $fh;
    if ($AGENT) {
        # 13.9 agent: the data is in RAM and the centre keeps the history, the reports and the mail -
        # here only what the checks need (two days), no own reports
        $c{general}{_agent} = 1;
        $c{web}{history_days} = 2;
        $c{web}{history_hourly_days} = 2;
        $c{report}{enabled} = 'no';
        $c{ssh}{known_hosts} = "$AGENT/known_hosts" if $c{ssh}{known_hosts} eq '/var/lib/mtmon/known_hosts';
    }

    # location (e.g. "Hotel Delfin"): shown in mails instead of the hostname and
    # available as $LOCATION / ${LOCATION} in any config value
    my $loc = $c{general}{location};
    $loc = hostname() unless defined $loc && length $loc;
    $c{general}{location} = $loc;
    my $expand = sub { $_[0] =~ s/\$\{LOCATION\}|\$LOCATION\b/$loc/g if defined $_[0] };
    for my $h ($c{general}, $c{mail}, $c{ssh}, @raw) { $expand->($_) for values %$h }
    $expand->($_->[1]) for @{ $c{switches} };
    delete $c{general}{_switches_title}
        unless defined $c{general}{_switches_title} && $c{general}{_switches_title} =~ /\S/;
    # [switches] enabled = no: all devices stay in the config but none is pinged
    if (defined(my $en = delete $c{general}{_switches_enabled})) {
        die "[switches] enabled must be yes or no\n" unless $en =~ /^(1|yes|da|true|on|0|no|ne|false|off)$/i;
        if ($en =~ /^(0|no|ne|false|off)$/i) {
            logmsg('debug', "[switches]: disabled (enabled = $en), " . scalar(@{ $c{switches} }) . " device(s) not pinged");
            $c{switches} = [];
        }
    }

    # [capsman NAME] -> one device per IP in "host" (several, comma separated, allowed)
    my %seen;
    for my $raw (@raw) {
        my $is_msm = ($raw->{_kind} // '') eq 'msm';
        my $is_cnp = ($raw->{_kind} // '') eq 'cnpilot';
        my $label  = $is_msm ? 'HP MSM' : $is_cnp ? 'cnPilot' : 'CAPsMAN';
        if (defined $raw->{enabled} && $raw->{enabled} =~ /^(0|no|ne|false|off)$/i) {
            logmsg('debug', "$label '$raw->{name}': disabled (enabled = $raw->{enabled})");
            next;
        }
        my $hosts = $raw->{host} // $raw->{hosts} // '';
        my @h = grep { length } split /[\s,;]+/, $hosts;
        if (!@h) {
            logmsg('warn', "$file: section [" . ($is_msm ? 'msm' : $is_cnp ? 'cnpilot' : 'capsman') . " $raw->{name}] has no host - skipped");
            next;
        }
        if ($is_cnp) {
            # one section = one group of access points; every AP is asked on its own
            my @aps = expand_hosts(@h);
            my %u;
            @aps = grep { !$u{$_}++ } @aps;
            for my $a (@aps) {
                die "cnPilot '$raw->{name}': '$a' is not an IP address or host name\n" unless $a =~ /^[\w.:-]+$/;
            }
            my %d = (
                snmp_version => '2c', community => 'public', timeout => 2, retries => 1, parallel => 16,
                user => '', auth_proto => 'SHA', auth_pass => '', priv_proto => 'AES', priv_pass => '',
                %$raw,
                method => 'cnpilot', label => $label, aps => \@aps,
                host => (@aps == 1 ? $aps[0] : scalar(@aps) . ' APs'),
            );
            delete @d{qw(hosts enabled _kind)};
            $d{snmp_version} = lc $d{snmp_version};
            $d{snmp_version} =~ s/^v//;
            $d{snmp_version} = '2c' if $d{snmp_version} eq '2';
            die "cnPilot '$d{name}': snmp_version must be 1, 2c or 3\n" unless $d{snmp_version} =~ /^(1|2c|3)$/;
            die "cnPilot '$d{name}': snmp_version = 3 requires user\n" if $d{snmp_version} eq '3' && !length $d{user};
            for my $k (qw(timeout retries parallel)) {
                die "cnPilot '$d{name}': $k must be a non-negative integer\n" unless $d{$k} =~ /^\d+$/;
            }
            $d{parallel} = 1 if $d{parallel} < 1;
            $d{parallel} = 64 if $d{parallel} > 64;
            $d{port} = '';
            die "Duplicate device name '$d{name}'\n" if $seen{ $d{name} }++;
            push @{ $c{capsman} }, \%d;
            next;
        }
        if ($is_msm) {
            for my $hp (@h) {
                # host or host:port (SNMP port, default 161): net-snmp takes "host:port" as it is
                my ($h, $hport) = host_port($hp, "HP MSM '$raw->{name}'");
                my %d = (
                    snmp_version => '2c', community => 'public', timeout => 5, retries => 2,
                    retry_delay => 3, max_wait => 90, clients_max_wait => 30,
                    user => '', auth_proto => 'SHA', auth_pass => '', priv_proto => 'AES', priv_pass => '',
                    %$raw,
                    method => 'msm', label => $label, host => ($hport ? ($h =~ /:/ ? "udp6:[$h]:$hport" : "$h:$hport") : $h),
                    name   => (@h > 1 ? "$raw->{name}/$h" : $raw->{name}),
                );
                delete @d{qw(hosts enabled _kind)};
                $d{snmp_version} = lc $d{snmp_version};
                $d{snmp_version} =~ s/^v//;
                $d{snmp_version} = '2c' if $d{snmp_version} eq '2';
                die "HP MSM '$d{name}': snmp_version must be 1, 2c or 3\n" unless $d{snmp_version} =~ /^(1|2c|3)$/;
                die "HP MSM '$d{name}': snmp_version = 3 requires user\n" if $d{snmp_version} eq '3' && !length $d{user};
                for my $k (qw(timeout retries retry_delay max_wait clients_max_wait)) {
                    die "HP MSM '$d{name}': $k must be a non-negative integer\n" unless $d{$k} =~ /^\d+$/;
                }
                $d{port} = '';
                die "Duplicate device name '$d{name}'\n" if $seen{ $d{name} }++;
                push @{ $c{capsman} }, \%d;
            }
            next;
        }
        my $method = lc($raw->{method} // 'ssh');
        die "CAPsMAN '$raw->{name}': method must be ssh or api\n" unless $method =~ /^(ssh|api)$/;

        for my $hp (@h) {
            # host or host:port ([IPv6]:port) - the port only for this device
            my ($h, $hport) = host_port($hp, "CAPsMAN '$raw->{name}'");
            my %d = (
                %{ $c{ssh} },
                ssl => 0, ssl_verify => 0, password => '', path => '',
                %$raw,
                method => $method,
                label  => $label,
                host   => $h,
                name   => (@h > 1 ? "$raw->{name}/$h" : $raw->{name}),
            );
            delete @d{qw(hosts enabled)};
            $d{port} = $hport || $raw->{port}
                    || ($method eq 'ssh' ? $c{ssh}{port} : ($d{ssl} ? 8729 : 8728));
            die "CAPsMAN '$d{name}': port must be 1-65535\n" unless $d{port} =~ /^\d+$/ && $d{port} >= 1 && $d{port} <= 65535;
            $d{timeout} ||= 15;
            die "CAPsMAN '$d{name}': user is not set\n" unless $d{user};
            if ($method eq 'ssh') {
                die "CAPsMAN '$d{name}': key is not set\n" unless $d{key};
                die "CAPsMAN '$d{name}': host_key_check must be yes, accept-new or no\n"
                    unless $d{host_key_check} =~ /^(yes|accept-new|no)$/;
                $d{extra_options} = [ grep { length } split /\s*,\s*/, ($d{extra_options} // '') ];
            } else {
                die "CAPsMAN '$d{name}': method = api requires a password\n" unless length $d{password};
            }
            die "Duplicate device name '$d{name}'\n" if $seen{ $d{name} }++;
            push @{ $c{capsman} }, \%d;
        }
    }
    for my $k (qw(interval fail_threshold cap_miss_threshold ping_count ping_timeout ping_parallel)) {
        die "[general] $k must be a positive integer\n" unless $c{general}{$k} =~ /^\d+$/ && $c{general}{$k} > 0;
    }
    die "[mail] method must be smtp or sendmail\n" unless $c{mail}{method} =~ /^(smtp|sendmail)$/;
    my $w = $c{web};
    $w->{enabled} = ($w->{enabled} // '') =~ /^(1|yes|da|true|on)$/i ? 1 : 0;
    $w->{tls}     = ($w->{tls} // '') =~ /^(0|no|ne|false|off)$/i ? 0 : 1;
    $w->{$_} = ($w->{$_} // '') =~ /^(0|no|ne|false|off)$/i ? 0 : 1 for qw(clients client_details);
    die "[web] port must be 1-65535\n" unless $w->{port} =~ /^\d+$/ && $w->{port} > 0 && $w->{port} < 65536;
    for my $k (qw(refresh history_days history_hourly_days session_hours max_per_ip)) {
        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,;]+/, $w->{allow} ];
    die "[web] password is required when user is set\n" if length $w->{user} && !length $w->{password};
    # dashboard users: [web] user/password (role full) and [web users] name = password [role=full|summary]
    my %u;
    $u{ lc $w->{user} } = { name => $w->{user}, secret => $w->{password}, role => 'full' } if length $w->{user};
    for my $e (values %{ $c{web_users} || {} }) {
        my ($name, $v, $line) = @$e;
        my $role = 'full';
        $role = lc $1 if $v =~ s/\s+role\s*=\s*(\S+)\s*$//i;
        die "$file:$line: [web users] $name: role must be full or summary\n" unless $role =~ /^(full|summary)$/;
        die "$file:$line: [web users] $name: no password\n" unless length $v;
        die "$file:$line: [web users] $name: unknown password hash (use mtmon --hash-password)\n"
            if $v =~ /^\{/ && $v !~ /^\{PBKDF2\}\d+\$[A-Za-z0-9+\/]+\$[A-Za-z0-9+\/]+$/;
        die "$file:$line: [web users] $name: invalid user name\n" if $name =~ /[\s:]/;
        die "$file:$line: [web users] $name is also [web] user\n" if $u{ lc $name };
        $u{ lc $name } = { name => $name, secret => $v, role => $role };
    }
    $w->{_users} = \%u;

    # API keys (scripts, apps): name = {SHA256}hash [role=full|summary] [allow=net,net]
    my %ak;
    for my $e (values %{ $c{api_keys} || {} }) {
        my ($name, $v, $line) = @$e;
        my %o = (role => 'full', allow => '');
        $o{ lc $1 } = $2 while $v =~ s/\s+(role|allow)\s*=\s*(\S+)\s*$//i;
        die "$file:$line: [api keys] $name: role must be full or summary\n" unless $o{role} =~ /^(full|summary)$/i;
        die "$file:$line: [api keys] $name: expected {SHA256}... (mtmon --new-api-key $name)\n" unless $v =~ /^\{SHA256\}([0-9a-f]{64})$/i;
        my @nets = map { parse_cidr($_) // die "$file:$line: [api keys] $name: invalid allow '$_'\n" } grep { length } split /\s*,\s*/, $o{allow};
        $ak{ lc $1 } = { name => "key:$name", role => lc $o{role}, _allow => \@nets };
    }
    $c{_api_keys} = \%ak;

    # [central]: send the status to an mtmon-admin-center after every check
    my $ce = $c{central};
    $ce->{enabled} = ($ce->{enabled} // '') =~ /^(1|yes|da|true|on)$/i ? 1 : 0;
    $ce->{$_} = ($ce->{$_} // '') =~ /^(0|no|ne|false|off)$/i ? 0 : 1 for qw(tls_verify send_client_details);
    if ($ce->{enabled}) {
        die "[central] url must start with https:// (or http:// for tests)\n" unless $ce->{url} =~ m{^https?://[^/\s]+}i;
        die "[central] key is not set (mtmon-admin-center --add-site NAME prints it)\n" unless $ce->{key} =~ /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{20,}$/;
        die "[central] fingerprint must look like sha256\$hex (mtmon-admin-center --fingerprint)\n"
            if length $ce->{fingerprint} && $ce->{fingerprint} !~ /^sha256\$[0-9a-f:]{64,95}$/i;
        die "[central] timeout must be a positive integer\n" unless $ce->{timeout} =~ /^\d+$/ && $ce->{timeout} > 0;
    }
    $c{general}{_history_days} = $w->{history_days};
    $c{general}{_history_hourly_days} = $w->{history_hourly_days};

    # flapping: flap_count drops within flap_window minutes (0 = off)
    for my $k (qw(flap_count flap_window inventory_hours disk_warn ap_ports_minutes topology_hours)) {
        die "[general] $k must be a whole number\n" unless $c{general}{$k} =~ /^\d+$/;
    }
    die "[general] disk_warn: percent of free disk space, 0 to 90\n" if $c{general}{disk_warn} > 90;
    die "[general] flap_window must be at least 10 minutes\n" if $c{general}{flap_count} && $c{general}{flap_window} < 10;
    $c{general}{flap_log} = yesno($c{general}{flap_log}, '[general] flap_log');

    # [report]: weekly / monthly summary mail
    my $rp = $c{report};
    $rp->{$_} = yesno($rp->{$_}, "[report] $_") for qw(enabled weekly monthly);
    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 ];

    # [certificates]: name = https://host[:port] | smtp://host[:port] | imap://... | host:port | file:/path
    my $ct = $c{certs};
    $ct->{$_} = yesno($ct->{$_}, "[certificates] $_") for qw(enabled web);
    die "[certificates] warn_days: days, comma separated (e.g. 30,14,7,3,1)\n" unless $ct->{warn_days} =~ /^\s*\d+(\s*,\s*\d+)*\s*$/;
    $ct->{_warn} = [ sort { $b <=> $a } map { $_ + 0 } split /\s*,\s*/, $ct->{warn_days} =~ s/^\s+|\s+$//gr ];
    for my $k (qw(check_hours timeout)) { die "[certificates] $k must be a positive number\n" unless $ct->{$k} =~ /^\d+$/ && $ct->{$k} > 0 }
    $ct->{_targets} = [ map { cert_target(@$_, $file) } @{ $ct->{list} } ];
    my %cn;
    $cn{ lc $_->{name} }++ and die "[certificates] name '$_->{name}' used twice\n" for @{ $ct->{_targets} };

    # SNMP of the [switches] devices
    my $sn = $c{snmp};
    $sn->{snmp} = yesno($sn->{snmp}, '[switches] snmp');
    for my $k (qw(timeout retries error_rate poe_warn temp_warn)) { die "[switches] $k must be a whole number\n" unless $sn->{$k} =~ /^\d+$/ }
    for my $sw (@{ $c{switches} }) {
        my ($h, $d, $o, $line) = @$sw;
        my %s = (%$sn, name => $d, host => $h);
        for my $k (keys %$o) {
            my $kk = $k;
            $kk =~ s/^snmp_(?!version)// unless $kk eq 'snmp';
            die "$file:$line: $h: unknown option '$k' (uplinks, snmp, community, snmp_version, snmp_user, ...)\n"
                unless $kk =~ /^(uplinks|snmp|snmp_version|community|user|auth_proto|auth_pass|priv_proto|priv_pass|timeout|retries|error_rate|poe_warn|temp_warn)$/;
            $s{$kk} = $o->{$k};
        }
        $s{snmp} = yesno($s{snmp}, "$h: snmp") if exists $o->{snmp};
        $s{snmp} = 1 if exists $o->{uplinks} && !exists $o->{snmp};       # uplinks given: SNMP is meant
        $s{snmp_version} = lc $s{snmp_version};
        $s{snmp_version} =~ s/^v//;
        $s{snmp_version} = '2c' if $s{snmp_version} eq '2';
        die "$file:$line: $h: snmp_version must be 1, 2c or 3\n" unless $s{snmp_version} =~ /^(1|2c|3)$/;
        die "$file:$line: $h: snmp_version = 3 requires snmp_user\n" if $s{snmp} && $s{snmp_version} eq '3' && !length $s{user};
        # uplinks=49,50  or with the expected speed  uplinks=49:10G,sfp-sfpplus1:10G
        my @up;
        for my $u (grep { length } split /\s*,\s*/, $s{uplinks} // '') {
            my ($port, $sp) = $u =~ /^(.+?)(?::(\d+(?:\.\d+)?)\s*([MGT]?))?$/i ? ($1, defined $2 ? $2 * { '' => 1, M => 1, G => 1000, T => 1000000 }->{ uc($3 // '') } : undef) : ($u);
            push @up, [ $port, $sp ];
        }
        $s{uplinks} = \@up;
        $sw->[2] = \%s;
        splice @$sw, 3;
    }
    $c{mail}{format} = lc $c{mail}{format};
    die "[mail] format must be html or text\n" unless $c{mail}{format} =~ /^(html|text)$/;
    die "No [capsman], [msm], [cnpilot] or [switches] defined\n" unless @{ $c{capsman} } || @{ $c{switches} };
    return \%c;
}

# ==========================================================================
# State
# ==========================================================================
sub lock_state {
    my ($cfg) = @_;
    my $lf = "$cfg->{general}{state_file}.lock";
    open(my $lh, '>>', $lf) or die "Cannot open $lf: $!\n";
    flock($lh, LOCK_EX) or die "flock $lf: $!\n";
    return $lh;
}

sub load_state {
    my ($file) = @_;
    return {} unless -e $file;
    open(my $fh, '<:raw', $file) or die "Cannot read $file: $!\n";
    local $/;
    my $raw = <$fh>;
    close $fh;
    my $s = eval { JSON::PP->new->utf8->decode($raw) };
    if (!$s) { logmsg('warn', "State file $file is corrupted, starting over: $@"); return {} }
    return $s;
}

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

sub show_state {
    my ($cfg) = @_;
    my $lock  = lock_state($cfg);
    my $state = load_state($cfg->{general}{state_file});
    for my $name (sort keys %{ $state->{capsman} || {} }) {
        my $known = $state->{capsman}{$name}{caps} || {};
        my @all = map { { %{ $known->{$_} }, key => $_ } } keys %$known;
        my $miss = grep { $_->{missing_since} } @all;
        my $id = $state->{capsman}{$name}{identity};
        my ($dev) = grep { $_->{name} eq $name } @{ $cfg->{capsman} };
        print(($dev ? $dev->{label} : 'CAPsMAN') . " '$name'" . ($id ? " ($id)" : '') . ": " . (@all - $miss) . " active, $miss missing\n");
        printf "  %-26s %-15s %-17s %-8s %s\n", 'Identity', 'IP', 'Key (MAC)', 'Status', 'Last seen';
        for my $c (sort { lc($a->{identity} // '') cmp lc($b->{identity} // '') } @all) {
            printf "  %-26s %-15s %-17s %-8s %s\n", $c->{identity} || '-', $c->{ip} || '-',
                $c->{key}, ($c->{missing_since} ? 'MISSING' : 'OK'), fmt_time($c->{last_seen});
        }
        print "\n";
    }
    my $sw = $state->{switches} || {};
    if (%$sw) {
        print "Switches:\n";
        for my $h (sort keys %$sw) {
            printf "  %-15s %-34s %s\n", $h, $sw->{$h}{desc} // '',
                !$sw->{$h}{down_since} ? 'OK'
                : 'UNREACHABLE since ' . fmt_time($sw->{$h}{down_since})
                  . ($sw->{$h}{muted} ? ' (reminders stopped)' : '');
        }
    }
}

sub show_maint_tail {
    my ($cfg) = @_;
    my $now = time;
    my @m = grep { $_->{until} > $now } @{ maint_load($cfg)->{mutes} };
    return unless @m;
    print "\nMaintenance windows (no mails):\n";
    printf "  %-8s %-24s until %s%s\n", $_->{id}, $_->{target}, fmt_time($_->{until}), ($_->{from} > $now ? ' (from ' . fmt_time($_->{from}) . ')' : '') for @m;
}

sub forget_cap {
    my ($cfg, $what) = @_;
    my $lock  = lock_state($cfg);
    my $state = load_state($cfg->{general}{state_file});
    my $n = 0;
    for my $cs (values %{ $state->{capsman} || {} }) {
        for my $k (keys %{ $cs->{caps} }) {
            my $e = $cs->{caps}{$k};
            if (uc($k) eq uc($what) || lc($e->{identity} // '') eq lc($what) || ($e->{ip} // '') eq $what) {
                delete $cs->{caps}{$k};
                $n++;
            }
        }
    }
    save_state($cfg->{general}{state_file}, $state) if $n;
    print $n ? "Records removed: $n\n" : "Access point '$what' not found in state.\n";
}

sub reset_state {
    my ($cfg) = @_;
    my $lock = lock_state($cfg);
    my $f = $cfg->{general}{state_file};
    if (-e $f) { unlink $f or die "Cannot delete $f: $!\n" }
    print "State deleted; the next cycle records a new baseline.\n";
}

# ==========================================================================
# Helpers
# ==========================================================================
# ==========================================================================
# Dashboard data: event log and per-cycle history (JSON lines next to the state file)
# ==========================================================================
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;
}

# a faster JSON module when one is installed (libjson-xs-perl / libcpanel-json-xs-perl), else JSON::PP
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 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;
}

# sections of one cycle -> events (reminders are not events). $silent: sections that are not
# mailed (maintenance, flapping ended, ...) - recorded the same way, maint => 1 where muted
sub record_events {
    my ($g, $sections, $now, $silent) = @_;
    my @ev;
    my %kind = (missing => 'ap_missing', back => 'ap_back', new => 'ap_new', down => 'dev_down', up => 'dev_up', missing_ad => 'ap_missing', down_ad => 'dev_down',
                flap => 'ap_flap', dflap => 'dev_flap', flap_end => 'flap_end', dflap_end => 'flap_end', forgot => 'ap_forgotten',
                port => 'port_problem', portok => 'port_ok', reboot => 'dev_reboot', c_exp => 'cert_warn', c_ren => 'cert_renewed', d_low => 'disk_low', d_ok => 'disk_ok');
    my $dn = $g->{_depn} || {};                    # 13.6: how many are unreachable behind each device reported down
    my $dtext = sub { my ($n, $ip, $t) = @_; $ip //= ''; $ip =~ s/:\d+$//; my $c = $dn->{ ($n // '') . (length $ip && $ip ne ($n // '') ? " ($ip)" : '') } or return $t;
                      return join('; ', grep { defined && length } $t, "$c behind it unreachable") };
    for my $s (@$sections, @{ $silent || [] }) {
        my %base = (t => $now, ctl => $s->{name}, label => $s->{label}, heading => $s->{heading}, ($s->{maint} ? (maint => 1) : ()),
                    ($s->{behind} ? (behind => $s->{behind}) : ()));
        if    ($s->{type} eq 'cm_down') { push @ev, { %base, type => 'ctl_down', host => $s->{host}, text => $dtext->($s->{heading} // $s->{name}, $s->{host}, $s->{err}) } unless $s->{after_maint} }
        elsif ($s->{type} eq 'cm_up')   { push @ev, { %base, type => 'ctl_up',   host => $s->{host} } }
        elsif ($s->{type} eq 'caps' && $s->{first}) {
            push @ev, { %base, type => 'baseline', host => $s->{host}, count => $s->{cur} };
        } else {
            if ($s->{type} eq 'switches' && $s->{first}) {
                push @ev, { t => $now, type => 'baseline_dev', heading => $s->{heading}, count => $s->{count}, ok => $s->{ok} };
            }
            for my $gr (@{ $s->{groups} || [] }) {
                my $type = $kind{ $gr->{kind} } or next;
                for my $x (@{ $gr->{items} }) {
                    # 13.6: behind a device that is down - recorded, not pushed (behind), and not a maintenance
                    push @ev, { %base, type => $type, (($gr->{maint} || $x->{_maint}) && !$x->{behind} ? (maint => 1) : ()),
                                ($x->{behind} ? (behind => $x->{behind}) : ()),
                                name => $x->{identity} // $x->{desc} // $x->{name} // '', ip => $x->{ip} // $x->{host} // '',
                                mac => $x->{mac} // '', (defined $x->{text} ? (text => $x->{text}) : ()),
                                ($gr->{kind} =~ /^(missing|down)$/ && !$gr->{maint} && %$dn ? (text => $dtext->($x->{desc} // $x->{identity} // $x->{name}, $x->{host} // $x->{ip}, $x->{text})) : ()),
                                (defined $x->{flap_text} ? (text => $x->{flap_text}) : ()),
                                ($s->{type} eq 'certs' ? (heading => 'Certificates', target => $x->{target}) : ()),
                                ($s->{type} eq 'server' ? (heading => 'Server', target => $x->{target}) : ()) };
                    delete $ev[-1]{ctl} if $s->{type} ne 'caps';
                }
            }
        }
    }
    append_jsonl($g, 'events.jsonl', @ev);
}

sub record_history {
    my ($cfg, $state, $now) = @_;
    my %c;
    my ($up, $down) = (0, 0);
    for my $cm (@{ $cfg->{capsman} }) {
        my $cs = $state->{capsman}{ $cm->{name} } or next;
        my @all = values %{ $cs->{caps} || {} };
        my $miss = grep { $_->{missing_since} } @all;
        $c{ $cm->{name} } = [ @all - $miss, $miss, $cs->{down_since} ? 0 : 1 ];
    }
    for my $sw (@{ $cfg->{switches} }) {
        my $st = $state->{switches}{ $sw->[0] } or next;
        $st->{down_since} ? $down++ : $up++;
    }
    my $rec = { t => $now, c => \%c, s => [ $up, $down ] };
    append_jsonl($cfg->{general}, 'history.jsonl', $rec);
    central_queue($cfg, 'history', $rec);
    hist_maintain($cfg->{general}, 'history', $now);
    # switch statistics of this check (SNMP): kept like the Wi-Fi clients - every check, hourly, daily
    my %ds;
    for my $sw (@{ $cfg->{switches} }) {
        my $st = $state->{switches}{ $sw->[0] } or next;
        my $d = delete $st->{_ds} or next;
        $ds{ $sw->[0] } = $d;
    }
    if (%ds) {
        my $dr = { t => $now + 0, c => \%ds };
        append_jsonl($cfg->{general}, 'devstats.jsonl', $dr);
        central_queue($cfg, 'devstats', $dr);                  # mtmon-admin-center 6.0.0+
    }
    hist_maintain($cfg->{general}, 'devstats', $now);
}

# ==========================================================================
# [central]: after every check the status is sent (HTTPS POST, outgoing only) to an
# mtmon-admin-center. History and client records wait in central-queue.jsonl until the
# centre has confirmed them, so an outage of the centre leaves no gap in its charts.
# ==========================================================================
my $CENTRAL_FAILS = 0;

sub central_queue {
    my ($cfg, $kind, $rec) = @_;
    return unless $cfg->{central}{enabled} && $rec;
    append_jsonl($cfg->{general}, 'central-queue.jsonl', { k => $kind, r => $rec });
}

sub central_post {
    my ($cfg, $body, $gzip, $path) = @_;
    my $ce = $cfg->{central};
    (my $url = $ce->{url}) =~ s{/+$}{};
    my %ssl = length $ce->{fingerprint}
        ? (verify_SSL => 1, SSL_options => { SSL_fingerprint => $ce->{fingerprint} })   # self-signed centre: pinned
        : (verify_SSL => $ce->{tls_verify} ? 1 : 0);
    my $http = HTTP::Tiny->new(timeout => $ce->{timeout}, agent => "mtmon/$VERSION", %ssl);
    return $http->post($url . ($path // '/api/v1/ingest'), {
        headers => { 'Content-Type' => 'application/json', 'Authorization' => "Bearer $ce->{key}",
                     ($gzip ? ('Content-Encoding' => 'gzip') : ()) },
        content => $body,
    });
}

# Records go to the centre in parts of CENTRAL_PART, so a large backlog (the history sent on the
# first contact, or what was kept while the centre was unreachable) never makes one huge request.
use constant { CENTRAL_PART => 300, CENTRAL_PARTS_PER_RUN => 40, CENTRAL_QUEUE_MAX => 30000 };
my $CENTRAL_NOGZIP = 0;

sub central_state {
    my ($g) = @_;
    return eval { open(my $fh, '<:raw', data_file($g, 'central.json')) or die; local $/; JSON::PP->new->utf8->decode(<$fh>) } || {};
}
sub central_state_save {
    my ($g, $st) = @_;
    my ($fh, $tmp) = tempfile('.central-XXXXXX', DIR => dirname(data_file($g, 'central.json')));
    binmode $fh;
    print {$fh} JSON::PP->new->utf8->encode($st);
    close $fh;
    rename $tmp, data_file($g, 'central.json');
}
sub central_queue_save {
    my ($g, $recs) = @_;
    my $file = data_file($g, 'central-queue.jsonl');
    if (!@$recs) { unlink $file; return }
    my ($fh, $tmp) = tempfile('.central-q-XXXXXX', DIR => dirname($file));
    binmode $fh;
    my $j = JSON::PP->new->utf8->canonical;
    print {$fh} $j->encode($_), "\n" for @$recs;
    close $fh;
    chmod 0640, $tmp;
    rename $tmp, $file;
}

# one request: the status (always - the centre needs it), some records, and with the last part the
# Wi-Fi clients and the events
sub central_send {
    my ($cfg, $recs, $last, $since, $ack, $st) = @_;
    my $ce = $cfg->{central};
    my $g = $cfg->{general};
    my $status = web_status($cfg, undef);
    delete @$status{qw(auth user role refresh)};
    my %p = (v => 1, sent => time + 0, status => $status, records => [ map { { kind => $_->{k}, rec => $_->{r} } } @$recs ],
             ($ack && @$ack ? (ack => $ack) : ()));
    my $event_t;
    if ($last) {
        $p{clients} = web_clients($cfg, $ce->{send_client_details} ? undef : { role => 'summary' });
        my @events = read_jsonl(data_file($g, 'events.jsonl'), $since + 1);
        @events = @events[-1000 .. -1] if @events > 1000;
        $p{events} = \@events;
        $event_t = @events ? $events[-1]{t} : $since;
    }
    if ($AGENT) {
        # 13.9: the agent's mails (the centre sends them), its configuration state and, now and then, its state for a restart
        $p{agent} = agent_info();
        my @m = read_jsonl(data_file($g, 'central-mail.jsonl'));
        $p{mails} = [ @m[0 .. ($#m > 19 ? 19 : $#m)] ] if @m;
        $p{backup} = agent_backup() if $last && agent_backup_due($st || {});
    }
    my $json = JSON::PP->new->utf8->canonical->encode(\%p);
    my ($body, $gz) = ($json, 0);
    if (!$CENTRAL_NOGZIP && eval { require IO::Compress::Gzip; 1 }) {
        my $z;
        if (IO::Compress::Gzip::gzip(\$json => \$z)) { ($body, $gz) = ($z, 1) }
    }
    my $res = central_post($cfg, $body, $gz);
    # a centre older than 4.1 does not take compressed reports: send them uncompressed from now on
    if ($gz && $res->{status} == 400 && ($res->{content} // '') =~ /invalid JSON/) {
        $CENTRAL_NOGZIP = 1;
        logmsg('info', "Central $ce->{url}: the centre does not take compressed reports, sending them uncompressed");
        $res = central_post($cfg, $json, 0);
        $body = $json;
    }
    my $ok = $res->{success} && (eval { JSON::PP->new->utf8->decode($res->{content})->{ok} } // 0);
    return ($ok, $res, length $body, length $json, $event_t, scalar @{ $p{events} || [] }, ($p{backup} ? 1 : 0));
}

sub central_push {
    my ($cfg, $verbose) = @_;
    my $g = $cfg->{general};
    my $st = central_state($g);
    my @queue = map { $_->{r} && $_->{k} ? $_ : () } read_jsonl(data_file($g, 'central-queue.jsonl'));
    if (!$st->{sent} && !$st->{backfill}) {
        # first contact with the centre: the whole local history goes to it after this report
        # (13.13: every level - checks, hours, days - and the events, central_resend_run), so its
        # charts do not start empty. A centre older than 7.21.0 gets the checks of history_days
        # through the queue instead (central_backfill_queue).
        $st->{backfill} = 1;
        $st->{event_t} //= time - ($g->{_history_days} || 30) * 86400;
        $st->{resend} = { auto => 1, t => time + 0 } unless $AGENT;
        central_state_save($g, $st);
        if ($AGENT) { @queue = central_backfill_queue($cfg, \@queue) }
        else { logmsg('info', 'Central: first contact - the local history goes to the centre after this report') }
    }
    if (!$st->{backfill_ap}) {
        # 11.2.1: the clients per access point recorded before they were sent to the centre
        # (11.2.0 kept them only locally) go once too; the centre skips what it already has
        my %q = map { ($_->{k} eq 'clientsap' ? ($_->{r}{t} => 1) : ()) } @queue;
        my @ap = grep { !$q{ $_->{t} } } read_jsonl(data_file($g, 'clientsap.jsonl'), time - ($g->{_history_days} || 30) * 86400);
        if (@ap) {
            @queue = sort { ($a->{r}{t} // 0) <=> ($b->{r}{t} // 0) } @queue, map { { k => 'clientsap', r => $_ } } @ap;
            central_queue_save($g, \@queue);
        }
        $st->{backfill_ap} = 1;
        central_state_save($g, $st);
    }
    if (@queue > CENTRAL_QUEUE_MAX) {
        logmsg('warn', "Central: " . (@queue - CENTRAL_QUEUE_MAX) . " oldest kept record(s) dropped (more than " . CENTRAL_QUEUE_MAX . ")");
        @queue = @queue[-CENTRAL_QUEUE_MAX .. -1];
    }
    my $since = $st->{event_t} // time - 3600;
    my ($parts, $sent, $bytes, $raw, $nev, $t0) = (0, 0, 0, 0, 0, time);
    while (1) {
        my @part = splice(@queue, 0, CENTRAL_PART);
        my $last = !@queue || $parts + 1 >= CENTRAL_PARTS_PER_RUN;
        my @ack = @{ $st->{cmd_ack} || [] };
        my ($ok, $res, $len, $jlen, $event_t, $ne, $bk) = central_send($cfg, \@part, $last, $since, \@ack, $st);
        if (!$ok) {
            my $why = $res->{status} == 599 ? ($res->{content} =~ s/\s+$//r) : "HTTP $res->{status} $res->{reason}"
                    . ($res->{status} == 401 ? ' (key rejected - check [central] key and the site on the centre)' : '')
                    . (($res->{content} // '') =~ /"error"\s*:\s*"([^"]+)"/ ? ": $1" : '');
            $why =~ s/\n.*//s;
            $CENTRAL_FAILS++;
            my $left = @part + @queue;
            logmsg($CENTRAL_FAILS == 1 || $verbose ? 'warn' : 'debug',
                   "Central $cfg->{central}{url}: sending failed ($why)" . ($sent ? ", $sent record(s) sent before" : '')
                   . ($left ? ", $left record(s) kept for later" : '') . sprintf(' [request %.0f kB]', $len / 1024));
            central_queue_save($g, [ @part, @queue ]) if $sent;
            return 0;
        }
        $parts++; $sent += @part; $bytes += $len; $raw += $jlen;
        central_queue_save($g, \@queue);                     # confirmed: these are at the centre now
        if (@ack) { my %a = map { $_ => 1 } @ack; $st->{cmd_ack} = [ grep { !$a{$_} } @{ $st->{cmd_ack} || [] } ]; central_state_save($g, $st) }
        central_commands($cfg, $st, $res);
        agent_answer($cfg, $st, $res, $bk) if $AGENT;
        if ($last) {
            $nev = $ne;
            $st->{event_t} = $event_t + 0;
            $st->{sent} = time + 0;
            delete $st->{backfill} unless @queue;
            central_state_save($g, $st);
            last;
        }
        logmsg('info', "Central: sent part $parts, " . scalar(@queue) . " record(s) still to send") if $verbose;
    }
    logmsg('info', "Central $cfg->{central}{url}: reachable again, sent $sent queued record(s)") if $CENTRAL_FAILS;
    logmsg('info', "Central: $sent record(s) still to send, next part at the next check") if @queue;
    logmsg($verbose ? 'info' : 'debug', sprintf("Central: sent %d record(s), %d event(s) in %d request(s), %.0f kB (%.0f kB uncompressed) in %d s",
                                                $sent, $nev, $parts, $bytes / 1024, $raw / 1024, time - $t0));
    $CENTRAL_FAILS = 0;
    return 1;
}

# the checks of the last history_days into the queue (the first contact with a centre older than 7.21.0)
sub central_backfill_queue {
    my ($cfg, $queue) = @_;
    my $g = $cfg->{general};
    my $from = time - ($g->{_history_days} || 30) * 86400;
    my @q = ((map { { k => 'history', r => $_ } } read_jsonl(data_file($g, 'history.jsonl'), $from)),
             (map { { k => 'clients', r => $_ } } read_jsonl(data_file($g, 'clients.jsonl'), $from)),
             (map { { k => 'clientsap', r => $_ } } read_jsonl(data_file($g, 'clientsap.jsonl'), $from)),
             (map { { k => 'devstats', r => $_ } } read_jsonl(data_file($g, 'devstats.jsonl'), $from)));
    my $n = @q;
    @q = sort { ($a->{r}{t} // 0) <=> ($b->{r}{t} // 0) } @{ $queue || [] }, @q;
    central_queue_save($g, \@q);
    logmsg('info', "Central: $n history record(s) of the last " . ($g->{_history_days} || 30) . " days to send");
    return @q;
}

# ==========================================================================
# 13.13: the whole local history to the centre - every level: each check (history_days), per hour
# (history_hourly_days), per day (all of it), for the devices, the Wi-Fi clients (per SSID and per
# access point) and the switch statistics, and all events. By itself on the first contact with a
# centre, and with mtmon --central-resend (a new centre, a centre that lost its data).
# POST /api/v1/history (centre 7.21.0+): one file in parts of about 1.5 MB; the centre gathers the
# parts and merges them with what it has (it keeps its records; the hours and days of the mtmon
# replace its own, which may cover only a part of them; an event is kept once).
# ==========================================================================
use constant { RESEND_PART_BYTES => 1_500_000 };
sub resend_files { return ((map { ("$_-1d.jsonl", "$_-1h.jsonl", "$_.jsonl") } qw(history clients clientsap devstats)), 'events.jsonl') }

# $job: { todo => [files left], line => next line of the first one, parts, sent, t } - kept in
# central.json between runs. $budget: seconds for this run (0: all of it).
# -> 1 done, -1 more next time, 0 failed, -2 the centre does not take it (older than 7.21.0)
sub central_resend {
    my ($cfg, $job, $budget, $verbose) = @_;
    my $g = $cfg->{general};
    my $t0 = time;
    my $cv = central_state($g)->{center_version};            # said by the centre in its answer to each report
    return -2 if $cv && vcmp_ver($cv, '7.21.0') < 0;
    $job->{todo} //= [ grep { -s data_file($g, $_) } resend_files() ];
    $job->{t} //= time + 0;
    while (@{ $job->{todo} }) {
        my $f = $job->{todo}[0];
        my @lines = read_lines(data_file($g, $f));
        my $i = $job->{line} // 0;
        $i = 0 if $i > @lines;                                # the file was trimmed meanwhile: again from its start
        my $start = $i == 0 ? 1 : 0;
        while (1) {
            my ($bytes, @part) = (0);
            while ($i < @lines && $bytes < RESEND_PART_BYTES) {
                my $l = $lines[$i++];
                $l =~ s/\s+$//;
                next unless length $l;
                push @part, decode('UTF-8', $l);
                $bytes += length $l;
            }
            my $end = $i >= @lines ? 1 : 0;
            my $json = JSON::PP->new->utf8->canonical->encode({ v => 1, file => $f, start => ($start ? JSON::PP::true : JSON::PP::false),
                                                          end => ($end ? JSON::PP::true : JSON::PP::false), lines => \@part });
            my ($body, $gz) = ($json, 0);
            if (eval { require IO::Compress::Gzip; 1 }) { my $z; ($body, $gz) = ($z, 1) if IO::Compress::Gzip::gzip(\$json => \$z) }
            my $res = central_post($cfg, $body, $gz, '/api/v1/history');
            return -2 if $res->{status} == 404 || $res->{status} == 405;
            my $ok = $res->{success} && (eval { JSON::PP->new->utf8->decode($res->{content})->{ok} } // 0);
            if (!$ok) {
                my $why = $res->{status} == 599 ? ($res->{content} =~ s/\s+$//r) : "HTTP $res->{status} $res->{reason}"
                        . (($res->{content} // '') =~ /"error"\s*:\s*"([^"]+)"/ ? ": $1" : '');
                $why =~ s/\n.*//s;
                logmsg($verbose || !$job->{fails} ? 'warn' : 'debug', "Central: sending the history ($f) failed: $why");
                $job->{fails}++;
                return 0;
            }
            $start = 0;
            $job->{line} = $i;
            $job->{parts}++;
            $job->{sent} += @part;
            delete $job->{fails};
            printf "  %-22s %7d of %d record(s)\n", $f, $i, scalar @lines if $verbose && ($end || $verbose > 1);
            last if $end;
            return -1 if $budget && time - $t0 >= $budget;
        }
        shift @{ $job->{todo} };
        $job->{line} = 0;
        return -1 if $budget && @{ $job->{todo} } && time - $t0 >= $budget;
    }
    return 1;
}

# after each report of the daemon: a resend that waits (first contact) goes on, at most 60 s a time
sub central_resend_run {
    my ($cfg) = @_;
    my $g = $cfg->{general};
    my $job = central_state($g)->{resend} or return;
    my $r = central_resend($cfg, $job, 60, 0);
    my $st = central_state($g);
    if ($r == 1) {
        delete $st->{resend};
        logmsg('info', sprintf('Central: the local history is at the centre (%d record(s) in %d request(s), %d s)', $job->{sent} // 0, $job->{parts} // 0, time - $job->{t}));
    } elsif ($r == -2) {
        delete $st->{resend};
        logmsg('info', "Central: the centre is older than 7.21.0 - it gets only the checks of the last " . ($g->{_history_days} || 30) . " days");
        central_backfill_queue($cfg, [ map { $_->{r} && $_->{k} ? $_ : () } read_jsonl(data_file($g, 'central-queue.jsonl')) ]) if $job->{auto};
    } else {
        $st->{resend} = $job;
        logmsg('debug', "Central: history to the centre: $job->{sent} record(s) sent, " . scalar(@{ $job->{todo} || [] }) . " file(s) left") if $r == -1;
    }
    central_state_save($g, $st);
}

# mtmon --central-resend
sub central_resend_cli {
    my ($cfg) = @_;
    die "[central] is not enabled in the configuration\n" unless $cfg->{central}{enabled};
    my $g = $cfg->{general};
    my @f = grep { -s data_file($g, $_) } resend_files();
    my ($n, $b) = (0, 0);
    for (@f) { $n += scalar(my @l = read_lines(data_file($g, $_))); $b += -s data_file($g, $_) }
    printf "Sending the whole local history to %s: %d file(s), %d record(s), %s\n", $cfg->{central}{url}, scalar @f, $n, fmt_bytes($b);
    print "  checks of the last " . ($g->{_history_days} || 30) . " days, hours of the last " . ($g->{_history_hourly_days} || 400) . " days, all days, all events\n";
    my $job = { todo => \@f };
    my $t0 = time;
    my $r = central_resend($cfg, $job, 0, 1);
    if ($r == 1) {
        printf "Done: %d record(s) in %d request(s), %d s. The centre merged them with what it had.\n", $job->{sent} // 0, $job->{parts} // 0, time - $t0;
        return 0;
    }
    print "The centre does not take it: it needs mtmon-admin-center 7.21.0 or newer.\n" if $r == -2;
    print "FAILED - see the message above. Run it again: it starts over and the centre keeps each record once.\n" if $r == 0;
    return 2;
}

# commands from the centre in its answer (maintenance windows set there): applied once each,
# confirmed with the next report
sub central_commands {
    my ($cfg, $st, $res) = @_;
    my $ans = eval { JSON::PP->new->utf8->decode($res->{content} // '') } or return;
    $st->{center_version} = $ans->{version} if defined $ans->{version} && $ans->{version} =~ /^[\d.]{1,20}$/;
    $st->{center_mtmon} = $ans->{mtmon_current} if defined $ans->{mtmon_current} && $ans->{mtmon_current} =~ /^[\d.]{1,20}$/;
    my @cmd = grep { ref $_ eq 'HASH' && ($_->{id} // '') =~ /^[\w-]{4,64}$/ } @{ ref $ans->{commands} eq 'ARRAY' ? $ans->{commands} : [] } or return;
    my %done = map { $_ => 1 } @{ $st->{cmd_done} || [] };
    for my $c (@cmd) {
        if (!$done{ $c->{id} }) {
            my $by = substr($c->{by} // 'centre', 0, 80) . ' (centre)';
            if (($c->{op} // '') eq 'mute' && defined $c->{target} && length $c->{target} <= 200 && ($c->{until} // 0) =~ /^\d+$/ && $c->{until} > time) {
                maint_add($cfg, id => ($c->{mid} // $c->{id}), target => $c->{target}, from => (($c->{from} // 0) =~ /^\d+$/ ? $c->{from} : time),
                          until => $c->{until}, reason => substr($c->{reason} // '', 0, 200), by => $by);
            } elsif (($c->{op} // '') eq 'unmute' && defined $c->{mid}) {
                maint_end($cfg, $c->{mid}, $by);
            } else {
                logmsg('warn', "Central: unknown or invalid command $c->{id} ignored");
            }
            push @{ $st->{cmd_done} }, $c->{id};
        }
        push @{ $st->{cmd_ack} }, $c->{id} unless grep { $_ eq $c->{id} } @{ $st->{cmd_ack} || [] };
    }
    splice @{ $st->{cmd_done} }, 0, @{ $st->{cmd_done} } - 200 if @{ $st->{cmd_done} || [] } > 200;
    central_state_save($cfg->{general}, $st);
}

# ==========================================================================
# 13.9: agent - mtmon without a disk (a MikroTik container on a RAM disk)
#   mtmon --agent: the connection to the centre from the environment (MTMON_CENTRAL, MTMON_KEY,
#   MTMON_FINGERPRINT), the configuration from the centre (the site's agent.conf there), the data in
#   MTMON_DATA (/tmp/mtmon). The mails go to the centre, which sends them; what must survive a
#   restart (state, maintenance, topology, inventory) is kept by the centre too and comes back from
#   there when the agent starts with an empty RAM disk.
# ==========================================================================
# (a sub, not a variable: the main program runs before a file-level assignment down here would)
sub agent_backup_files { qw(state.json maintenance.json inventory.json topology.json certificates.json ap-ports.json central.json known_hosts report.json) }

sub agent_env {
    my %e = (url => $ENV{MTMON_CENTRAL} // '', key => $ENV{MTMON_KEY} // '', fingerprint => $ENV{MTMON_FINGERPRINT} // '',
             tls_verify => $ENV{MTMON_TLS_VERIFY} // 'yes', timeout => $ENV{MTMON_TIMEOUT} // 20);
    die "mtmon --agent: MTMON_CENTRAL is not set (the address of the centre, e.g. https://centre.example.com/)\n" unless length $e{url};
    die "mtmon --agent: MTMON_CENTRAL must start with https:// (or http:// for tests)\n" unless $e{url} =~ m{^https?://[^/\s]+}i;
    die "mtmon --agent: MTMON_KEY is not set (mtmon-admin-center --add-site NAME --agent prints it)\n" unless $e{key} =~ /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{20,}$/;
    die "mtmon --agent: MTMON_FINGERPRINT must look like sha256\$hex\n" if length $e{fingerprint} && $e{fingerprint} !~ /^sha256\$[0-9a-f]{64}$/i;
    $e{fingerprint} =~ s/^sha256\$(.*)$/sha256\$\L$1/i;
    return %e;
}

sub agent_http {
    my ($method, $path, $body) = @_;
    my %e = %AGENT_ENV;
    (my $url = $e{url}) =~ s{/+$}{};
    my %ssl = length $e{fingerprint} ? (verify_SSL => 1, SSL_options => { SSL_fingerprint => $e{fingerprint} })
            : (verify_SSL => ($e{tls_verify} =~ /^(0|no|ne|false|off)$/i ? 0 : 1));
    my $http = HTTP::Tiny->new(timeout => $e{timeout}, agent => "mtmon/$VERSION (agent)", %ssl);
    return $http->request($method, "$url$path", { headers => { Authorization => "Bearer $e{key}", ($body ? ('Content-Type' => 'application/json') : ()) },
                                                  ($body ? (content => $body) : ()) });
}

# the configuration as the agent runs it: the text from the centre, with the data folder and the
# connection to the centre of this container (whatever the text says about them)
sub agent_conf_text {
    my ($text) = @_;
    # line for line (an error names the same line as in agent.conf); what the agent sets itself is
    # commented out and comes at the end
    my (@out, $sec);
    for my $l (split /\n/, $text, -1) {
        if ($l =~ /^\s*\[\s*(.+?)\s*\]\s*$/) { $sec = lc $1; push @out, $sec eq 'central' ? "# $l   (set by the container)" : $l; next }
        if (defined $sec && ($sec eq 'central' || ($sec eq 'general' && $l =~ /^\s*state_file\s*=/i)) && $l =~ /\S/ && $l !~ /^\s*[#;]/) { push @out, "# $l   (set by the container)"; next }
        push @out, $l;
    }
    my %e = %AGENT_ENV;
    push @out, '', '[general]', "state_file = $AGENT/state.json", '[central]', 'enabled = yes', "url = $e{url}", "key = $e{key}", (length $e{fingerprint} ? "fingerprint = $e{fingerprint}" : ()),
               "tls_verify = $e{tls_verify}", "timeout = $e{timeout}";
    return join("\n", @out) . "\n";
}

sub agent_write {
    my ($name, $bytes) = @_;
    my ($fh, $tmp) = tempfile(".agent-XXXXXX", DIR => $AGENT);
    binmode $fh;
    print {$fh} $bytes;
    close $fh or die "Writing $AGENT/$name failed: $!\n";
    chmod 0600, $tmp;
    rename $tmp, "$AGENT/$name" or die "Cannot write $AGENT/$name: $!\n";
}

# fetch the configuration from the centre; returns 1 when it is new, 0 when unchanged, undef (and the reason) on an error
sub agent_fetch_config {
    my $res = agent_http('GET', '/api/v1/agent/config');
    if (!$res->{success}) {
        my $why = $res->{status} == 599 ? ($res->{content} // '') =~ s/\s+$//r : "HTTP $res->{status}"
                . ($res->{status} == 401 ? ' (key rejected - check MTMON_KEY and the site on the centre)' : '')
                . ($res->{status} == 404 ? ' (no agent configuration for this site on the centre: mtmon-admin-center --agent-config SITE)' : '');
        return (undef, $why =~ s/\n.*//sr);
    }
    my $a = eval { JSON::PP->new->utf8->decode($res->{content}) };
    return (undef, 'the centre did not answer with a configuration') unless ref $a eq 'HASH' && defined $a->{config};
    my $text = agent_conf_text($a->{config});
    my $old = agent_read('mtmon.conf') // '';
    my $new = encode('UTF-8', $text);
    my $md5 = $a->{md5} // md5_hex($new);
    if ($old eq $new) { agent_write('config.md5', "$md5\n"); unlink "$AGENT/config-error", "$AGENT/config-bad.md5"; return (0) }
    agent_write('mtmon.conf.new', $new);
    agent_write('config.new.md5', "$md5\n");                              # becomes config.md5 when it is taken
    return (1);
}
sub agent_read { my $fh; open($fh, '<:raw', "$AGENT/$_[0]") or return undef; local $/; my $b = <$fh>; close $fh; return $b }
sub agent_config_md5 { my $m = agent_read($_[0] // 'config.md5') // ''; chomp $m; return $m }
# the new configuration passed the check: it runs now / it did not: the previous one stays
sub agent_config_taken { rename "$AGENT/mtmon.conf.new", "$AGENT/mtmon.conf"; rename "$AGENT/config.new.md5", "$AGENT/config.md5"; unlink "$AGENT/config-error", "$AGENT/config-bad.md5" }
sub agent_config_bad {
    my ($e) = @_;
    my $err = $e =~ s/\s+$//r =~ s{\Q$AGENT\E/mtmon\.conf\.new}{agent.conf}gr;
    unlink "$AGENT/mtmon.conf.new";
    rename "$AGENT/config.new.md5", "$AGENT/config-bad.md5";
    agent_write('config-error', encode('UTF-8', $err));
    return $err;
}

# start: data folder, what the centre kept of this site (when the folder is empty), the configuration
sub agent_bootstrap {
    $AGENT = $ENV{MTMON_DATA} || '/tmp/mtmon';
    %AGENT_ENV = agent_env();
    $AGENT =~ s{/+$}{};
    -d $AGENT or mkdir($AGENT, 0700) or die "Cannot create $AGENT: $!\n";
    logmsg('info', "Agent: data in $AGENT, centre $AGENT_ENV{url}");
    if (!-e "$AGENT/state.json") {
        my $res = agent_http('GET', '/api/v1/agent/backup');
        my $b = $res->{success} ? eval { JSON::PP->new->utf8->decode($res->{content}) } : undef;
        if (ref $b eq 'HASH' && ref $b->{files} eq 'HASH') {
            my $n = 0;
            for my $f (grep { my $x = $_; grep { $_ eq $x } agent_backup_files() } keys %{ $b->{files} }) { agent_write($f, encode('UTF-8', $b->{files}{$f})); $n++ }
            logmsg('info', "Agent: $n file(s) of the state taken back from the centre (kept " . fmt_time($b->{t}) . ")");
        } elsif ($res->{status} == 404) { logmsg('info', 'Agent: first start - the centre has no saved state of this site yet') }
        else { logmsg('warn', "Agent: the saved state could not be read from the centre (HTTP $res->{status}) - starting without it") }
    }
    my $wait = 30;
    while (1) {
        my ($new, $why) = agent_fetch_config();
        if (defined $new) {
            if (-e "$AGENT/mtmon.conf.new") {
                my $ok = eval { local $AGENT = $AGENT; load_config("$AGENT/mtmon.conf.new"); 1 };
                if ($ok) { agent_config_taken(); logmsg('info', 'Agent: configuration from the centre (md5 ' . agent_config_md5() . ')') }
                else {
                    my $err = agent_config_bad($@);
                    if (!-e "$AGENT/mtmon.conf") {
                        # nothing to run yet: the centre is told (its page shows the error) and the agent waits for a correction
                        logmsg('error', "Agent: the configuration from the centre is not valid: $err - waiting for a correction");
                        agent_tell_error($err);
                        sleep 60;
                        next;
                    }
                    logmsg('error', "Agent: the new configuration from the centre is not valid, keeping the previous one: $err");
                }
            }
            last;
        }
        if (-e "$AGENT/mtmon.conf") { logmsg('warn', "Agent: configuration not read from the centre ($why) - using the previous one"); last }
        logmsg('warn', "Agent: waiting for the configuration from the centre ($why), again in $wait s");
        sleep $wait;
        $wait = $wait < 300 ? $wait * 2 : 300;
    }
    return "$AGENT/mtmon.conf";
}

# no valid configuration yet: a minimal report, so the centre's page shows the agent and its error
sub agent_tell_error {
    my ($err) = @_;
    my $body = JSON::PP->new->utf8->canonical->encode({ v => 1, sent => time + 0,
        status => { location => (split /\./, $AGENT_ENV{key})[0], version => $VERSION, interval => 300, host => hostname(), controllers => [], devices => { items => [] } },
        agent => { version => $VERSION, config_md5 => '', config_error => $err, data => $AGENT, started => $^T + 0 } });
    my $res = agent_http('POST', '/api/v1/ingest', $body);
    logmsg('warn', "Agent: the error could not be reported to the centre (HTTP $res->{status})") unless $res->{success};
}

# a new configuration on the centre (its md5 came in the answer to a report): fetch, check, reload
sub agent_config_changed {
    my ($cfg, $md5) = @_;
    # the faulty change was taken back on the centre: the error is gone
    unlink "$AGENT/config-error", "$AGENT/config-bad.md5" if $AGENT && defined $md5 && $md5 eq agent_config_md5() && -e "$AGENT/config-error";
    return unless $AGENT && defined $md5 && $md5 =~ /^[0-9a-f]{32}$/ && $md5 ne agent_config_md5() && $md5 ne agent_config_md5('config-bad.md5');
    my ($new, $why) = agent_fetch_config();
    if (!defined $new) { logmsg('warn', "Agent: the new configuration could not be read from the centre: $why"); return }
    return unless -e "$AGENT/mtmon.conf.new";
    if (eval { load_config("$AGENT/mtmon.conf.new"); 1 }) {
        agent_config_taken();
        logmsg('info', 'Agent: new configuration from the centre - reloading');
        $reload = 1;
    } else {
        my $err = agent_config_bad($@);
        logmsg('error', "Agent: the new configuration from the centre is not valid, keeping the previous one: $err");
    }
}

# what the agent tells the centre with each report
sub agent_info {
    my $err = agent_read('config-error');
    $err = decode('UTF-8', $err) if defined $err;
    my $md5 = agent_config_md5();
    # the agent's last applied configuration: the md5 of the centre's text it runs (the error is about a newer one)
    return { version => $VERSION, config_md5 => $md5, (defined $err ? (config_error => $err, config_bad => agent_config_md5('config-bad.md5')) : ()), data => $AGENT,
             started => $^T + 0 };
}

# the files the centre keeps for a restart: every 15 minutes, and after a report with changes
sub agent_backup_due {
    my ($st) = @_;
    return 1 if -e "$AGENT/backup-now";
    return time - ($st->{backup_t} // 0) >= 900;
}
sub agent_backup {
    my %f;
    for my $n (agent_backup_files()) {
        open(my $fh, '<:raw', "$AGENT/$n") or next;
        local $/;
        my $b = <$fh>;
        next if length($b) > 4_000_000;
        $f{$n} = decode('UTF-8', $b, Encode::FB_DEFAULT);
    }
    return { t => time + 0, files => \%f };
}

# mails: to the centre, which sends them (the agent has no mail server of its own)
sub agent_mail {
    my ($cfg, $subject, $body, $html) = @_;
    my $m = $cfg->{mail};
    my $id = md5_hex(time . $$ . rand() . $subject);
    append_jsonl($cfg->{general}, 'central-mail.jsonl', { id => $id, t => time + 0, subject => $subject, prefix => $m->{subject_prefix}, to => $m->{to} // '',
                                                         text => $body, (defined $html ? (html => $html) : ()) });
    my $now = data_file($cfg->{general}, 'central-now');
    my $fh;
    open($fh, '>', $now) and close $fh;                                      # the daemon sends it within a second
    open($fh, '>', "$AGENT/backup-now") and close $fh;                      # and the state that goes with it
    logmsg('debug', "Agent: mail '$subject' handed to the centre");
    return 1;
}

# the centre's answer to an agent: which mails it took, whether it kept the state, the md5 of the configuration
sub agent_answer {
    my ($cfg, $st, $res, $bk) = @_;
    my $a = eval { JSON::PP->new->utf8->decode($res->{content} // '') } or return;
    my $g = $cfg->{general};
    if (ref $a->{mails_ok} eq 'ARRAY' && @{ $a->{mails_ok} }) {
        my %ok = map { $_ => 1 } grep { defined && !ref } @{ $a->{mails_ok} };
        my $f = data_file($g, 'central-mail.jsonl');
        my @left = grep { !$ok{ $_->{id} // '' } } read_jsonl($f);
        if (@left) {
            my ($fh, $tmp) = tempfile('.central-m-XXXXXX', DIR => dirname($f));
            binmode $fh;
            print {$fh} JSON::PP->new->utf8->canonical->encode($_), "\n" for @left;
            close $fh;
            rename $tmp, $f;
        } else { unlink $f }
        logmsg('info', 'Agent: ' . scalar(keys %ok) . ' mail(s) sent by the centre');
    }
    if (ref $a->{mails_failed} eq 'HASH') {
        logmsg('warn', "Agent: the centre could not send mail '$_': $a->{mails_failed}{$_} - again with the next report") for sort keys %{ $a->{mails_failed} };
    }
    if ($bk && $a->{backup_ok}) { $st->{backup_t} = time + 0; unlink "$AGENT/backup-now"; central_state_save($g, $st) }
    agent_config_changed($cfg, $a->{agent_config_md5}) if defined $a->{agent_config_md5};
}

# --test-central: send now and say what happened
sub test_central {
    my ($cfg) = @_;
    die "[central] is not enabled in the configuration\n" unless $cfg->{central}{enabled};
    print "Sending to $cfg->{central}{url} ...\n";
    my $ok = central_push($cfg, 1);
    print $ok ? "OK - the centre accepted the status.\n" : "FAILED - see the message above.\n";
    if ($ok) {
        my $st = central_state($cfg->{general});
        my $cv = $st->{center_version};
        print "Centre: mtmon-admin-center " . ($cv // 'older than 6.0.0 (it does not say its version)') . "\n";
        for my $f (@CENTER_FEATURES) {
            print "  not on this centre: $f->[1] (needs $f->[0])\n" if !$cv ? vcmp_ver($f->[0], '6.0.0') >= 0 : vcmp_ver($cv, $f->[0]) < 0;
        }
        print "  the centre is built with mtmon $st->{center_mtmon} - this is $VERSION, update it\n"
            if $st->{center_mtmon} && vcmp_ver($st->{center_mtmon}, $VERSION) > 0;
    }
    return $ok ? 0 : 2;
}

# ==========================================================================
# Long-term history for the dashboard charts, in three steps (like RRD/MRTG):
#   <kind>.jsonl      every check (5 min)      kept history_days (30)
#   <kind>-1h.jsonl   per hour: average + peak  kept history_hourly_days (400)
#   <kind>-1d.jsonl   per day:  average + peak  kept forever
# kind = history (access points / devices), clients (Wi-Fi clients per SSID) or
# clientsap (Wi-Fi clients per access point, same form as clients, since 11.2.0).
# Hours and days are local time. Missing steps are filled from the finer file,
# so existing data is rolled up automatically after an upgrade.
# ==========================================================================
my %TRIMMED;   # file -> last trim time

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);
}

# t of the last record in a jsonl file (reads only the end of the file)
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;
}

# a record of any step -> the common aggregated form (n = number of checks behind it)
#   clients: { t, n => {ctl => n}, c => {ctl => {ssid => [avg, peak]}} }
#   history: { t, n => {ctl => n, _s => n}, c => {ctl => [up, missing, reachable]},
#              cm => {ctl => [lowest up, highest missing]}, s => [up, down], sm => [lowest up, highest down] }
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) : ()) };
}

# hourly / daily client files from before 8.1.0 have no totals (peak of all clients): rebuild them
# from the 5-minute data when that still covers them, otherwise keep them (no totals for that time)
my $CLIENTS_CHECKED;
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");
    }
}

# writes the completed hours / days that are not in the -1h / -1d file yet
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);
    }
}

# drop old records: raw after history_days, hourly after history_hourly_days (once a day per file)
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);
}

# chart data for a time range: the finest step that still has data for 'from' and is not
# finer than needed, completed with the newer finer records, merged to at most $max points
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 };
}

# peak number of clients (all SSIDs) per controller and for all of them, for calendar periods
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 };
}

# ==========================================================================
# Wi-Fi client report (11.3.0): everything a monthly / yearly / custom report shows,
# from the hourly history (daily for times older than history_hourly_days).
#   scope: '' = all controllers, or one controller name
# Shared with mtmon-admin-center (site pages and all sites together).
# ==========================================================================
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;
}

# the same, kept on disk for periods that are over (a month or a year does not change any more);
# at most 300 files, the oldest go first
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;
}

# reports of following periods (months of a year) of the same place as one report
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),
    };
}

# previous calendar month / year when the period is one, otherwise the same length just before
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);
}

# several reports (sites of the centre) as one: series added up per step, SSIDs merged by name,
# controllers = the sites, access points with the site in front
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 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;
}

# ==========================================================================
# Web dashboard: a small read-only HTTP server, run by the daemon as a child
# process ([web] enabled = yes) - if it fails, monitoring is not affected.
# ==========================================================================
my ($WEB_PID, $WEB_NEXT, $WEB_STARTED, $WEB_RUNS);
my $WEB_RESULT; # sign-in result of one connection: 'ok' / 'fail' (reported to the web server by exit code)
BEGIN { ($WEB_PID, $WEB_NEXT, $WEB_STARTED, $WEB_RUNS) = (0, 0, 0, 0) }

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_stop {
    return unless $WEB_PID;
    kill 'TERM', $WEB_PID;
    for (1 .. 50) { last if waitpid($WEB_PID, WNOHANG) != 0; select(undef, undef, undef, 0.1) }
    kill 'KILL', $WEB_PID if kill 0, $WEB_PID;
    waitpid($WEB_PID, 0) if kill 0, $WEB_PID;
    $WEB_PID = 0;
}

# called every second from the daemon loop: restart the dashboard if it stopped
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 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 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 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;
    }
}

# one connection: TLS (or the redirect of plain http), then the request -> exit code 0 / 10 / 11
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;
}

# one line of an HTTP request. Over TLS a read can come back empty although the connection is open
# (right after the handshake the request may still be on its way, or a TLS record without data was
# read): wait for more and try again instead of taking it as the end (alarm() limits the time)
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;
}

# http://host:port/path on the TLS port -> 301 to https://host:port/path
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");
}

# certificate for tls = yes: the configured files, or for the default files that are missing
# a self-signed one created next to the state file (the service cannot write /etc/mtmon)
# process name of the web server (mtmon-admin-center uses its own, see there)
sub web_procname { 'mtmon-web' }

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;
    if ($crt ne '/etc/mtmon/web.crt' || $key ne '/etc/mtmon/web.key') {
        logmsg('error', "Web dashboard: cannot read " . (-r $crt ? $key : $crt) . " ([web] cert_file / key_file)");
        return;
    }
    my $dir = dirname($cfg->{general}{state_file});
    ($crt, $key) = ("$dir/web.crt", "$dir/web.key");
    return ($crt, $key) if -r $crt && -r $key;
    my $mk = '/usr/lib/mtmon/mkcert';
    if (-x $mk && system($mk, $crt, $key) == 0 && -r $crt && -r $key) {
        logmsg('info', "Web dashboard: created a self-signed certificate $crt (valid 30 years)");
        return ($crt, $key);
    }
    logmsg('error', "Web dashboard: no certificate - /etc/mtmon/web.crt is missing and $mk could not create $crt");
    return;
}

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 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" }     # e.g. a browser's unused pre-connection
    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 // '';
    return web_reply($c, 403, 'text/plain', "Access from $peer is not allowed.\n") unless ip_allowed($w, $peer);
    my ($route, $query) = split /\?/, $path // '/', 2;

    # ---- login (only when dashboard users are configured) -------------------
    my $auth_on = (%{ $w->{_users} } || %{ $cfg->{_api_keys} || {} }) ? 1 : 0;
    my $who = $auth_on ? undef : { name => '', role => 'full' };   # the signed-in user
    if ($auth_on) {
        my %ck = map { /^\s*([^=]+)=(.*)$/ ? ($1 => $2) : () } split /;/, $h{cookie} // '';
        $who = session_valid($cfg, $ck{mtmon_session});
        # HTTP basic auth only for the API (scripts). Not for the pages: a browser that once used
        # basic auth keeps sending it, which would make signing out impossible.
        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 dashboard 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 }
    my $logged_in = $who ? 1 : 0;
    if ($route eq '/login') {
        return web_reply($c, 303, 'text/plain', '', 'Location: /') if $logged_in;
        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 dashboard: '$u->{name}' signed in from $peer" . ($u->{role} ne 'full' ? " (role $u->{role})" : ''));
                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 dashboard: failed sign-in" . (length $tried ? " as '$tried'" : '') . " from $peer" . ($locked ? ' - locked for 5 min' : ''));
            sleep 1;                                      # slows down guessing
            my $msg = $locked ? 'Too many wrong attempts. Try again in 5 min.' : 'Wrong user name or password.';
            return web_reply($c, 200, 'text/html; charset=utf-8', login_page($cfg, $msg, $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: ' . ($auth_on ? '/login' : '/'),
                         'Set-Cookie: mtmon_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict' . ($w->{_secure} ? '; Secure' : ''));
    }
    return web_reply($c, 200, 'text/plain', "ok\n") if $route eq '/healthz';
    if (!$logged_in) {
        return web_reply($c, 401, 'application/json', qq({"error":"login required"}\n)) if $route =~ m{^/api/};
        return web_reply($c, 302, 'text/plain', '', 'Location: /login');
    }
    if ($method eq 'POST' && $route =~ m{^/api/maintenance(/end)?$}) { return web_maint_post($cfg, $c, \%h, $who, $peer, $1 ? 'end' : 'add') }
    if ($route =~ m{^/api/push/(register|unregister|events)$}) { return web_push($cfg, $c, \%h, $who, $peer, $1, $method, $query) }
    return web_reply($c, 405, 'text/plain', "Only GET is supported.\n") unless $method =~ /^(GET|HEAD)$/;

    my %q = map { my ($k, $v) = split /=/, $_, 2; ($k => $v // '') } split /&/, $query // '';
    my $json = JSON::PP->new->utf8->canonical;
    if ($route eq '/api/maintenance') {
        my $now = time;
        return web_reply($c, 200, 'application/json', $json->encode({ can_edit => ($who->{role} eq 'full' ? JSON::PP::true : JSON::PP::false),
            active => [ sort { $a->{until} <=> $b->{until} } grep { $_->{until} > $now } @{ maint_load($cfg)->{mutes} } ] }));
    }
    if ($route eq '/api/inventory') {
        return web_reply($c, 200, 'application/json', $json->encode(jread(data_file($cfg->{general}, 'inventory.json')) || { rows => [] }));
    }
    if ($route eq '/api/inventory.csv') {
        my $inv = jread(data_file($cfg->{general}, 'inventory.json')) || { rows => [] };
        (my $fn = lc "mtmon-inventory-$cfg->{general}{location}") =~ s/[^a-z0-9]+/-/g;
        return web_reply($c, 200, 'text/csv; charset=utf-8', encode('UTF-8', inventory_csv($inv->{rows})),
                         "Content-Disposition: attachment; filename=\"$fn-" . strftime('%Y%m%d', localtime) . ".csv\"");
    }
    if ($route eq '/api/certificates') {
        return web_reply($c, 200, 'application/json', $json->encode(certs_status($cfg)));
    }

    if ($route eq '/manual') {
        return manual_page($c, 'mtmon', $q{lang}, $h{'accept-language'}, '/usr/share/doc/mtmon', dirname(__FILE__) . '/docs', dirname(__FILE__));
    }
    if ($route eq '/topology') {                       # 13.8: the topology on its own page (full screen, zoom, VLANs)
        my $file = (-r $w->{html} ? dirname($w->{html}) : dirname(__FILE__)) . '/topology.html';
        $file = dirname(__FILE__) . '/topology.html' unless -r $file;
        open(my $fh, '<:raw', $file) or return web_reply($c, 500, 'text/plain', "Topology page not found ($file).\n");
        local $/;
        my $html = <$fh>;
        close $fh;
        return web_reply($c, 200, 'text/html; charset=utf-8', $html,
            "Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:");
    }
    if ($route eq '/report') {
        my $file = (-r $w->{html} ? dirname($w->{html}) : dirname(__FILE__)) . '/report.html';
        $file = dirname(__FILE__) . '/report.html' unless -r $file;
        open(my $fh, '<:raw', $file) or return web_reply($c, 500, 'text/plain', "Report page not found ($file).\n");
        local $/;
        my $html = <$fh>;
        close $fh;
        my $rc = JSON::PP->new->canonical->encode({ api => 'api/clients/report', dapi => 'api/devices/report', back => './', kind => 'controllers' });
        $html =~ s{/\*MTMON-REPORT\*/}{window.REPORT = $rc;};
        return web_reply($c, 200, 'text/html; charset=utf-8', $html,
            "Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:");
    }
    if ($route eq '/' || $route eq '/index.html') {
        my $file = -r $w->{html} ? $w->{html} : dirname(__FILE__) . '/dashboard.html';
        open(my $fh, '<:raw', $file) or return web_reply($c, 500, 'text/plain', "Dashboard page not found ($w->{html}).\n");
        local $/;
        my $html = <$fh>;
        close $fh;
        return web_reply($c, 200, 'text/html; charset=utf-8', $html,
            "Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:");
    }
    if ($route eq '/api/status') {
        return web_reply($c, 200, 'application/json', $json->encode(web_status($cfg, $who)));
    }
    if ($route eq '/api/clients') {
        return web_reply($c, 200, 'application/json', $json->encode(web_clients($cfg, $who)));
    }
    if ($route =~ m{^/api/(?:history|clients/history|clients/aphistory)$} && ($q{from} // '') =~ /^\d+$/) {
        my $kind = $route eq '/api/history' ? 'history' : $route eq '/api/clients/aphistory' ? 'clientsap' : 'clients';
        my $to   = ($q{to} // '') =~ /^\d+$/ ? $q{to} : time;
        my $from = $q{from} < $to ? $q{from} : $to - 86400;
        return web_reply($c, 200, 'application/json', $json->encode(
            $kind =~ /^clients/ && !$w->{clients} ? { from => $from + 0, to => $to + 0, points => [] } : hist_range($cfg, $kind, $from + 0, $to + 0, 500)));
    }
    if ($route 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($cfg->{general}, $from + 0, $to + 0, web_status($cfg));
        $r->{location} = $cfg->{general}{location};
        return web_reply($c, 200, 'application/json', $json->encode($r));
    }
    if ($route eq '/api/clients/report') {
        return web_reply($c, 200, 'application/json', $json->encode(web_client_report($cfg, \%q, $w->{clients})));
    }
    if ($route eq '/api/clients/peaks') {
        return web_reply($c, 200, 'application/json', $json->encode($w->{clients} ? client_peaks($cfg) : { periods => [], peaks => {} }));
    }
    if ($route eq '/api/clients/history') {
        my $hours = ($q{hours} // '') =~ /^\d+$/ ? $q{hours} : 24;
        my @h = $w->{clients} ? read_jsonl(data_file($cfg->{general}, 'clients.jsonl'), time - $hours * 3600) : ();
        if (@h > 400) {
            my $step = @h / 400;
            @h = map { $h[ int($_ * $step) ] } 0 .. 399;
        }
        return web_reply($c, 200, 'application/json', $json->encode(\@h));
    }
    if ($route eq '/api/events') {
        my $limit = ($q{limit} // '') =~ /^\d+$/ ? $q{limit} : 100;
        my @ev = read_jsonl(data_file($cfg->{general}, 'events.jsonl'), time - $w->{history_days} * 86400);
        @ev = @ev[-$limit .. -1] if @ev > $limit;
        return web_reply($c, 200, 'application/json', $json->encode([ reverse @ev ]));
    }
    if ($route eq '/api/history') {
        my $hours = ($q{hours} // '') =~ /^\d+$/ ? $q{hours} : 24;
        my @h = read_jsonl(data_file($cfg->{general}, 'history.jsonl'), time - $hours * 3600);
        if (@h > 400) {                                    # at most 400 points for the chart
            my $step = @h / 400;
            @h = map { $h[ int($_ * $step) ] } 0 .. 399;
        }
        return web_reply($c, 200, 'application/json', $json->encode(\@h));
    }
    return web_reply($c, 404, 'text/plain', "Not found.\n");
}

# /api/clients/report?from=&to=[&ctl=]: from / to as epoch seconds (the page asks for whole local
# months / years / days), at most 3 years
sub web_client_report {
    my ($cfg, $q, $enabled) = @_;
    return { error => 'Wi-Fi clients are not recorded here ([web] clients = no).' } unless $enabled;
    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 $ctl = url_dec($q->{ctl});
    $ctl = '' unless grep { $_ eq $ctl } map { $_->{name} } @{ $cfg->{capsman} };
    my $cur = jread(data_file($cfg->{general}, 'clients.json')) || {};
    my %ifmap = map { ($_ => $cur->{ctl}{$_}{ifmap} || {}) } keys %{ $cur->{ctl} || {} };
    my $r = client_report_cached($cfg, $from + 0, $to + 0, $ctl, \%ifmap, ($q->{aps} // '') eq '1');
    $r->{location} = $cfg->{general}{location};
    # access points = the devices the controllers know (remote CAPs, HP / cnPilot APs), not radios or SSIDs
    my $state = load_state($cfg->{general}{state_file});
    my $n = 0;
    for my $cm (grep { client_enabled($cfg, $_) && (!length $ctl || $_->{name} eq $ctl) } @{ $cfg->{capsman} }) {
        $n += scalar keys %{ ($state->{capsman}{ $cm->{name} } || {})->{caps} || {} };
    }
    $r->{ap_count} = $n;
    $r->{controller_list} = [ map { { name => $_->{name}, title => ($_->{title} || "$_->{label} $_->{name}"), label => $_->{label} } }
                              grep { client_enabled($cfg, $_) } @{ $cfg->{capsman} } ];
    return $r;
}

# POST /api/maintenance {target, duration, reason} and /api/maintenance/end {id} - role full only
sub web_maint_post {
    my ($cfg, $c, $h, $who, $peer, $op) = @_;
    my $jr = sub { web_reply($c, $_[0], 'application/json', JSON::PP->new->utf8->canonical->encode($_[1])) };
    return $jr->(403, { error => 'Only users with role full may set maintenance windows.' }) unless ($who->{role} // '') eq 'full';
    return $jr->(415, { error => 'JSON expected' }) unless ($h->{'content-type'} // '') =~ m{^application/json}i;
    if (defined(my $or = $h->{origin})) {
        my ($oh) = $or =~ m{^https?://([^/]+)}i;
        return $jr->(403, { error => 'cross-site request refused' }) unless $oh && lc $oh eq lc($h->{host} // '');
    }
    my $len = $h->{'content-length'} // 0;
    return $jr->(413, { error => 'request too large' }) if $len !~ /^\d+$/ || $len > 8192;
    my $body = '';
    alarm 10;
    read($c, $body, $len) if $len;
    alarm 0;
    my $p = eval { JSON::PP->new->utf8->decode($body) };
    return $jr->(400, { error => 'invalid JSON' }) unless ref $p eq 'HASH';
    my $by = ($who->{name} || 'dashboard') . " ($peer)";
    if ($op eq 'end') {
        my @g = maint_end($cfg, $p->{id} // '', $by);
        return @g ? $jr->(200, { ok => JSON::PP::true, ended => [ map { $_->{id} } @g ] }) : $jr->(404, { error => 'No such maintenance window.' });
    }
    (my $t = $p->{target} // '') =~ s/^\s+|\s+$//g;
    return $jr->(400, { error => 'Target missing.' }) unless length $t && length $t <= 200;
    my ($from, $until) = eval { maint_window($p->{duration} // '', time) };
    return $jr->(400, { error => ($@ =~ s/\s+$//r) }) unless $until;
    my @hit = maint_targets($cfg, $t);
    return $jr->(400, { error => "'$t' matches nothing." }) unless @hit;
    my $m = maint_add($cfg, target => $t, from => $from, until => $until, reason => substr($p->{reason} // '', 0, 200), by => $by);
    return $jr->(200, { ok => JSON::PP::true, maintenance => $m, matches => \@hit });
}

# failed sign-ins per address + user name, shared by all web processes (a small file under a lock).
# 5 wrong passwords lock that name from that address for 5 minutes; others behind the same address
# (an office, a VPN) are not affected. op: check | fail | ok; returns the seconds still locked.
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) }

# random secret in the state directory: sessions survive restarts; changing the
# password in the config invalidates all sessions (it is part of the signature)
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;
}

# session cookie: <user, base64url>.<expiry>.<signature>. The signature includes the user's
# password (or hash), so changing or removing one user signs out only that user.
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;
}

# ---- 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 (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 push-tokens.json next to the state. (The centre has the same, for
# all its sites - turn the notifications on in one place only, or each outage comes twice.)
sub push_types { qw(ap_missing ap_back dev_down dev_up ctl_down ctl_up disk_low disk_ok) }
sub push_file { data_file($_[0]{general}, 'push-tokens.json') }
sub web_fail_file { data_file($_[0]{general}, 'web-fail.json') }
sub push_tokens { jread(push_file($_[0])) || {} }
sub push_change {
    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);
    jwrite(push_file($cfg), $t);
    close $lk;
    return $r;
}
sub push_user {
    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;
}
sub web_push {
    my ($cfg, $c, $h, $who, $peer, $what, $method, $query) = @_;
    my $json = JSON::PP->new->utf8->canonical;
    my $jr = sub { web_reply($c, $_[0], 'application/json', $json->encode($_[1])) };
    my %q = map { my ($k, $v) = split /=/, $_, 2; ($k => $v // '') } split /&/, $query // '';
    my $g = $cfg->{general};
    if ($what eq 'register') {
        return $jr->(405, { error => 'POST only' }) unless $method eq 'POST';
        return $jr->(403, { error => 'sign in with a user, not with a key' }) if $who->{_push} || exists $who->{_allow};
        my $len = $h->{'content-length'} // 0;
        return $jr->(413, { error => 'too large' }) if $len !~ /^\d+$/ || $len > 4096;
        my $body = '';
        alarm 10; read($c, $body, $len) if $len; alarm 0;
        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 $jr->(200, { token => $tok, name => $name, types => [ push_types() ], location => $g->{location} });
    }
    return $jr->(401, { error => 'device token required' }) unless $who->{_push};
    if ($what eq 'unregister') {
        push_change($cfg, sub { delete $_[0]{ $who->{_push} } });
        logmsg('info', "Push: phone '$who->{_push_name}' unregistered");
        return $jr->(200, { ok => JSON::PP::true });
    }
    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 $hh = $who->{_push};
    my $t = push_tokens($cfg);
    if ($t->{$hh} && ($t->{$hh}{seen} // 0) < $now - 3600) { eval { push_change($cfg, sub { $_[0]{$hh}{seen} = $now if $_[0]{$hh} }) } }
    my %want = map { ($_ => 1) } push_types();
    my $f = data_file($g, 'events.jsonl');
    my ($end, $mt, @ev) = (time + $wait, -1);
    while (1) {
        my $m = (stat $f)[9] // 0;
        if ($m != $mt) {
            $mt = $m;
            # 13.5: a device by its name, never by its MAC (an access point without an identity: its IP)
            @ev = map { { t => $_->{t}, site => '', site_title => $g->{location}, type => $_->{type},
                          name => (($_->{name} // '') =~ /^(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}$/i || !length($_->{name} // '') ? ($_->{ip} || $_->{host} || $_->{name} // '') : $_->{name}),
                          ip => $_->{ip} // $_->{host} // '', text => $_->{text} // '', heading => $_->{heading} // '' } }
                  grep { $want{ $_->{type} // '' } && !$_->{maint} && !$_->{behind} && $_->{t} > $since } ($m >= $since ? read_jsonl($f, $since) : ());
        }
        last if @ev || time >= $end;
        sleep 2;
    }
    return $jr->(200, { now => time + 0, events => \@ev, location => $g->{location} });
}

# API key from "Authorization: Bearer KEY" -> pseudo user (role from [api keys]), or undef
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 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;
}

# --new-api-key NAME: a random key (shown once) and the line for [api keys]
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/mtmon.conf and run systemctl reload mtmon:\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>:8686/api/status\n";
    return 0;
}

# password check: plain text or {PBKDF2}iterations$salt$hash (PBKDF2-HMAC-SHA256, mtmon --hash-password)
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/mtmon.conf, e.g.:  [web users]  name = <the line above>\n" if $tty;
    return 0;
}

sub login_page {
    my ($cfg, $msg, $user) = @_;
    my $loc  = h($cfg->{general}{location});
    my $u    = h($user // '');
    my $prod = 'MT-Mon network monitor';
    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 web_status {
    my ($cfg, $who) = @_;
    my $g = $cfg->{general};
    my $state = load_state($g->{state_file});
    my $now = time;
    my $M = maint_ctx($cfg, $now);
    my $mu = sub { my $m = shift; return $m ? $m->{until} + 0 : undef };
    my $mi = sub { my $m = shift; return $m ? $m->{id} : undef };
    my $apdb = jread(ap_ports_file($g)) || {};
    my $topo_all = jread(topo_file($g)) || {};
    my $topo = $topo_all->{nodes} || {};                               # 13.6: what hangs on which port
    my $topo_t = $topo_all->{t};
    my @ctl;
    for my $cm (@{ $cfg->{capsman} }) {
        my $cs = $state->{capsman}{ $cm->{name} } || {};
        my $cc = $cs->{caps} || {};
        my @aps = map {
            my $apo = ap_ports_status(($apdb->{ $cm->{name} } || {})->{$_}, $now);
            $apo->{links} = $topo->{"ap:$cm->{name}:$_"}{links} if $apo && $topo->{"ap:$cm->{name}:$_"} && $topo->{"ap:$cm->{name}:$_"}{links};
            my $tk = "ap:$cm->{name}:$_";
            local $_ = $cc->{$_};
            +{ identity => $_->{identity}, ip => $_->{ip}, mac => $_->{mac}, info => $_->{board}, state => $_->{state}, ($apo ? (snmp => $apo) : ()), tk => $tk,
              status => ($_->{missing_since} ? 'missing' : 'online'), version => $_->{version},
              last_seen => $_->{last_seen}, missing_since => $_->{missing_since}, first_seen => $_->{first_seen},
              maint => $mu->(m_ap($M, $cm, $_)), maint_id => $mi->(m_ap($M, $cm, $_)), ($_->{flap_since} ? (flap => $_->{flap_n} + 0, flap_since => $_->{flap_since}) : ()),
              ($_->{missing_since} && ($_->{hidden} // '') eq 'dep' ? (behind => $_->{behind}) : ()) }
        } keys %$cc;
        push @ctl, { name => $cm->{name}, label => $cm->{label}, heading => dev_heading($cm), host => $cm->{host},
                     identity => $cs->{identity}, info_label => col4($cm), maint => $mu->(m_ctl($M, $cm)), maint_id => $mi->(m_ctl($M, $cm)),
                     status => (!$cs->{initialized} && !$cs->{down_since} ? 'unknown' : $cs->{down_since} ? 'down' : 'up'),
                     down_since => $cs->{down_since}, fails => $cs->{fails} // 0,
                     ($cs->{down_since} && ($cs->{down_hidden} // '') eq 'dep' ? (behind => $cs->{behind}) : ()),
                     aps => [ sort { lc($a->{identity} // '') cmp lc($b->{identity} // '') } @aps ] };
    }
    my @dev;
    for my $sw (@{ $cfg->{switches} }) {
        my $st = $state->{switches}{ $sw->[0] };
        my $d = { host => $sw->[0], desc => $sw->[1],
                  status => (!$st ? 'unknown' : $st->{down_since} ? 'down' : ($st->{fails} ? 'warn' : 'up')),
                  last_ok => $st ? $st->{last_ok} : undef, down_since => $st ? $st->{down_since} : undef,
                  muted => ($st && $st->{muted}) ? JSON::PP::true : JSON::PP::false, maint => $mu->(m_dev($M, $sw->[0], $sw->[1])), maint_id => $mi->(m_dev($M, $sw->[0], $sw->[1])),
                  ($st && $st->{down_since} && ($st->{hidden} // '') eq 'dep' ? (behind => $st->{behind}) : ()) };
        if ($st && $st->{flap_since}) { $d->{flap} = $st->{flap_n} + 0; $d->{flap_since} = $st->{flap_since} }
        if ($sw->[2]{snmp}) {
            my $sn = ($st && $st->{snmp}) || {};
            my @alerts = map { { key => $_, text => $st->{alerts}{$_}{text}, since => $st->{alerts}{$_}{since}, sent => ($st->{alerts}{$_}{sent} ? 1 : 0) } }
                         sort keys %{ ($st && $st->{alerts}) || {} };
            my %ul = map { ($_->[7] => $_) } grep { defined $_->[7] } @{ $sn->{ports} || [] };
            $d->{snmp} = {
                state => ($sn->{err} ? 'error' : $sn->{t} ? 'ok' : 'waiting'), err => $sn->{err}, t => $sn->{t},
                uptime => (!$sn->{err} && defined $sn->{uptime} ? $sn->{uptime} + ($now - ($sn->{t} // $now)) : undef),
                descr => $sn->{descr}, sysname => $sn->{sysname}, poe => $sn->{poe}, temp => $sn->{temp},
                uplinks => [ map { my $p = $ul{ $_->[0] }; +{ port => $_->[0], want => $_->[1], name => $p ? $p->[1] : undef,
                                   oper => $p ? $p->[3] : undef, admin => $p ? $p->[4] : undef, speed => $p ? $p->[5] : undef,
                                   errors => $p ? $p->[6] : undef, max => ($st && $st->{speed_max} ? $st->{speed_max}{ $_->[0] } : undef) } } @{ $sw->[2]{uplinks} } ],
                alerts => \@alerts, ports => $sn->{ports} || [], ($topo->{"dev:$sw->[0]"} && $topo->{"dev:$sw->[0]"}{links} ? (links => $topo->{"dev:$sw->[0]"}{links}) : ()),
            };
            $d->{status} = 'warn' if $d->{status} eq 'up' && grep { $_->{sent} } @alerts;
        }
        push @dev, $d;
    }
    my $inv = jread(data_file($g, 'inventory.json')) || {};
    my @mm = grep { $_->{mismatch} } @{ $inv->{rows} || [] };
    return {
        version => $VERSION, location => $g->{location}, host => hostname(), now => $now,
        auth => (%{ $cfg->{web}{_users} } ? JSON::PP::true : JSON::PP::false), user => ($who ? $who->{name} : ''),
        role => ($who ? $who->{role} : 'full'),
        last_check => $state->{last_check}, interval => $g->{interval} + 0, refresh => $cfg->{web}{refresh} + 0,
        cap_miss_threshold => $g->{cap_miss_threshold} + 0, fail_threshold => $g->{fail_threshold} + 0,
        flap => { count => $g->{flap_count} + 0, window => $g->{flap_window} + 0 },
        controllers => \@ctl,
        devices => { heading => $g->{_switches_title} // 'Switches (ping)', items => \@dev },
        # 13.7: the tree of what is behind what, for the Topology panel (keys: dev:HOST, ctl:NAME, ap:CTL:KEY)
        (%$topo ? (topology => { t => $topo_t, nodes => { map { my $n = $topo->{$_};
            ($_ => { (map { defined $n->{$_} ? ($_ => $n->{$_}) : () } qw(name kind ip parent how port cport same)),
                      (($n->{kind} // '') eq 'ctl' && $n->{links} ? (links => $n->{links}) : ()) }) } keys %$topo } }) : ()),
        maintenance => [ map { my @w = maint_targets($cfg, $_->{target} // ''); +{ %$_, what => [ @w > 12 ? (@w[0 .. 10], (@w - 11) . ' more') : @w ] } }
                         sort { $a->{until} <=> $b->{until} } grep { $_->{until} > $now } @{ maint_load($cfg)->{mutes} } ],
        certs => certs_status($cfg),
        (($who && $who->{role} ne 'full') ? () : (server => server_info(data_file($g, 'server.json'), dirname($g->{state_file}), $g->{disk_warn}, 'mtmon', $VERSION))),
        inventory_info => { t => $inv->{t}, refreshed => $inv->{refreshed}, rows => scalar(@{ $inv->{rows} || [] }), mismatch => scalar @mm },
        ($who ? () : (inventory => $inv->{rows} || [])),       # the centre gets the whole list
    };
}

# When running as root and the mtmon user exists, switch to it so that state and
# known_hosts always stay owned by mtmon (MTMON_RUN_AS_ROOT=1 disables this).
# --changelog [VERSION]: the whole CHANGELOG.md, or only the versions newer than VERSION
sub show_changelog {
    my ($since) = @_;
    my ($file) = grep { -r } '/usr/share/mtmon/CHANGELOG.md', '/usr/share/doc/mtmon/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 @lines = <$fh>;
    close $fh;
    if (!length($since // '')) { print @lines; return 0 }
    $since =~ s/^v//i;
    return do { print STDERR "--changelog: '$since' is not a version\n"; 2 } unless $since =~ /^\d+(?:[.\-]\d+)*$/;
    my $newer = sub {        # numeric compare, 7.10.0 > 7.9.1; a missing part counts as 0
        my @a = split /[.\-]/, $_[0]; my @b = split /[.\-]/, $since;
        for my $i (0 .. ($#a > $#b ? $#a : $#b)) {
            my ($x, $y) = ($a[$i] // 0, $b[$i] // 0);
            return $x > $y if $x != $y;
        }
        return 0;
    };
    my ($show, $n) = (0, 0);
    for my $l (@lines) {
        if ($l =~ /^## (\S+)/) { $show = $newer->($1); $n++ if $show }
        print $l if $show;
    }
    print "No changes after $since (installed: $VERSION).\n" unless $n;
    return 0;
}

sub drop_privileges {
    return if $> != 0 || $ENV{MTMON_RUN_AS_ROOT};
    my @pw = getpwnam('mtmon') 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 failed\n" if $< != $uid || $> != $uid;
    chdir '/';
}

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

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 usage {
    my ($rc) = @_;
    print <<"EOT";
mtmon $VERSION - MikroTik CAPsMAN access point and switch monitor

Usage: mtmon [-c config] [options]

  -c, --config FILE   configuration file (default /etc/mtmon/mtmon.conf)
      --once          run a single cycle and exit (for cron or testing)
  -n, --dry-run       print mail to the screen, do not save state
  -d, --debug         verbose output
      --check         test the connection to all devices and print what is seen
      --discover      list devices from the MikroTik neighbor tables as [switches] lines
      --clients       read the Wi-Fi clients of all controllers now and print them per SSID
      --hash-password ask for a password and print its hash for [web users]
      --new-api-key NAME
                      create an API key for scripts / apps and print the line for [api keys]
      --push-list     list the phones that get push notifications from this mtmon (MT-Mon app)
      --push-remove NAME|all
                      stop push notifications to a phone (name from --push-list) or to all
      --rename-ssid OLD NEW [CONTROLLER]
                      rename an SSID in the recorded Wi-Fi client history (all controllers,
                      or only the [capsman]/[msm]/[cnpilot] section CONTROLLER)
      --test-central  send the status to the mtmon-admin-center now ([central]) and show the result
      --central-resend
                      send the whole local history to the centre again - every check of history_days,
                      every hour of history_hourly_days, every day, all events (a new centre, or one
                      that lost its data; the centre keeps each record once; centre 7.21.0+)
      --web           run only the web dashboard in the foreground (normally started by the daemon)
      --test-mail     send a test message
      --show          print the recorded access point and switch state
      --report        check all devices now and mail the full status; changes nothing
      --period-report week|month|7d
                      mail the report of the last complete week / month (or the last N days) now
      --mute TARGET DURATION [REASON]
                      maintenance window: no mails about TARGET (all, a [capsman]/[msm]/[cnpilot] name, an
                      access point, a switch IP or description; * ? wildcards) for DURATION
                      (2h, 90m, 1d, until 18:00, window 22:00-02:00)
      --unmute ID|TARGET|all
                      end a maintenance window early
      --mutes         list the maintenance windows
      --inventory [--csv]
                      models, serial numbers and versions of all devices (asks them now)
      --certs         check the certificates of [certificates] now and print them
      --ap-ports [AP] read the ports and VLANs of the access points now (or of one: IP, name or MAC)
      --topology      find what is behind what now (LLDP/CDP, MAC tables, routes) and print it as a tree
      --agent         run without a disk (MikroTik container): the configuration comes from the centre,
                      the data is in MTMON_DATA (/tmp/mtmon), mails are sent by the centre; needs
                      MTMON_CENTRAL (https://centre/) and MTMON_KEY, optional MTMON_FINGERPRINT
                      and print them
      --server        what mtmon uses on this server (memory, CPU, processes), free disk space
                      and the size of its data
      --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
      --forget X      remove an access point from the state (MAC, identity or IP)
      --reset         delete the state (next cycle = new baseline)
      --changelog [V] print the change history (with a version: only the changes after it)
  -V, --version       print the version
  -h, --help          this help

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

# ==========================================================================
# Small helpers (11.0)
# ==========================================================================
sub yesno {
    my ($v, $what) = @_;
    return 1 if !defined $v || $v =~ /^(1|yes|da|true|on)$/i;
    return 0 if $v =~ /^(0|no|ne|false|off)$/i;
    die "$what must be yes or no\n";
}

# JSON file next to the state file: read (undef if missing / broken), write atomically
# ==========================================================================
# The server: what this program itself uses (memory, CPU, processes) and the disk of its data.
# Read straight from the kernel (cgroup of the systemd service, /proc) - no extra programs except
# one "df" per sample. The daemon samples every cycle into server.json (CPU over the last cycle,
# folder sizes every 10 min, the disk alert); the web part adds the live numbers when asked.
# ==========================================================================
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;
}

# memory (bytes, without the file cache), cache, CPU time used so far (microseconds), processes
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;
}

# the file system of a folder: size, used, free (bytes), mount point
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;
}

# space used on the disk by a folder: each entry of it, and the entries one level below its folders
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 };
}

# daemon side, once per cycle: CPU since the last sample, folder sizes (every 10 min), the disk and
# its alert. Returns (sample, 'low' | 'ok' | undef, commit) - commit writes server.json (after the mail)
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;
}

# web side: the sample plus the live numbers, for the status JSON
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) : ()),
    };
}

# mail section of the disk alert ('low' / 'ok')
sub server_section {
    my ($ss, $tr, $warn, $root) = @_;
    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})
             . " (alert below $warn %)";
    return { type => 'server', heading => 'Server', groups => [ { kind => ($tr eq 'low' ? 'd_low' : 'd_ok'),
             items => [ { name => hostname(), target => ($df->{mount} // '?') . " (data in $root)", text => $text } ] } ] };
}

# --server: the same numbers as the "Server" panel of the dashboard
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;
}

# the files of the data folder in groups people understand
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 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 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";
}

# 10000 -> "10 Gbit/s", 100 -> "100 Mbit/s" (value in Mbit/s)
sub fmt_speed {
    my ($m) = @_;
    return '-' unless $m;
    return ($m / 1000000) . ' Tbit/s' if $m >= 1000000 && $m % 100000 == 0;
    return ($m / 1000) . ' Gbit/s' if $m >= 1000 && $m % 100 == 0;
    return "$m Mbit/s";
}

# ==========================================================================
# Certificates: expiry of web / mail server certificates ([certificates]), checked with the
# openssl command once per check_hours; a warning at each of warn_days (30, 14, 7, 3, 1)
# ==========================================================================
sub cert_target {
    my ($name, $v, $line, $file) = @_;
    my %t = (name => $name);
    $v =~ s/^\s+|\s+$//g;
    my %def = (https => [443], smtp => [25, 'smtp'], submission => [587, 'smtp'], smtps => [465], imap => [143, 'imap'],
               imaps => [993], pop3 => [110, 'pop3'], pop3s => [995], ldaps => [636], ftp => [21, 'ftp'], tls => [443]);
    if ($v =~ m{^file:(/\S+)$}i) { $t{file} = $1; $t{show} = $1 }
    elsif ($v =~ m{^([a-z0-9]+)://(\[[^\]]+\]|[^/:\s]+)(?::(\d+))?/?$}i && $def{ lc $1 }) {
        my ($sch, $h, $p) = (lc $1, $2, $3);
        ($t{host} = $h) =~ s/^\[|\]$//g;
        $t{port} = $p // $def{$sch}[0];
        $t{starttls} = $def{$sch}[1];
        $t{show} = "$sch://$h" . ($p ? ":$p" : '');
    }
    elsif ($v =~ /^(\[[^\]]+\]|[^\/:\s]+):(\d+)$/) { ($t{host} = $1) =~ s/^\[|\]$//g; $t{port} = $2; $t{show} = $v }
    elsif ($v =~ /^[\w.-]+$/) { $t{host} = $v; $t{port} = 443; $t{show} = "https://$v" }
    else {
        die "$file:$line: [certificates] $name: expected https://host[:port], smtp://host[:port], imaps://host, host:port or file:/path\n";
    }
    die "$file:$line: [certificates] $name: invalid port\n" if defined $t{port} && ($t{port} < 1 || $t{port} > 65535);
    die "$file:$line: [certificates] $name: invalid host\n" if defined $t{host} && $t{host} =~ /^-/;
    return \%t;
}

# configured certificates + the dashboard's own one
sub cert_list {
    my ($cfg) = @_;
    my $ct = $cfg->{certs};
    my @t = @{ $ct->{_targets} || [] };
    my $w = $cfg->{web};
    if ($ct->{web} && $w->{enabled} && $w->{tls}) {
        my ($crt) = grep { -r } $w->{cert_file}, dirname($cfg->{general}{state_file}) . '/web.crt';
        push @t, { name => 'Web dashboard (this server)', file => $crt, show => $crt, own => 1 } if $crt;
    }
    return @t;
}

# notAfter=Feb  3 12:00:00 2027 GMT -> epoch
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 cert_check {
    my ($t, $timeout) = @_;
    my $pem;
    if ($t->{file}) {
        open(my $fh, '<', $t->{file}) or return { error => "cannot read $t->{file}: $!" };
        local $/;
        $pem = <$fh> // '';
        close $fh;
    } else {
        my $hp = ($t->{host} =~ /:/ ? "[$t->{host}]" : $t->{host}) . ":$t->{port}";
        my @cmd = ('openssl', 's_client', '-connect', $hp,
                   ($t->{host} =~ /^[\d.:]+$/ ? () : ('-servername', $t->{host})),
                   ($t->{starttls} ? ('-starttls', $t->{starttls}) : ()));
        my ($rc, $out, $err) = eval { run_cmd($timeout, @cmd) };
        return { error => ($@ =~ s/\s+$//r =~ s/^openssl to \S+: /connection: /r) } unless defined $rc;
        $pem = $out;
        if ($pem !~ /-----BEGIN CERTIFICATE-----/) {
            my ($e) = grep { /\S/ && !/^(depth=|verify |---|CONNECTED|\s)/ } split /\n/, $err;
            $e =~ s/^[0-9A-F]+:error:[0-9A-F]+:// if defined $e;
            return { error => 'no certificate received' . ($e ? " ($e)" : '') };
        }
    }
    my ($first) = $pem =~ /(-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/s
        or return { error => 'no PEM certificate found' };
    my ($fh, $tmp) = tempfile('mtmon-cert-XXXXXX', TMPDIR => 1);
    print {$fh} $first;
    close $fh;
    my ($rc, $out) = eval { run_cmd(15, 'openssl', 'x509', '-in', $tmp, '-noout', '-enddate', '-subject', '-issuer') };
    unlink $tmp;
    return { error => 'openssl cannot read the certificate' } unless defined $rc && $rc == 0;
    my %r;
    for my $l (split /\n/, $out) {
        if    ($l =~ /^notAfter=(.*)/) { $r{not_after} = cert_date($1) }
        elsif ($l =~ /^subject=\s*(.*)/) { $r{subject} = $1 }
        elsif ($l =~ /^issuer=\s*(.*)/)  { $r{issuer} = $1 }
    }
    return { error => 'expiry date not readable' } unless $r{not_after};
    for my $k (qw(subject issuer)) {       # "CN = example.com, O = ..." -> the CN only
        next unless defined $r{$k};
        my ($cn) = $r{$k} =~ /CN\s*=\s*([^,\/]+)/;
        my ($o)  = $r{$k} =~ /\bO\s*=\s*([^,\/]+)/;
        $r{$k} = ($cn // $o // $r{$k}) =~ s/^\s+|\s+$//gr;
    }
    $r{self_signed} = (defined $r{subject} && defined $r{issuer} && $r{subject} eq $r{issuer}) ? 1 : 0;
    return \%r;
}

# smallest warn_days threshold the certificate has reached (-1 = expired, undef = none)
sub cert_level {
    my ($ct, $not_after, $now) = @_;
    return -1 if $not_after <= $now;
    my $d = ($not_after - $now) / 86400;
    my @ge = grep { $d <= $_ } @{ $ct->{_warn} };
    return @ge ? $ge[-1] : undef;
}

sub cert_days { my ($na, $now) = @_; return int(($na - $now) / 86400) }

# one check cycle: returns a mail section (or undef) and silent items; daily (check_hours)
sub certs_cycle {
    my ($cfg, $now, $subject, $force) = @_;
    my $ct = $cfg->{certs};
    return () unless $ct->{enabled};
    my @t = cert_list($cfg);
    my $f = data_file($cfg->{general}, 'certs.json');
    my $st = jread($f) || {};
    my $sig = md5_hex(encode('UTF-8', join '|', map { "$_->{name}=$_->{show}" } @t));
    if (!@t) { unlink $f if -e $f; return () }
    return () if !$force && ($st->{sig} // '') eq $sig && $now - ($st->{t} // 0) < $ct->{check_hours} * 3600;
    my $M = $cfg->{_M} || maint_ctx($cfg, $now);
    my (%new, @exp, @ren, @sexp, @sren);
    for my $t (@t) {
        my $old = $st->{certs}{ $t->{name} } || {};
        my $r = cert_check($t, $ct->{timeout});
        my %e = (name => $t->{name}, target => $t->{show}, checked => $now + 0, ($t->{own} ? (own => 1) : ()));
        if ($r->{error}) {
            %e = (%e, error => $r->{error}, fails => ($old->{fails} // 0) + 1);
            $e{$_} = $old->{$_} for grep { defined $old->{$_} } qw(not_after subject issuer warned self_signed);
            logmsg($e{fails} == 1 ? 'warn' : 'debug', "Certificate $t->{name} ($t->{show}): $r->{error}");
        } else {
            %e = (%e, %$r);
            $e{warned} = $old->{warned} if defined $old->{warned};
            my $lvl = cert_level($ct, $r->{not_after}, $now);
            my $item = { name => $t->{name}, target => $t->{show}, not_after => $r->{not_after}, subject => $r->{subject},
                         days => cert_days($r->{not_after}, $now) };
            $item->{text} = $r->{not_after} <= $now ? 'EXPIRED on ' . fmt_time($r->{not_after})
                          : "expires in $item->{days} day" . ($item->{days} == 1 ? '' : 's') . ' (' . fmt_time($r->{not_after}) . ')';
            my $quiet = m_any($M, $t->{name});
            if (defined $lvl && (!defined $e{warned} || $lvl < $e{warned})) {
                $e{warned} = $lvl;
                push @{ $quiet ? \@sexp : \@exp }, $item;
            } elsif (!defined $lvl && defined $e{warned}) {
                delete $e{warned};
                $item->{text} = 'renewed, valid until ' . fmt_time($r->{not_after});
                push @{ $quiet ? \@sren : \@ren }, $item;
            }
        }
        $new{ $t->{name} } = \%e;
    }
    my $commit = sub { jwrite($f, { t => $now + 0, sig => $sig, certs => \%new }) };
    my (@groups, @sgroups);
    push @groups, { kind => 'c_exp', items => \@exp } if @exp;
    push @groups, { kind => 'c_ren', items => \@ren } if @ren;
    push @sgroups, { kind => 'c_exp', maint => 1, items => \@sexp } if @sexp;
    push @sgroups, { kind => 'c_ren', items => \@sren } if @sren;
    push @$subject, scalar(@exp) . " certificate(s) expiring" if @exp;
    push @$subject, scalar(@ren) . " certificate(s) renewed" if @ren;
    return ((@groups ? { type => 'certs', heading => 'Certificates', groups => \@groups } : undef),
            (@sgroups ? { type => 'certs', heading => 'Certificates', groups => \@sgroups } : undef), $commit);
}

sub certs_status {
    my ($cfg) = @_;
    my $st = jread(data_file($cfg->{general}, 'certs.json')) || {};
    my $now = time;
    return [ map {
        my $e = $st->{certs}{$_};
        +{ %$e, days => ($e->{not_after} ? cert_days($e->{not_after}, $now) : undef),
          level => ($e->{not_after} ? cert_level($cfg->{certs}, $e->{not_after}, $now) : undef) }
    } sort { lc $a cmp lc $b } keys %{ $st->{certs} || {} } ];
}

# --certs: check all certificates now and print them (changes nothing)
sub certs_cli {
    my ($cfg) = @_;
    my @t = cert_list($cfg);
    if (!@t) { print "No certificates configured ([certificates]).\n"; return 0 }
    my $now = time;
    my $bad = 0;
    printf "%-28s %-38s %-17s %s\n", 'Name', 'Target', 'Valid until', 'Status';
    for my $t (@t) {
        my $r = cert_check($t, $cfg->{certs}{timeout});
        my $st;
        if ($r->{error}) { $st = "ERROR: $r->{error}"; $bad = 1 }
        else {
            my $d = cert_days($r->{not_after}, $now);
            my $l = cert_level($cfg->{certs}, $r->{not_after}, $now);
            $st = $r->{not_after} <= $now ? 'EXPIRED' : "$d days" . (defined $l ? " - warning (within $l days)" : '');
            $st .= ", $r->{subject}" if $r->{subject};
            $st .= ' (self-signed)' if $r->{self_signed};
        }
        printf "%-28s %-38s %-17s %s\n", substr($t->{name}, 0, 28), substr($t->{show} // '', 0, 38),
            $r->{not_after} ? fmt_time($r->{not_after}) : '-', $st;
    }
    return $bad ? 2 : 0;
}

# ==========================================================================
# Maintenance windows: no mails about a muted target until the window ends.
#   mtmon --mute TARGET DURATION [REASON], --unmute TARGET|ID|all, --mutes
# TARGET: all (whole site), a [capsman]/[msm]/[cnpilot] name (the controller and all its access points),
# an access point (identity, MAC, IP), a switch (IP or description); * and ? as wildcards.
# What goes down during the window is mailed after it, if it is still down then.
# ==========================================================================
sub maint_path { data_file($_[0]{general}, 'maintenance.json') }

sub maint_load {
    my ($cfg) = @_;
    my $d = jread(maint_path($cfg)) || {};
    $d->{mutes} = [ grep { ref $_ eq 'HASH' && $_->{id} && $_->{until} && defined $_->{target} } @{ $d->{mutes} || [] } ];
    return $d;
}

# locked read-modify-write; $fn->($data) returns true to save
sub maint_edit {
    my ($cfg, $fn) = @_;
    my $lf = maint_path($cfg) . '.lock';
    open(my $lk, '>>', $lf) or die "Cannot open $lf: $!\n";
    flock($lk, LOCK_EX) or die "flock $lf: $!\n";
    my $d = maint_load($cfg);
    my $r = $fn->($d);
    jwrite(maint_path($cfg), $d) if $r;
    close $lk;
    return $r;
}

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_active { my ($m, $now) = @_; return ($m->{from} // 0) <= $now && $m->{until} > $now }
sub maint_ctx {
    my ($cfg, $now) = @_;
    return { now => $now, list => [ grep { maint_active($_, $now) } @{ maint_load($cfg)->{mutes} } ] };
}
sub m_site { my ($M) = @_; return (grep { $_->{target} =~ /^(all|\*)$/i } @{ $M->{list} })[0] }
sub m_ctl  { my ($M, $cm) = @_; return m_site($M) // (grep { maint_match($_->{target}, $cm->{name}, $cm->{host}, dev_heading($cm)) } @{ $M->{list} })[0] }
sub m_ap   { my ($M, $cm, $r) = @_; return m_ctl($M, $cm) // (grep { maint_match($_->{target}, $r->{identity}, $r->{mac}, $r->{ip}) } @{ $M->{list} })[0] }
sub m_dev  { my ($M, $h, $d) = @_; return m_site($M) // (grep { maint_match($_->{target}, $h, $d) } @{ $M->{list} })[0] }
sub m_any  { my ($M, @n) = @_; return m_site($M) // (grep { maint_match($_->{target}, @n) } @{ $M->{list} })[0] }

# what a target matches now -> list of "kind name" (for the confirmation and to refuse typos)
sub maint_targets {
    my ($cfg, $target) = @_;
    return ('the whole site') if $target =~ /^(all|\*)$/i;
    my $state = load_state($cfg->{general}{state_file});
    my @hit;
    for my $cm (@{ $cfg->{capsman} }) {
        if (maint_match($target, $cm->{name}, $cm->{host}, dev_heading($cm))) { push @hit, "$cm->{label} $cm->{name} with all its access points"; next }
        for my $a (values %{ ($state->{capsman}{ $cm->{name} } || {})->{caps} || {} }) {
            push @hit, "access point " . ($a->{identity} || $a->{mac}) if maint_match($target, $a->{identity}, $a->{mac}, $a->{ip});
        }
    }
    for my $sw (@{ $cfg->{switches} }) { push @hit, "device $sw->[1] ($sw->[0])" if maint_match($target, $sw->[0], $sw->[1]) }
    for my $t (cert_list($cfg)) { push @hit, "certificate $t->{name}" if maint_match($target, $t->{name}) }
    return @hit;
}

# local time HH:MM on the day of $base (or the given YYYY-MM-DD)
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);
}

# "2h", "90m", "1d12h", "45" (minutes), "18:00" (until), "22:00-02:00" (window),
# "2026-11-20T22:00-2026-11-21T02:00" -> (from, until)
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 maint_event {
    my ($cfg, $type, $m, $by) = @_;
    my $txt = $type eq 'maint_start'
        ? 'until ' . fmt_time($m->{until}) . (($m->{from} // 0) > time ? ' (from ' . fmt_time($m->{from}) . ')' : '')
        : ($by // 'ended');
    append_jsonl($cfg->{general}, 'events.jsonl', { t => time + 0, type => $type, name => $m->{target}, text => $txt,
                                                    reason => $m->{reason} // '', by => $m->{by} // '', id => $m->{id},
                                                    from => ($m->{from} // 0) + 0, until => $m->{until} + 0 });
    # 13.5: the centre hears of it within seconds (the daemon sends a report when it sees this file), not at the next check
    if ($cfg->{central}{enabled} && open(my $fh, '>', data_file($cfg->{general}, 'central-now'))) { close $fh }
}

# add a window; returns the entry
sub maint_add {
    my ($cfg, %a) = @_;
    my $now = time;
    my $m = { id => ($a{id} // substr(md5_hex(time . $$ . rand()), 0, 8)), target => $a{target}, from => $a{from} + 0,
              until => $a{until} + 0, reason => $a{reason} // '', by => $a{by} // '', created => $now + 0 };
    maint_edit($cfg, sub {
        my ($d) = @_;
        return 0 if grep { $_->{id} eq $m->{id} } @{ $d->{mutes} };    # already there (resent by the centre)
        push @{ $d->{mutes} }, $m;
        return 1;
    }) or return $m;
    maint_event($cfg, 'maint_start', $m);
    logmsg('info', "Maintenance: '$m->{target}' muted until " . fmt_time($m->{until})
         . ($m->{from} > $now ? ' from ' . fmt_time($m->{from}) : '') . ($m->{by} ? " by $m->{by}" : '')
         . (length $m->{reason} ? " ($m->{reason})" : ''));
    return $m;
}

# end windows by id or target (or all); returns the ended entries
sub maint_end {
    my ($cfg, $what, $by) = @_;
    my @gone;
    maint_edit($cfg, sub {
        my ($d) = @_;
        my @keep;
        for my $m (@{ $d->{mutes} }) {
            if ($what eq '*all*' || $m->{id} eq $what || lc $m->{target} eq lc $what) { push @gone, $m } else { push @keep, $m }
        }
        $d->{mutes} = \@keep;
        return scalar @gone;
    });
    for my $m (@gone) {
        maint_event($cfg, 'maint_end', $m, 'ended early' . ($by ? " by $by" : ''));
        logmsg('info', "Maintenance: '$m->{target}' ended" . ($by ? " by $by" : ''));
    }
    return @gone;
}

# windows that are over: removed (once, by the daemon)
sub maint_prune {
    my ($cfg, $now) = @_;
    my @gone;
    maint_edit($cfg, sub {
        my ($d) = @_;
        @gone = grep { $_->{until} <= $now } @{ $d->{mutes} };
        $d->{mutes} = [ grep { $_->{until} > $now } @{ $d->{mutes} } ];
        return scalar @gone;
    }) if -e maint_path($cfg);
    maint_event($cfg, 'maint_end', $_, 'ended') for @gone;
    return @gone;
}

sub maint_list_cli {
    my ($cfg) = @_;
    my $now = time;
    my @m = sort { $a->{until} <=> $b->{until} } grep { $_->{until} > $now } @{ maint_load($cfg)->{mutes} };
    if (!@m) { print "No maintenance window.\n"; return 0 }
    printf "%-8s %-24s %-17s %-17s %-12s %s\n", qw(ID Target From Until By Reason);
    printf "%-8s %-24s %-17s %-17s %-12s %s\n", $_->{id}, substr($_->{target}, 0, 24), fmt_time($_->{from}),
        fmt_time($_->{until}), substr($_->{by} || '-', 0, 12), $_->{reason} || '' for @m;
    return 0;
}

sub maint_cli {
    my ($cfg, $target, @rest) = @_;
    my $spec = shift @rest;
    die "Usage: mtmon --mute TARGET DURATION [REASON]   (e.g. mtmon --mute 10.0.0.12 2h replacing the switch)\n"
        unless defined $target && length $target && defined $spec;
    my ($from, $until) = maint_window($spec, time);
    my @hit = maint_targets($cfg, $target);
    die "'$target' matches nothing: use all, a [capsman]/[msm]/[cnpilot] name, an access point (identity, MAC, IP)\n"
      . "or a switch (IP or description); * and ? work as wildcards. See mtmon --show.\n" unless @hit;
    my $who = $ENV{SUDO_USER} || getpwuid($<) || 'console';
    my $m = maint_add($cfg, target => $target, from => $from, until => $until, reason => join(' ', @rest), by => "$who (console)");
    print "Maintenance window $m->{id}: no mails about " . (@hit > 6 ? scalar(@hit) . " targets" : join(', ', @hit)) . "\n"
        . "  " . ($from > time + 30 ? 'from ' . fmt_time($from) . ' ' : '') . "until " . fmt_time($until) . "\n"
        . "End it early: mtmon --unmute $m->{id}\n";
    return 0;
}

sub unmute_cli {
    my ($cfg, $what) = @_;
    die "Usage: mtmon --unmute ID|TARGET|all\n" unless defined $what && length $what;
    my @g = maint_end($cfg, lc $what eq 'all' && !grep({ lc $_->{target} eq 'all' } @{ maint_load($cfg)->{mutes} }) ? '*all*' : $what,
                      ($ENV{SUDO_USER} || getpwuid($<) || 'console') . ' (console)');
    print @g ? "Ended: " . join(', ', map { "$_->{id} ($_->{target})" } @g) . "\n" : "No maintenance window '$what'. See mtmon --mutes.\n";
    return @g ? 0 : 1;
}

# ==========================================================================
# Flapping: an access point / device that drops again and again. A drop is one missed
# check (before cap_miss_threshold / fail_threshold hide it), or for MikroTik a
# disconnect line about that access point in the CAPsMAN log (flap_log = yes).
# ==========================================================================

# new "disconnected / lost" lines of the CAPsMAN log about known access points -> {ap key => n}
sub fetch_caps_log {
    my ($cm) = @_;
    my @lines;
    if ($cm->{method} eq 'api') {
        my $api = RosAPI->new(%$cm);
        my ($re, $trap) = $api->cmd('/log/print', '=.proplist=time,topics,message');
        $api->close;
        die "/log/print: $trap\n" if defined $trap;
        @lines = map { [ $_->{time} // '', $_->{message} // '' ] } grep { ($_->{topics} // '') =~ /caps/ } @$re;
    } else {
        my ($rc, $out) = ssh_exec($cm, '/log print terse without-paging where topics~"caps"');
        my @l = grep { /\S/ } map { s/\r//gr } split /\n/, $out;
        die "SSH to $cm->{host} failed\n" if $rc == 255;
        if (my ($err) = grep { !/^\s*\d+\s/ && /\(line \d+ column \d+\)|not enough permissions|^failure:|^bad command name|^syntax error|^expected end of command/i } @l) {
            die "MikroTik rejected /log print: $err\n";
        }
        for (@l) { my $r = parse_terse($_); push @lines, [ $r->{time} // '', $r->{message} ] if defined $r->{message} }
    }
    return \@lines;
}

sub log_drops {
    my ($cs, $lines, $known) = @_;
    my $first = !defined $cs->{log_seen};
    my %old = map { $_ => 1 } split /,/, $cs->{log_seen} // '';
    my (%seen, %cnt);
    my @aps = map { [ $_, uc($known->{$_}{mac} // ''), $known->{$_}{identity} // '' ] } keys %$known;
    for my $l (@$lines) {
        my ($time, $msg) = @$l;
        my ($hms) = $time =~ /(\d\d:\d\d:\d\d)/;
        my $h = substr(md5_hex(encode('UTF-8', ($hms // $time) . "|$msg")), 0, 12);
        my $new = !$old{$h} && !$seen{$h};
        $seen{$h} = 1;
        next if $first || !$new;
        next unless $msg =~ /disconnect|connection lost|\blost\b|\bleft\b|timed? ?out|timeout|leaving|reconnect/i;
        next if $msg =~ /^\s*[0-9A-F]{2}(?::[0-9A-F]{2}){5}@/i;          # a Wi-Fi client (MAC@interface)
        my $um = uc $msg;
        for my $a (@aps) {
            my ($k, $mac, $id) = @$a;
            if (($mac && index($um, $mac) >= 0)
                || (length $id && $msg =~ /(?:^|[\s\[\("'])\Q$id\E(?:$|[\s@%\]\)"':,])/)) { $cnt{$k}++; last }
        }
    }
    $cs->{log_seen} = join ',', sort keys %seen;
    return \%cnt;
}

# drops of one access point / device: add, keep flap_window, start / end flapping.
# Returns 'start', 'end' or undef.
sub flap_track {
    my ($g, $e, $n, $now) = @_;
    return undef unless $g->{flap_count};
    my $win = $g->{flap_window} * 60;
    my @d = grep { $_ > $now - $win } @{ $e->{drops} || [] };
    push @d, ($now) x $n if $n;
    @d = @d[-50 .. -1] if @d > 50;
    if (@d) { $e->{drops} = \@d } else { delete $e->{drops} }
    if (!$e->{flap_since} && @d >= $g->{flap_count}) { $e->{flap_since} = $now; $e->{flap_n} = scalar @d; return 'start' }
    if ($e->{flap_since}) {
        $e->{flap_n} = scalar @d if @d > ($e->{flap_n} // 0);
        if (!@d) { delete @$e{qw(flap_since flap_n)}; return 'end' }
    }
    return undef;
}

# ==========================================================================
# Switches over SNMP ([switches] snmp = yes): uplinks (down, slower, errors), PoE budget,
# temperature, restarts; all ports for the statistics. One process per switch.
# ==========================================================================
my %ETH_TYPE;
BEGIN { %ETH_TYPE = map { $_ => 1 } (6, 62, 69, 117, 161) }

sub snmp_collect {
    my ($g, $list, $inv) = @_;
    my %res;
    my @q = @$list;
    my $par = $g->{ping_parallel} > 16 ? 16 : $g->{ping_parallel};
    while (@q) {
        last if $reload || !$running;
        my @b = splice(@q, 0, $par);
        my %fh;
        for my $s (@b) {
            my $pid = open(my $fh, '-|');
            if (!defined $pid) { $res{ $s->{host} } = { err => "cannot start: $!" }; next }
            if (!$pid) {
                $SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { POSIX::_exit(1) };
                my $r = eval { switch_snmp($s, $inv) } || { err => (($@ // '') =~ s/\s+$//r) || 'unknown error' };
                binmode STDOUT;
                print JSON::PP->new->utf8->encode($r);
                close STDOUT;
                POSIX::_exit(0);
            }
            $fh{ $s->{host} } = $fh;
        }
        for my $h (keys %fh) {
            my $fh = $fh{$h};
            binmode $fh;
            local $/;
            my $j = <$fh>;
            close $fh;
            $res{$h} = eval { JSON::PP->new->utf8->decode($j // '') } || { err => 'no answer from the SNMP process' };
        }
    }
    return \%res;
}

sub snmp_num { my $v = shift // ''; return $v =~ /\((-?\d+)\)/ ? $1 : $v =~ /(-?\d+(?:\.\d+)?)/ ? $1 : undef }

# one switch (runs in its own process)
sub switch_snmp {
    my ($s, $inv) = @_;
    my %a = (%$s, name => $s->{host});
    my $limit = ($s->{timeout} || 1) * ($s->{retries} + 1) * 2 + 10;
    my ($rc, $out, $err) = run_cmd($limit, 'snmpget', '-On', '-Oe', msm_auth(\%a), $s->{host},
                                   '1.3.6.1.2.1.1.3.0', '1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.5.0', '1.3.6.1.2.1.1.2.0');
    my %sys = map { $_->[0] => $_->[2] } msm_parse(split /\n/, $out);
    my $up = $sys{'1.3.6.1.2.1.1.3.0'};
    if (!defined $up || $up =~ /No Such/i) {
        my $msg = (grep { /\S/ } split /\n/, $err)[0] // ($rc ? "exit code $rc" : 'no sysUpTime');
        $msg =~ s/^Timeout: No Response from .*/no answer (timeout) - check community \/ SNMP access/;
        die "$msg\n";
    }
    my %r = (uptime => int((snmp_num($up) // 0) / 100), descr => msm_str($sys{'1.3.6.1.2.1.1.1.0'} // '') =~ s/\s+/ /gr,
             sysname => msm_str($sys{'1.3.6.1.2.1.1.5.0'} // ''), oid => ($sys{'1.3.6.1.2.1.1.2.0'} // '') =~ s/^\.//r);
    $r{descr} = substr($r{descr}, 0, 200);
    my $col = sub {
        my ($oid) = @_;
        my ($st, $lines) = msm_walk(\%a, $oid);
        return {} unless $st eq 'ok';
        my %v;
        for (msm_parse(@$lines)) { my ($o, $t, $v) = @$_; $v{$1} = $v if $o =~ /^\Q$oid\E\.(.+)$/ }
        return \%v;
    };
    my $name  = $col->('1.3.6.1.2.1.31.1.1.1.1');
    my $descr = $col->('1.3.6.1.2.1.2.2.1.2');
    my $type  = $col->('1.3.6.1.2.1.2.2.1.3');
    my $adm   = $col->('1.3.6.1.2.1.2.2.1.7');
    my $oper  = $col->('1.3.6.1.2.1.2.2.1.8');
    my $hs    = $col->('1.3.6.1.2.1.31.1.1.1.15');
    my $sp    = %$hs ? {} : $col->('1.3.6.1.2.1.2.2.1.5');
    my $ine   = $col->('1.3.6.1.2.1.2.2.1.14');
    my $oute  = $col->('1.3.6.1.2.1.2.2.1.20');
    my $alias = $col->('1.3.6.1.2.1.31.1.1.1.18');
    my @ports;
    my %idx = map { $_ => 1 } (keys %$name, keys %$descr);
    for my $i (sort { $a <=> $b } grep { /^\d+$/ } keys %idx) {
        my $speed = defined $hs->{$i} ? snmp_num($hs->{$i}) : defined $sp->{$i} ? int((snmp_num($sp->{$i}) // 0) / 1000000) : undef;
        $speed += 0 if defined $speed;
        push @ports, { i => $i + 0, name => msm_str($name->{$i} // $descr->{$i} // "if$i"), descr => msm_str($descr->{$i} // ''),
                       alias => msm_str($alias->{$i} // ''), type => snmp_num($type->{$i}) // 0,
                       admin => snmp_num($adm->{$i}) // 0, oper => snmp_num($oper->{$i}) // 0, speed => $speed,
                       ine => (snmp_num($ine->{$i}) // 0) + 0, oute => (snmp_num($oute->{$i}) // 0) + 0 };
        $ports[-1]{eth} = $ETH_TYPE{ $ports[-1]{type} } ? 1 : 0;
    }
    die "interface table (IF-MIB) not readable\n" unless @ports;
    $r{ports} = \@ports;
    # PoE (POWER-ETHERNET-MIB): budget of the PSE groups, ports delivering power
    my $pse = $col->('1.3.6.1.2.1.105.1.3.1.1');
    if (%$pse) {
        my ($pw, $used) = (0, 0);
        for my $k (keys %$pse) { my ($c) = split /\./, $k; $pw += snmp_num($pse->{$k}) // 0 if $c == 2; $used += snmp_num($pse->{$k}) // 0 if $c == 4 }
        # RFC 3621 says watts, but some switches (HP/Aruba and others) give milliwatts:
        # the budget (a few W .. a few kW) or the consumption (more than the budget) shows which
        $pw /= 1000 if $pw > 20000;
        $used /= 1000 if $used > 20000 || ($pw && $used > $pw * 1.5 && $used / 1000 <= $pw * 1.5);
        ($pw, $used) = map { 0 + sprintf('%.1f', $_) } $pw, $used;
        my $det = $col->('1.3.6.1.2.1.105.1.1.1.6');
        $r{poe} = { power => $pw, used => $used, ports_on => scalar(grep { (snmp_num($_) // 0) == 3 } values %$det),
                    ports => scalar(keys %$det) } if $pw;
    }
    # temperature: ENTITY-SENSOR-MIB (celsius sensors), MikroTik gauges
    my @temp;
    my $sen = $col->('1.3.6.1.2.1.99.1.1.1');
    if (%$sen) {
        my %e;
        for my $k (keys %$sen) { my ($c, $i) = split /\./, $k, 2; $e{$i}{$c} = snmp_num($sen->{$k}) }
        my @cels = grep { ($e{$_}{1} // 0) == 8 && defined $e{$_}{4} && ($e{$_}{5} // 1) == 1 } keys %e;
        my $nm = @cels ? $col->('1.3.6.1.2.1.47.1.1.1.1.7') : {};
        for my $i (@cels) {
            my $v = $e{$i}{4} * 10 ** ((($e{$i}{2} // 9) - 9) * 3) / 10 ** ($e{$i}{3} // 0);
            push @temp, [ msm_str($nm->{$i} // "sensor $i"), 0 + sprintf('%.1f', $v) ] if $v > -50 && $v < 200;
        }
    }
    if (!@temp && $r{oid} =~ /^1\.3\.6\.1\.4\.1\.14988\./) {
        my $gg = $col->('1.3.6.1.4.1.14988.1.1.3.100.1');
        my %e;
        for my $k (keys %$gg) { my ($c, $i) = split /\./, $k, 2; $e{$i}{$c} = $gg->{$k} }
        for my $i (grep { (snmp_num($e{$_}{4}) // 0) == 1 } keys %e) { push @temp, [ msm_str($e{$i}{2} // "gauge $i"), snmp_num($e{$i}{3}) + 0 ] }
        if (!@temp) {
            my ($rc2, $o2) = eval { run_cmd($limit, 'snmpget', '-On', '-Oqv', msm_auth(\%a), $s->{host}, '1.3.6.1.4.1.14988.1.1.3.10.0') };
            my $v = snmp_num($o2 // '');
            push @temp, [ 'temperature', $v / 10 ] if defined $rc2 && $rc2 == 0 && defined $v && $v > 0 && ($o2 // '') !~ /No Such/;
        }
    }
    $r{temp} = \@temp if @temp;
    # VLANs per port (Q-BRIDGE-MIB), once an hour: "1u,2t,5t" per ifIndex, PVID
    if ($s->{_vlan}) {
        my $v = eval { switch_vlans(\%a, $col) };
        $r{vlans} = $v if $v;
    }
    # interface traffic (for the statistics of the device report): 64-bit octet counters
    my $hin  = $col->('1.3.6.1.2.1.31.1.1.1.6');
    my $hout = %$hin ? $col->('1.3.6.1.2.1.31.1.1.1.10') : {};
    if (%$hin) {
        for my $p (@ports) {
            my ($i, $o) = (snmp_num($hin->{ $p->{i} } // ''), snmp_num($hout->{ $p->{i} } // ''));
            $p->{oct} = [ $i + 0, $o + 0 ] if defined $i && defined $o;
        }
    }
    # inventory (once per inventory_hours): ENTITY-MIB chassis, MikroTik serial / firmware
    if ($inv) {
        my %ent;
        for my $c (5, 8, 9, 10, 11, 13) { my $v = $col->("1.3.6.1.2.1.47.1.1.1.1.$c"); $ent{$_}{$c} = msm_str($v->{$_}) for keys %$v }
        my @ids = sort { $a <=> $b } grep { /^\d+$/ } keys %ent;
        my ($ch) = grep { ($ent{$_}{5} // '') =~ /^\s*3\s*$|\(3\)/ && (length($ent{$_}{11} // '') || length($ent{$_}{13} // '')) } @ids;
        ($ch) = grep { length($ent{$_}{11} // '') } @ids unless defined $ch;
        my %iv;
        if (defined $ch) { %iv = (model => $ent{$ch}{13}, serial => $ent{$ch}{11}, version => $ent{$ch}{10}, firmware => $ent{$ch}{9}, hardware => $ent{$ch}{8}) }
        if ($r{oid} =~ /^1\.3\.6\.1\.4\.1\.14988\./) {
            my ($rc3, $o3) = eval { run_cmd($limit, 'snmpget', '-On', '-Oe', msm_auth(\%a), $s->{host},
                                            '1.3.6.1.4.1.14988.1.1.7.3.0', '1.3.6.1.4.1.14988.1.1.7.4.0', '1.3.6.1.4.1.14988.1.1.4.4.0') };
            my %m = map { $_->[0] => msm_str($_->[2]) } grep { $_->[2] !~ /No Such/ } msm_parse(split /\n/, $o3 // '');
            $iv{serial}   ||= $m{'1.3.6.1.4.1.14988.1.1.7.3.0'};
            $iv{firmware} ||= $m{'1.3.6.1.4.1.14988.1.1.7.4.0'};
            $iv{version}  ||= $m{'1.3.6.1.4.1.14988.1.1.4.4.0'};
            ($iv{model}) = $r{descr} =~ /RouterOS\s+(\S+)/ if !$iv{model};
        }
        $iv{$_} = substr($iv{$_} =~ s/^\s+|\s+$//gr, 0, 80) for grep { defined $iv{$_} } keys %iv;
        delete $iv{$_} for grep { !length($iv{$_} // '') } keys %iv;
        $r{inv} = \%iv;
    }
    return \%r;
}

# VLAN membership per port from Q-BRIDGE-MIB: static (configured) VLANs, else the current ones.
# Port bitmaps are by bridge port (dot1dBasePortIfIndex -> ifIndex). Returns { ifIndex => "1u,2t,5-9t" }
# and the PVID per ifIndex, or undef when the switch does not have the MIB.
sub switch_vlans {
    my ($sa, $col) = @_;
    my $bp = $col->('1.3.6.1.2.1.17.1.4.1.2');
    return undef unless %$bp;
    my %bp2if = map { ($_ => snmp_num($bp->{$_})) } grep { /^\d+$/ } keys %$bp;
    my $hex = sub { local $sa->{_ox} = 1; $col->($_[0]) };
    my $bits = sub {                           # "FF 00 80" -> bridge port numbers (MSB of the first octet = port 1)
        my ($v) = @_;
        $v //= '';
        $v =~ s/^.*?:\s*//s if $v =~ /^[A-Za-z-]+:/;
        my @o = map { hex } grep { /^[0-9A-Fa-f]{2}$/ } split /\s+/, $v;
        my @p;
        for my $k (0 .. $#o) { for my $b (0 .. 7) { push @p, $k * 8 + $b + 1 if $o[$k] & (0x80 >> $b) } }
        return @p;
    };
    my $eg = $hex->('1.3.6.1.2.1.17.7.1.4.3.1.2');
    my $un = %$eg ? $hex->('1.3.6.1.2.1.17.7.1.4.3.1.4') : {};
    if (!%$eg) {                               # current table: index timemark.vlan
        my $ce = $hex->('1.3.6.1.2.1.17.7.1.4.2.1.4');
        my $cu = %$ce ? $hex->('1.3.6.1.2.1.17.7.1.4.2.1.5') : {};
        $eg = { map { ((split /\./)[-1] => $ce->{$_}) } keys %$ce };
        $un = { map { ((split /\./)[-1] => $cu->{$_}) } keys %$cu };
    }
    return undef unless %$eg;
    my %per;                                   # ifIndex -> vlan -> u / t
    for my $vl (keys %$eg) {
        next unless $vl =~ /^\d+$/;
        my %u = map { ($_ => 1) } $bits->($un->{$vl});
        for my $p ($bits->($eg->{$vl})) {
            my $if = $bp2if{$p} // next;
            $per{$if}{$vl} = $u{$p} ? 'u' : 't';
        }
    }
    my $pv = $col->('1.3.6.1.2.1.17.7.1.4.5.1.1');
    my %pvid = map { ($bp2if{$_} => snmp_num($pv->{$_}) + 0) } grep { defined $bp2if{$_} && defined snmp_num($pv->{$_}) } keys %$pv;
    my %str;
    for my $if (keys %per) {
        my @v = sort { $a <=> $b } keys %{ $per{$if} };
        my @out;
        while (@v) {                           # 5,6,7,8 tagged -> 5-8t
            my $v0 = shift @v;
            my $t = $per{$if}{$v0};
            my $v1 = $v0;
            while (@v && $v[0] == $v1 + 1 && $per{$if}{ $v[0] } eq $t) { $v1 = shift @v }
            push @out, ($v1 > $v0 + 1 ? "$v0-$v1" : $v1 == $v0 + 1 ? "$v0$t,$v1" : $v0) . $t;
        }
        $str{$if} = join(',', @out);
    }
    return { ports => \%str, pvid => \%pvid };
}

# uplink "49", "Gi1/0/49", "sfp-sfpplus1", ifIndex -> port
sub uplink_port {
    my ($ports, $tok) = @_;
    my $t = lc $tok;
    for my $p (@$ports) { return $p if lc($p->{name} // '') eq $t }
    for my $p (@$ports) { return $p if lc($p->{descr} // '') eq $t || lc($p->{alias} // '') eq $t }
    if ($tok =~ /^\d+$/) {
        my @eth = grep { $_->{eth} } @$ports;
        for my $f (qw(name descr)) {
            for my $p (@eth) { return $p if ($p->{$f} // '') =~ /(?:^|\D)0*\Q$tok\E$/ }
        }
        for my $p (@$ports) { return $p if $p->{i} == $tok }
    }
    return undef;
}

# SNMP result of one switch -> stored statistics, conditions, alerts; returns (\@new, \@fixed, $reboot_uptime)
sub switch_alerts {
    my ($g, $s, $st, $r, $now) = @_;
    my (%cond, @new, @fixed, $reboot);
    my $prev = $st->{snmp} || {};
    if ($r->{err}) {
        $cond{snmp} = "SNMP: $r->{err}";
        $st->{snmp} = { %$prev, err => $r->{err}, err_t => $now };
    } else {
        if (defined $prev->{uptime} && $prev->{t} && !$prev->{err}) {
            my $since = $now - $prev->{t};
            $reboot = $r->{uptime} if $r->{uptime} + 600 < $prev->{uptime} + $since && $r->{uptime} < $since + 600;
        }
        my $dt = $prev->{t} ? $now - $prev->{t} : 0;
        my %errs = %{ $prev->{_err} || {} };
        my %now_err;
        for my $p (@{ $r->{ports} }) {
            my $tot = ($p->{ine} // 0) + ($p->{oute} // 0);
            $now_err{ $p->{i} } = $tot;
            my $pe = $errs{ $p->{i} };
            $p->{errd} = (defined $pe && $dt > 0 && !$reboot) ? ($tot >= $pe ? $tot - $pe : 0) : undef;
        }
        my %upl;
        for my $u (@{ $s->{uplinks} || [] }) {
            my ($tok, $want) = @$u;
            my $p = uplink_port($r->{ports}, $tok);
            if (!$p) { $cond{"up:$tok:none"} = "uplink $tok: no such port on the switch"; next }
            $upl{ $p->{i} } = $tok;
            my $lbl = "uplink $tok" . (lc($p->{name}) ne lc($tok) ? " ($p->{name})" : '');
            next if $p->{admin} != 1;                                         # disabled on purpose
            if ($p->{oper} != 1) { $cond{"up:$tok:down"} = "$lbl is down"; next }
            my $max = $st->{speed_max}{$tok};
            $st->{speed_max}{$tok} = $p->{speed} + 0 if $p->{speed} && (!$max || $p->{speed} > $max);
            my $exp = $want // $max;
            $cond{"up:$tok:speed"} = "$lbl runs at " . fmt_speed($p->{speed}) . " instead of " . fmt_speed($exp)
                if $exp && $p->{speed} && $p->{speed} < $exp;
            if (defined $p->{errd} && $dt > 0 && $s->{error_rate}) {
                my $rate = $p->{errd} / ($dt / 60);
                $cond{"up:$tok:err"} = "$lbl: $p->{errd} errors in " . fmt_dur($dt) . sprintf(' (%.0f per minute)', $rate) if $rate >= $s->{error_rate};
            }
        }
        my $poe = $r->{poe};
        if ($poe && $poe->{power}) {
            $poe->{pct} = 0 + sprintf('%.0f', 100 * $poe->{used} / $poe->{power});
            $cond{poe} = "PoE budget $poe->{pct}% used ($poe->{used} of $poe->{power} W)" if $s->{poe_warn} && $poe->{pct} >= $s->{poe_warn};
        }
        my ($hot) = sort { $b->[1] <=> $a->[1] } @{ $r->{temp} || [] };
        $cond{temp} = "temperature $hot->[1] °C ($hot->[0])" if $hot && $s->{temp_warn} && $hot->[1] >= $s->{temp_warn};
        # compact port list for the dashboard: [ifIndex, name, alias, oper, admin, Mbit/s, errors since last check, uplink]
        # statistics for the device report: ports in use, PoE, temperature, uplink traffic (Mbit/s), errors
        my @eth = grep { $_->{eth} } @{ $r->{ports} };
        my %ds = (up => scalar(grep { $_->{oper} == 1 } @eth), n => scalar(@eth));
        $ds{poe}  = $poe->{used} + 0 if $poe && $poe->{power};
        $ds{poew} = $poe->{power} + 0 if $poe && $poe->{power};
        $ds{temp} = $hot->[1] + 0 if $hot;
        my %oct = map { ($_->{i} => $_->{oct}) } grep { $_->{oct} } @{ $r->{ports} };
        my $pod = $prev->{_oct} || {};
        my $err = 0; $err += $_->{errd} // 0 for @eth;
        $ds{err} = $err if $dt > 0;
        if ($dt > 0 && !$reboot) {
            for my $i (keys %upl) {
                my ($o, $n) = ($pod->{$i}, $oct{$i});
                next unless $o && $n;
                my ($p) = grep { $_->{i} == $i } @{ $r->{ports} };
                my ($rx, $tx) = ($n->[0] - $o->[0], $n->[1] - $o->[1]);
                next if $rx < 0 || $tx < 0;                                  # counter reset
                my $tok = $upl{$i};
                $ds{"rx:$tok"} = 0 + sprintf('%.2f', $rx * 8 / $dt / 1e6);
                $ds{"tx:$tok"} = 0 + sprintf('%.2f', $tx * 8 / $dt / 1e6);
                $ds{"sp:$tok"} = $p->{speed} + 0 if $p && $p->{speed};
            }
        }
        $st->{_ds} = \%ds;
        my $vl = $r->{vlans} || $prev->{vlans};
        my $vt = $r->{vlans} || $s->{_vlan} ? $now : $prev->{vlans_t};     # also when the switch has no Q-BRIDGE-MIB
        my @pl = map { [ $_->{i}, $_->{name}, $_->{alias}, $_->{oper} + 0, $_->{admin} + 0, $_->{speed}, $_->{errd}, $upl{ $_->{i} },
                         ($vl ? (($vl->{ports} || {})->{ $_->{i} } // '', ($vl->{pvid} || {})->{ $_->{i} }) : ()) ] }
                 grep { $_->{eth} || $upl{ $_->{i} } } @{ $r->{ports} };
        $st->{snmp} = { t => $now, uptime => $r->{uptime}, descr => $r->{descr}, sysname => $r->{sysname}, ports => \@pl,
                        ($vl ? (vlans => $vl) : ()), ($vt ? (vlans_t => $vt) : ()),
                        ($poe ? (poe => $poe) : ()), ($r->{temp} ? (temp => $r->{temp}) : ()), _err => \%now_err, (%oct ? (_oct => \%oct) : ()),
                        inv => ($r->{inv} || $prev->{inv}) };
        delete $st->{snmp}{inv} unless $st->{snmp}{inv};
    }
    my $al = $st->{alerts} ||= {};
    for my $k (sort keys %cond) {
        my $a = $al->{$k} ||= { since => $now, n => 0 };
        $a->{n}++;
        $a->{text} = $cond{$k};
        if (!$a->{sent} && $a->{n} >= $g->{fail_threshold}) { $a->{sent} = $now; push @new, { key => $k, text => $a->{text}, since => $a->{since} } }
    }
    for my $k (sort keys %$al) {
        next if $cond{$k};
        next if $cond{snmp} && $k ne 'snmp';            # without SNMP the other conditions are unknown: keep them
        my $a = delete $al->{$k};
        push @fixed, { key => $k, text => $a->{text}, since => $a->{since} } if $a->{sent};
    }
    delete $st->{alerts} unless %$al;
    return (\@new, \@fixed, $reboot);
}

# ==========================================================================
# 13.6: topology - what is behind what, found without any configuration:
#  - the neighbours a device sees (LLDP and CDP over SNMP from the switches, MNDP/LLDP/CDP of the
#    MikroTik controllers and access points from /ip neighbor),
#  - the MAC tables of the switches and MikroTik bridges (a device hangs on the port with the
#    fewest MACs behind it), the ARP tables for the MAC of an IP,
#  - the path of the packets (ping with a growing TTL, one per /24) for the routers in between.
# Every [general] topology_hours (6) in the background into topology.json; mtmon --topology
# finds it now and prints it. While a device is down, the devices behind it are not reported on
# their own: the mail of that device lists them, the phones get nothing for them.
# ==========================================================================
sub topo_file { data_file($_[0], 'topology.json') }
sub mac_norm { my $m = uc(shift // ''); $m =~ s/[^0-9A-F]//g; return length($m) == 12 ? join(':', $m =~ /(..)/g) : '' }
sub topo_host { my $h = shift // ''; $h =~ s/:\d+$//; return topo_ip4($h) ? $h : () }
sub topo_ip4 { defined $_[0] && $_[0] =~ /^\d{1,3}(?:\.\d{1,3}){3}$/ }

# a switch over SNMP: its addresses, neighbours (LLDP, CDP), MAC table and ARP table
sub topo_snmp {
    my ($s) = @_;
    my %a = (%$s, name => $s->{host});
    my $walk = sub {
        my ($oid) = @_;
        my ($st, $l) = msm_walk(\%a, $oid);
        return [] unless $st eq 'ok';
        return [ map { [ ($_->[0] =~ /^\Q$oid\E\.(.+)$/)[0] // '', $_->[1], $_->[2] ] } msm_parse(@$l) ];
    };
    my %r = (host => $s->{host}, nb => [], ips => [], macs => []);
    my ($rc, $out) = run_cmd(($s->{timeout} || 1) * ($s->{retries} + 1) * 2 + 10, 'snmpget', '-On', '-Oe', msm_auth(\%a), $s->{host}, '1.3.6.1.2.1.1.5.0');
    my ($sn) = map { $_->[2] } msm_parse(split /\n/, $out // '');
    die "no answer over SNMP\n" unless defined $sn && $sn !~ /No Such/i;
    $r{sysname} = msm_str($sn);
    my %ifn = map { ($_->[0] => msm_str($_->[2])) } @{ $walk->('1.3.6.1.2.1.31.1.1.1.1') };
    %ifn = map { ($_->[0] => msm_str($_->[2])) } @{ $walk->('1.3.6.1.2.1.2.2.1.2') } unless %ifn;
    $r{ips} = [ grep { topo_ip4($_) && !/^127\./ } map { $_->[0] } @{ $walk->('1.3.6.1.2.1.4.20.1.1') } ];
    for (@{ $walk->('1.0.8802.1.1.2.1.3.2') }) { my $m = mac_norm(msm_mac($_->[1], $_->[2])); push @{ $r{macs} }, $m if $m }
    my %lpd = map { ($_->[0] => msm_str($_->[2])) } @{ $walk->('1.0.8802.1.1.2.1.3.7.1.4') };
    my %lpi = map { ($_->[0] => msm_str($_->[2])) } @{ $walk->('1.0.8802.1.1.2.1.3.7.1.3') };
    my $lport = sub { my $p = shift; return $ifn{$p} // ($lpi{$p} && $lpi{$p} !~ /^[0-9A-F ]{17}$/i ? $lpi{$p} : undef) // $lpd{$p} // "port $p" };
    my %rem;
    for (@{ $walk->('1.0.8802.1.1.2.1.4.1.1') }) {
        my ($col, undef, $lp, $ri) = split /\./, $_->[0];
        next unless defined $ri;
        my $e = $rem{"$lp.$ri"} ||= { lp => $lp };
        if    ($col == 5) { $e->{mac} = mac_norm(msm_mac($_->[1], $_->[2])) }
        elsif ($col == 7) { $e->{rport} = msm_str($_->[2]); $e->{mac2} = mac_norm(msm_mac($_->[1], $_->[2])) }
        elsif ($col == 8) { $e->{rdesc} = msm_str($_->[2]) }
        elsif ($col == 9) { $e->{name} = msm_str($_->[2]) }
    }
    for (@{ $walk->('1.0.8802.1.1.2.1.4.2.1.3') }) {               # lldpRemManAddrIfSubtype: the address is in the index
        my @i = split /\./, $_->[0];
        next unless @i >= 9 && $i[3] == 1 && $i[4] == 4;
        push @{ ($rem{"$i[1].$i[2]"} ||= { lp => $i[1] })->{ips} }, join('.', @i[5 .. 8]);
    }
    # the port on the other side: its port id, unless that is only a MAC - then its description
    my $rp = sub { my $e = shift; my $id = $e->{rport} // ''; return length $id && !$e->{mac2} && $id !~ /^[0-9A-F]{2}([ :-]?[0-9A-F]{2}){5}$/i ? $id : ($e->{rdesc} // '') };
    push @{ $r{nb} }, { port => $lport->($_->{lp}), mac => $_->{mac} || $_->{mac2} || '', name => $_->{name} // '', ips => $_->{ips} || [], via => 'lldp', rport => $rp->($_) } for values %rem;
    my %cdp;
    for my $c ([ 4, 'ip' ], [ 6, 'name' ], [ 7, 'rport' ]) {
        for (@{ $walk->("1.3.6.1.4.1.9.9.23.1.2.1.1.$c->[0]") }) {
            my ($ifi, $di) = split /\./, $_->[0];
            my $e = $cdp{"$ifi.$di"} ||= { lp => $ifi };
            if ($c->[1] eq 'ip') { my @b = map { hex } grep { /^[0-9A-Fa-f]{2}$/ } split ' ', ($_->[2] =~ s/"//gr); $e->{ips} = [ join '.', @b ] if @b == 4 }
            else { $e->{name} = msm_str($_->[2]) }
        }
    }
    push @{ $r{nb} }, { port => $ifn{ $_->{lp} } // "if$_->{lp}", mac => '', name => $_->{name} // '', ips => $_->{ips} || [], via => 'cdp', rport => $_->{rport} // '' } for values %cdp;
    # the MAC table: Q-BRIDGE (per VLAN), else BRIDGE-MIB; bridge port -> ifIndex -> name
    my %bp = map { ($_->[0] => snmp_num($_->[2])) } @{ $walk->('1.3.6.1.2.1.17.1.4.1.2') };
    my $fq = $walk->('1.3.6.1.2.1.17.7.1.2.2.1.2');
    $fq = $walk->('1.3.6.1.2.1.17.4.3.1.2') unless @$fq;
    for (@$fq) {
        my @i = split /\./, $_->[0];
        next unless @i >= 6;
        my $b = snmp_num($_->[2]) or next;
        my $ifi = $bp{$b} // $b;
        $r{fdb}{ join ':', map { sprintf '%02X', $_ } @i[-6 .. -1] } = $ifn{$ifi} // "port $b";
    }
    for (@{ $walk->('1.3.6.1.2.1.4.22.1.2') }) {
        my @i = split /\./, $_->[0];
        next unless @i >= 5;
        my $m = mac_norm(msm_mac($_->[1], $_->[2])) or next;
        $r{arp}{ join '.', @i[-4 .. -1] } = $m;
    }
    return \%r;
}

# a RouterOS table as a list of hashes, over the API or SSH ($path like '/ip/neighbor')
sub ros_rows {
    my ($c, $path) = @_;
    if ($c->{method} eq 'api') {
        my $api = RosAPI->new(%$c);
        my ($re, $trap) = $api->cmd("$path/print");
        $api->close;
        die "$path: $trap\n" if defined $trap;
        return @$re;
    }
    (my $sp = $path) =~ s{/}{ }g;
    my ($rc, $out) = ssh_exec($c, "$sp print terse without-paging" =~ s/^ /\//r);
    die "SSH: exit code $rc\n" if $rc == 255;
    return grep { %$_ } map { parse_terse($_) } grep { /=/ } map { s/\r//gr } split /\n/, $out;
}

# a MikroTik controller: neighbours, addresses, ARP, bridge hosts (its MAC table)
sub topo_ros {
    my ($cm) = @_;
    my %r = (host => $cm->{host}, nb => [], ips => []);
    for (eval { ros_rows($cm, '/ip/neighbor') }) {
        push @{ $r{nb} }, { port => $_->{interface} // '', mac => mac_norm($_->{'mac-address'}), name => $_->{identity} // '',
                            ips => [ grep { topo_ip4($_) } $_->{address4}, $_->{address} ], via => 'mndp', rport => $_->{'interface-name'} // '' };
    }
    for (eval { ros_rows($cm, '/ip/address') }) { my ($ip) = ($_->{address} // '') =~ m{^([\d.]+)/}; push @{ $r{ips} }, $ip if topo_ip4($ip) }
    for (eval { ros_rows($cm, '/ip/arp') }) { my $m = mac_norm($_->{'mac-address'}); $r{arp}{ $_->{address} } = $m if $m && topo_ip4($_->{address}) }
    for (eval { ros_rows($cm, '/interface/bridge/host') }) {
        my $p = $_->{'on-interface'} // $_->{interface} // next;
        next if ros_true($_->{local}) || $p eq ($_->{bridge} // '');
        my $m = mac_norm($_->{'mac-address'}) or next;
        $r{fdb}{$m} = $p;
    }
    die "nothing readable\n" unless @{ $r{nb} } || @{ $r{ips} } || $r{fdb};
    return \%r;
}

# this server: its MACs, addresses, ARP table
sub topo_self {
    my %r = (macs => [], ips => [], arp => {});
    for my $f (glob '/sys/class/net/*/address') {
        open(my $fh, '<', $f) or next;
        my $m = mac_norm(scalar <$fh>);
        push @{ $r{macs} }, $m if $m && $m ne '00:00:00:00:00:00';
    }
    if (open(my $fh, '<', '/proc/net/arp')) {
        while (<$fh>) { $r{arp}{$1} = mac_norm($2) if /^(\d+\.\d+\.\d+\.\d+)\s+\S+\s+0x[2-9a-f]\S*\s+([0-9a-f:]{17})/i }
    }
    my ($rc, $out) = eval { run_cmd(10, 'ip', '-o', '-4', 'addr') };
    push @{ $r{ips} }, grep { !/^127\./ } ($out // '') =~ m{inet (\d+\.\d+\.\d+\.\d+)/}g;
    if (!@{ $r{ips} }) { ($rc, $out) = eval { run_cmd(10, 'hostname', '-I') }; push @{ $r{ips} }, grep { topo_ip4($_) && !/^127\./ } split ' ', $out // '' }
    return \%r;
}

# the routers on the way to an address: ping with TTL 1, 2, ... (the one that answers "TTL exceeded")
sub topo_trace {
    my ($ip, $max) = @_;
    my @h;
    for my $ttl (1 .. ($max || 12)) {
        my ($rc, $out) = run_cmd(4, 'ping', '-n', '-c', '1', '-W', '1', '-t', $ttl, $ip);
        $out //= '';
        if ($out =~ /From (\d+\.\d+\.\d+\.\d+)\S*\s.*(?:Time to live exceeded|TTL exceeded)/i) { push @h, $1; next }
        return [ @h ] if $rc == 0 || $out =~ /bytes from/;                       # there
        push @h, '*';
        last if @h >= 3 && !grep { $_ ne '*' } @h[-3 .. -1];                     # nobody answers any more
    }
    return undef;                                                                # not reached: no path
}

# routers in between from the TTL of one answer of each address -> { ip => hops }
sub topo_ttl {
    my ($ips, $par) = @_;
    my (%r, @q) = ();
    @q = @$ips;
    while (@q) {
        my %fh;
        for my $ip (splice(@q, 0, $par || 16)) { my $fh; $fh{$ip} = $fh if open($fh, '-|', 'ping', '-n', '-c', '1', '-W', '1', $ip) }
        for my $ip (keys %fh) {
            my $fh = $fh{$ip};
            local $/;
            my $out = <$fh> // '';
            close $fh;
            next unless $out =~ /ttl=(\d+)/i;
            my $t = $1;
            my ($init) = grep { $_ >= $t } 32, 64, 128, 255;
            $r{$ip} = $init - $t if defined $init;
        }
    }
    return \%r;
}

# run jobs in parallel processes -> { id => result }
sub topo_par {
    my ($jobs, $code, $par) = @_;
    my %res;
    my @q = @$jobs;
    while (@q) {
        my @b = splice(@q, 0, $par || 8);
        my %fh;
        for my $j (@b) {
            my $pid = open(my $fh, '-|');
            next unless defined $pid;
            if (!$pid) {
                $SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { POSIX::_exit(1) };
                my $r = eval { $code->($j->[1]) };
                binmode STDOUT;
                print JSON::PP->new->utf8->encode({ r => $r, err => ($r ? undef : (($@ // '') =~ s/\s+$//r)) });
                close STDOUT;
                POSIX::_exit(0);
            }
            $fh{ $j->[0] } = $fh;
        }
        for my $id (keys %fh) {
            my $fh = $fh{$id};
            binmode $fh;
            local $/;
            my $js = <$fh>;
            close $fh;
            my $x = eval { JSON::PP->new->utf8->decode($js // '') } || {};
            $res{$id} = $x->{r} if $x->{r};
            logmsg('debug', "Topology $id: $x->{err}") if $x->{err};
        }
    }
    return \%res;
}

# gather everything and work out who is behind whom -> topology.json
sub topo_run {
    my ($cfg) = @_;
    my $g = $cfg->{general};
    my $state = load_state($g->{state_file});
    my $par = $g->{ping_parallel} > 16 ? 16 : $g->{ping_parallel};
    my %col;
    $col{self} = topo_self();
    my @sj = map { [ $_->[0], $_->[2] ] } grep { $_->[2]{snmp} } @{ $cfg->{switches} };
    $col{snmp} = @sj ? topo_par(\@sj, \&topo_snmp, $par) : {};
    my @rj = map { [ $_->{name}, $_ ] } grep { $_->{method} eq 'api' || $_->{method} eq 'ssh' } @{ $cfg->{capsman} };
    $col{ros} = @rj ? topo_par(\@rj, \&topo_ros, $par) : {};
    $col{ap} = jread(ap_ports_file($g)) || {};
    # the path to every /24 that has a monitored address
    my %net;
    my @ips = ((map { $_->[0] } @{ $cfg->{switches} }), (map { topo_host($_->{host}) } @{ $cfg->{capsman} }),
               (map { map { $_->{ip} // () } values %{ $_->{caps} || {} } } values %{ $state->{capsman} || {} }));
    for my $ip (grep { topo_ip4($_) } @ips) { (my $n = $ip) =~ s/\.\d+$//; $net{$n} //= $ip }
    my %mine = map { (s/\.\d+$//r => 1) } @{ $col{self}{ips} };
    my @tj = map { [ $_, $net{$_} ] } grep { !$mine{$_} } sort keys %net;
    $col{trace} = @tj ? topo_par(\@tj, sub { topo_trace($_[0], 12) }, $par) : {};
    $col{trace}{$_} = [] for keys %mine;
    $col{ttl} = topo_ttl([ grep { topo_ip4($_) } @ips ], $par);
    my $t = topo_build($cfg, $state, \%col);
    jwrite(topo_file($g), $t);
    logmsg('info', 'Topology: ' . scalar(grep { $_->{parent} } values %{ $t->{nodes} }) . ' of ' . scalar(grep { $_->{kind} ne 'x' } values %{ $t->{nodes} })
                 . ' devices have a device in front of them (' . join(', ', map { "$_ $t->{src}{$_}" } sort keys %{ $t->{src} }) . ')');
    return $t;
}

sub topo_build {
    my ($cfg, $state, $col) = @_;
    my (%N, %byip, %bymac, %byname);
    my $add = sub {
        my ($k, %x) = @_;
        my $n = $N{$k} ||= { key => $k, kind => $x{kind}, name => $x{name}, ip => $x{ip}, ips => {}, macs => {}, names => {} };
        $n->{ips}{$_} = 1 for grep { topo_ip4($_) } $x{ip}, @{ $x{ips} || [] };
        $n->{macs}{$_} = 1 for grep { $_ } map { mac_norm($_) } @{ $x{macs} || [] };
        $n->{names}{ lc $_ } = 1 for grep { defined && length } @{ $x{names} || [] };
        return $n;
    };
    $add->('mtmon', kind => 'self', name => 'mtmon (' . hostname() . ')', ips => $col->{self}{ips}, macs => $col->{self}{macs});
    for my $s (@{ $cfg->{switches} }) {
        my ($h, $d) = @$s;
        my $sn = $col->{snmp}{$h} || {};
        $add->("dev:$h", kind => 'dev', name => $d, ip => $h, ips => $sn->{ips}, macs => $sn->{macs}, names => [ $d, $sn->{sysname} ]);
    }
    my %alias;                                     # a controller that is also monitored as a device (same address): one node
    for my $cm (@{ $cfg->{capsman} }) {
        my $h = topo_host($cm->{host});
        my $ro = $col->{ros}{ $cm->{name} } || {};
        my $cs = ($state->{capsman} || {})->{ $cm->{name} } || {};
        if (defined $h && $N{"dev:$h"}) { $alias{"ctl:$cm->{name}"} = "dev:$h"; $add->("dev:$h", ips => $ro->{ips}, names => [ $cm->{name}, $cs->{identity} ]) }
        else { $add->("ctl:$cm->{name}", kind => 'ctl', name => dev_heading($cm) // $cm->{name}, ip => $h, ips => $ro->{ips}, names => [ $cm->{name}, $cs->{identity} ]) }
        for my $k (keys %{ $cs->{caps} || {} }) {
            my $a = $cs->{caps}{$k};
            my $pe = ($col->{ap}{ $cm->{name} } || {})->{$k} || {};
            $add->("ap:$cm->{name}:$k", kind => 'ap', name => $a->{identity} || $a->{ip} || $a->{mac}, ip => $a->{ip}, ips => $pe->{ips},
                   macs => [ $a->{mac} ], names => [ $a->{identity}, $pe->{sysname} ]);
        }
    }
    # the MAC of each address, from every ARP table
    my %arp = (%{ $col->{self}{arp} || {} }, map { %{ $_->{arp} || {} } } values %{ $col->{snmp} }, values %{ $col->{ros} });
    for my $n (values %N) { $n->{macs}{ $arp{$_} } = 1 for grep { $arp{$_} } keys %{ $n->{ips} } }
    my (%dupip, %dupmac);
    for my $n (values %N) {
        for (keys %{ $n->{ips} })  { $dupip{$_}++  if $byip{$_}  && $byip{$_}  ne $n->{key}; $byip{$_}  = $n->{key} }
        for (keys %{ $n->{macs} }) { $dupmac{$_}++ if $bymac{$_} && $bymac{$_} ne $n->{key}; $bymac{$_} = $n->{key} }
        for (keys %{ $n->{names} }) { $byname{$_} //= $n->{key} }
    }
    delete $byip{$_} for keys %dupip;
    delete $bymac{$_} for keys %dupmac;
    my $resolve = sub {
        my ($nb) = @_;
        for (@{ $nb->{ips} || [] }) { return $byip{$_} if $byip{$_} }
        return $bymac{ $nb->{mac} } if $nb->{mac} && $bymac{ $nb->{mac} };
        return $byname{ lc $nb->{name} } if length($nb->{name} // '') && $byname{ lc $nb->{name} };
        my $id = ($nb->{ips} || [])->[0] // ($nb->{mac} || lc($nb->{name} // ''));
        return undef unless length $id;
        my $x = $add->("x:$id", kind => 'x', name => $nb->{name} || ($nb->{ips} || [])->[0] || $nb->{mac}, ips => $nb->{ips}, macs => [ $nb->{mac} ]);
        return $x->{key};
    };
    my (%E, %src, %lldp_port);
    my $edge = sub {
        my ($a, $b, $how, $port, $rport) = @_;
        return if !$b || $a eq $b;
        $E{$a}{$b} ||= { how => $how };
        $E{$a}{$b}{port} //= $port if length($port // '');
        $E{$b}{$a} ||= { how => $how };
        $E{$b}{$a}{port} //= $rport if length($rport // '');            # the neighbour's own port towards $a
        $src{$how}++;
    };
    my @tables;                                    # [node, { mac => port }]
    my $neigh = sub {
        my ($k, $r) = @_;
        for my $nb (@{ $r->{nb} || [] }) {
            my $o = $resolve->($nb) or next;
            $edge->($k, $o, $nb->{via}, $nb->{port}, $nb->{rport});
            $lldp_port{$k}{ $nb->{port} } = 1 if length($nb->{port} // '');
        }
        push @tables, [ $k, $r->{fdb} ] if $r->{fdb} && %{ $r->{fdb} };
    };
    $neigh->("dev:$_", $col->{snmp}{$_}) for keys %{ $col->{snmp} };
    $neigh->($alias{"ctl:$_"} // "ctl:$_", $col->{ros}{$_}) for keys %{ $col->{ros} };
    for my $c (keys %{ $col->{ap} }) { $neigh->("ap:$c:$_", $col->{ap}{$c}{$_}) for grep { $N{"ap:$c:$_"} } keys %{ $col->{ap}{$c} } }
    # MAC tables: a device hangs on the port with the fewest MACs behind it (an uplink has many)
    my %cnt;
    for my $t (@tables) { $cnt{ $t->[0] }{$_}++ for values %{ $t->[1] } }
    for my $n (values %N) {
        next if $n->{kind} eq 'x';
        my $best;
        for my $m (keys %{ $n->{macs} }) {
            for my $t (@tables) {
                next if $t->[0] eq $n->{key};
                my $p = $t->[1]{$m} // next;
                my $score = $cnt{ $t->[0] }{$p} + ($lldp_port{ $t->[0] }{$p} ? 10000 : 0);
                $best = [ $t->[0], $p, $score ] if !$best || $score < $best->[2];
            }
        }
        next unless $best && !$E{ $best->[0] }{ $n->{key} };
        # its own port towards that switch: where that switch's MAC is in its own MAC table (if it has one)
        my ($own) = grep { $_->[0] eq $n->{key} } @tables;
        my ($rp) = $own ? grep { defined } map { $own->[1]{$_} } keys %{ $N{ $best->[0] }{macs} } : ();
        $edge->($best->[0], $n->{key}, 'mac', $best->[1], $rp);
    }
    # the routers in between: the path to the /24 of each address
    my (%H, %hp);
    for my $n (values %N) {
        next if $n->{kind} eq 'x' || $n->{kind} eq 'self' || !topo_ip4($n->{ip});
        (my $net = $n->{ip}) =~ s/\.\d+$//;
        my $p = $col->{trace}{$net} or next;
        my @h;
        for (@$p) { last if $n->{ips}{$_}; push @h, $_ }               # the device itself is a router on the way
        $H{ $n->{key} } = \@h;
        $hp{ $n->{key} } = join ' ', @h;
    }
    # routers in between from the TTL of each device's answer (64 / 128 / 255 minus what came back)
    my %hops = map { ($_ => $col->{ttl}{ $N{$_}{ip} }) } grep { defined $N{$_}{ip} && defined(($col->{ttl} || {})->{ $N{$_}{ip} }) } keys %N;
    my %gw;                                                            # the router of a /24 we do not know by the address it answers from
    for my $k (keys %H) {
        my @h = @{ $H{$k} };
        next unless @h && !$byip{ $h[-1] };
        (my $net = $N{$k}{ip}) =~ s/\.\d+$//;
        next if exists $gw{$net};
        # the monitored device of that /24 one router closer than the others is that router (on its LAN address);
        # without TTLs: the one device of the /24 that is a router for mtmon by its address (.1 / .254)
        my @in = grep { ($N{$_}{ip} // '') =~ /^\Q$net\E\./ } keys %H;
        my @c = grep { defined $hops{$_} && $hops{$_} == @h - 1 } @in;
        @c = grep { $N{$_}{ip} =~ /\.(1|254)$/ } @in if !@c && !grep { defined $hops{$_} } @in;
        $gw{$net} = @c == 1 ? $c[0] : undef;
    }
    my %p3;                                                            # the last known router before it
    for my $k (keys %H) {
        my @h = @{ $H{$k} };
        (my $net = ($N{$k}{ip} // '')) =~ s/\.\d+$//;
        pop @h if @h && $gw{$net} && $gw{$net} eq $k;                  # the router itself: its own WAN side is not in front of it
        my $p = 'mtmon';
        for (@h) { my $m = $byip{$_}; $p = $m if $m && $m ne $k }
        $p = $gw{$net} if @h && !$byip{ $h[-1] } && $gw{$net} && $gw{$net} ne $k;
        $p3{$k} = $p;
    }
    # inside each router's part: who is behind whom along the neighbours and MAC tables
    my %par;
    my %grp;
    push @{ $grp{ $p3{$_} // 'mtmon' } }, $_ for grep { $N{$_}{kind} ne 'x' && $N{$_}{kind} ne 'self' } keys %N;
    # mtmon itself not found in any MAC table: its part starts at the router the other parts are reached through
    # (the first router on the paths), else at the device with the most neighbours
    my $start = sub {
        my ($r, $in) = @_;
        return $r if $r ne 'mtmon' || grep { $in->{$_} || ($N{$_}{kind} // '') eq 'x' } keys %{ $E{mtmon} || {} };
        my %first;
        $first{ $byip{ $_->[0] } }++ for grep { @$_ && $byip{ $_->[0] } } values %H;
        my ($f) = sort { $first{$b} <=> $first{$a} } grep { $in->{$_} } keys %first;
        return $f if $f;
        my ($d) = sort { scalar(keys %{ $E{$b} }) <=> scalar(keys %{ $E{$a} }) || $a cmp $b } grep { $E{$_} } keys %$in;
        return $d // $r;
    };
    for my $r (keys %grp) {
        my %in = map { ($_ => 1) } @{ $grp{$r} };
        my (%prev, @q) = ();
        my $r0 = $start->($r, \%in);
        my %seen = ($r0 => 1);
        @q = ($r0);
        while (@q) {
            my $u = shift @q;
            for my $v (sort keys %{ $E{$u} || {} }) {
                next if $seen{$v} || !($in{$v} || $N{$v}{kind} eq 'x');
                $seen{$v} = 1;
                $prev{$v} = $u;
                push @q, $v;
            }
        }
        for my $k (@{ $grp{$r} }) {
            next if $k eq $r || $k eq $r0;
            my $u = $prev{$k};
            my $how = $u ? $E{$u}{$k}{how} : 'route';
            my $cport = $u ? $E{$k}{$u}{port} : undef;                               # its own port towards it
            my $c = $k;
            while (defined $u && $N{$u}{kind} eq 'x' && $u ne $r0) { $c = $u; $u = $prev{$u} }   # through devices we do not monitor
            my $port = defined $u ? $E{$u}{$c}{port} : undef;                        # the port of the device in front of it
            $u //= $r0 ne $r && !$prev{$k} ? $r : $r0;
            $u = undef if $u eq 'mtmon';
            $par{$k} = { parent => $u, how => $how, port => $port, cport => $cport } if defined $u;
        }
    }
    # what hangs on each port of a device: the neighbours it sees there, the devices found in its MAC table
    # there, and how many MACs are behind the port in all (a device without LLDP/CDP shows up this way too)
    # 13.6.2, per port: d = connected to it (a neighbour it sees over LLDP/CDP/MNDP, or found on it in
    # the MAC table), with that device's own port; b = what is further behind them; m = MACs on the port
    my %links;
    for my $a (keys %E) {
        for my $b (keys %{ $E{$a} }) {
            my $p = $E{$a}{$b}{port};
            next unless length($p // '') && ($N{$b}{kind} // '') ne 'self';
            my $nm = $N{$b}{name} // $b;
            my $l = $links{$a}{$p} ||= {};
            next if grep { $_->{n} eq $nm } @{ $l->{d} || [] };
            my $rp = $E{$b}{$a}{port};
            push @{ $l->{d} }, { n => $nm, how => $E{$a}{$b}{how}, (length($rp // '') ? (r => $rp) : ()), ($N{$b}{kind} eq 'x' ? (x => 1) : ()) };
        }
    }
    my %kids;
    push @{ $kids{ $par{$_}{parent} } }, $_ for grep { defined $par{$_}{parent} } keys %par;
    for my $k (keys %par) {
        my ($u, $p) = @{ $par{$k} }{qw(parent port)};
        next unless defined $u && length($p // '');
        my $l = $links{$u}{$p} ||= {};
        my %direct = map { ($_->{n} => 1) } @{ $l->{d} || [] };
        my @q = ($k);
        my %seen;
        while (defined(my $x = shift @q)) {
            next if $seen{$x}++;
            my $nm = $N{$x}{name} // $x;
            push @{ $l->{b} }, $nm unless $direct{$nm} || grep { $_ eq $nm } @{ $l->{b} || [] };
            push @q, @{ $kids{$x} || [] };
        }
    }
    for my $l (map { values %$_ } values %links) {
        # a neighbour seen over LLDP/CDP/MNDP first, then the ones from the MAC table
        $l->{d} = [ sort { ($a->{how} eq 'mac') <=> ($b->{how} eq 'mac') || lc $a->{n} cmp lc $b->{n} } @{ $l->{d} } ] if $l->{d};
        $l->{b} = [ sort { lc $a cmp lc $b } @{ $l->{b} } ] if $l->{b};
    }
    for my $t (@tables) { $links{ $t->[0] }{$_}{m} = $cnt{ $t->[0] }{$_} for keys %{ $cnt{ $t->[0] } } }
    my %out;
    for my $k (keys %N) {
        my $n = $N{$k};
        next if $n->{kind} eq 'x' || $n->{kind} eq 'self';
        $out{$k} = { name => $n->{name}, kind => $n->{kind}, ip => $n->{ip}, %{ $par{$k} || {} }, ($links{$k} ? (links => $links{$k}) : ()) };
        delete $out{$k}{parent} unless defined $out{$k}{parent};
    }
    for my $c (keys %alias) {                       # the controller is that device: what is in front of the device is in front of it
        my $d = $out{ $alias{$c} } or next;
        my ($nm) = map { dev_heading($_) // $_->{name} } grep { "ctl:$_->{name}" eq $c } @{ $cfg->{capsman} };
        $out{$c} = { name => $nm // $c, kind => 'ctl', ip => $d->{ip}, same => $alias{$c}, map { defined $d->{$_} ? ($_ => $d->{$_}) : () } qw(parent how port) };
    }
    # no loops (a wrong neighbour could make one): cut where a chain comes back to itself
    for my $k (keys %out) {
        my (%seen, $u) = ();
        $u = $k;
        while (defined $u && $out{$u}) {
            if ($seen{$u}++) { delete $out{$u}{parent}; last }
            $u = $out{$u}{parent};
        }
    }
    return { t => time + 0, nodes => \%out, src => \%src };
}

# start a background search when it is due (never twice at a time)
sub topo_maybe {
    my ($cfg, $now) = @_;
    my $g = $cfg->{general};
    my $h = $g->{topology_hours} or return;
    my $f = topo_file($g);
    my $t = (stat $f)[9] // 0;
    my $run = data_file($g, 'topology.run');
    my $rt = (stat $run)[9] // 0;
    return if $now - $t < $h * 3600 || $now - $rt < 3600;
    if (open my $fh, '>', $run) { close $fh }
    my $pid = fork;
    return unless defined $pid;
    if ($pid) { waitpid($pid, 0); return }
    POSIX::setsid();
    my $pid2 = fork;
    POSIX::_exit(0) if !defined $pid2 || $pid2;
    $SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { POSIX::_exit(1) };
    eval { topo_run($cfg); 1 } or logmsg('warn', "Topology: $@");
    unlink $run;
    POSIX::_exit(0);
}

sub topo_load {
    my ($g) = @_;
    return undef unless $g->{topology_hours};
    my $t = jread(topo_file($g)) or return undef;
    return $t->{nodes} && %{ $t->{nodes} } ? $t : undef;
}

# the device in front of $key that is down now (the one closest to mtmon) -> its name, or undef
sub dep_behind {
    my ($g, $key) = @_;
    my $T = $g->{_T} or return undef;
    my $down = $g->{_down} || {};
    my ($hit, %seen);
    my $k = ($T->{nodes}{$key} || {})->{parent};
    while (defined $k && !$seen{$k}++) {
        $hit = $k if $down->{$k};
        $k = ($T->{nodes}{$k} || {})->{parent};
    }
    return undef unless $hit;
    my $n = $T->{nodes}{$hit};
    return $n->{name} . (length($n->{ip} // '') && $n->{name} ne $n->{ip} ? " ($n->{ip})" : '');
}

# everything now unreachable behind a device that is down (state) -> [{ behind, kind, name, ip }]
sub dep_all {
    my ($cfg, $state) = @_;
    my @l;
    for my $cm (@{ $cfg->{capsman} }) {
        my $cs = ($state->{capsman} || {})->{ $cm->{name} } or next;
        push @l, { behind => $cs->{behind}, kind => $cm->{label} // 'controller', name => dev_heading($cm) // $cm->{name}, ip => $cm->{host} }
            if ($cs->{down_hidden} // '') eq 'dep' && $cs->{behind};
        push @l, map { +{ behind => $_->{behind}, kind => 'access point', name => $_->{identity} || $_->{ip} || $_->{mac}, ip => $_->{ip} } }
                 grep { ($_->{hidden} // '') eq 'dep' && $_->{behind} && $_->{missing_since} } values %{ $cs->{caps} || {} };
    }
    for my $h (keys %{ $state->{switches} || {} }) {
        my $st = $state->{switches}{$h};
        push @l, { behind => $st->{behind}, kind => 'device', name => $st->{desc} // $h, ip => $h } if ($st->{hidden} // '') eq 'dep' && $st->{behind} && $st->{down_since};
    }
    return @l;
}

# mtmon --topology: find it now and print it as a tree
sub topo_cli {
    my ($cfg) = @_;
    print "Looking for the topology (neighbours, MAC tables, paths) - this takes a minute ...\n";
    my $t = topo_run($cfg);
    my $N = $t->{nodes};
    my %kids;
    push @{ $kids{ $N->{$_}{parent} // '' } }, $_ for keys %$N;
    my %kind = (dev => 'device', ctl => 'controller', ap => 'access point');
    my $pr;
    $pr = sub {
        my ($k, $d) = @_;
        for my $c (sort { lc($N->{$a}{name} // '') cmp lc($N->{$b}{name} // '') } @{ $kids{$k} || [] }) {
            my $n = $N->{$c};
            printf "%s%s%s  [%s%s]\n", '    ' x $d, $n->{name} // $c, (length($n->{ip} // '') && $n->{ip} ne ($n->{name} // '') ? " ($n->{ip})" : ''),
                   $kind{ $n->{kind} } // $n->{kind}, ($n->{parent} ? ", " . { lldp => 'LLDP', cdp => 'CDP', mndp => 'neighbour', mac => 'MAC table', route => 'route' }->{ $n->{how} // '' } // ($n->{how} // '')
                   . (length($n->{port} // '') ? " port $n->{port}" : '')
                   . (length($n->{cport} // '') ? " -> its $n->{cport}" : '') : '');
            $pr->($c, $d + 1);
        }
    };
    print "\nmtmon (" . hostname() . ")\n";
    $pr->('', 1);
    print "\nFound from: " . (join(', ', map { "$_ $t->{src}{$_}" } sort keys %{ $t->{src} || {} }) || 'nothing') . "\n"
        . "A device at the first level has nothing monitored in front of it (or it was not found).\n"
        . "LLDP or CDP on the switches (and SNMP in mtmon for them) gives the best picture.\n";
    return 0;
}

# ==========================================================================
# 13.4: ports and VLANs of the access points, shown like the ports of a switch.
# MikroTik: every AP is asked on its own address - over SSH with the user and key of its
# [capsman] section (or ap_user / ap_key / ap_port), with the RouterOS API for method = api,
# and over SNMP (ap_community) when that does not work (ports, but no VLANs: RouterOS does not
# give them over SNMP). VLANs from bridge VLAN filtering, VLAN interfaces and the VLAN of each
# wireless / wifi interface (vlan-id, datapath.vlan-id). cnPilot: SNMP with its section's settings.
# Every [general] ap_ports_minutes (15), in parallel, into ap-ports.json.
# ==========================================================================
sub ap_ports_file { data_file($_[0], 'ap-ports.json') }
sub ros_true { ($_[0] // '') =~ /^(true|yes)$/i }
sub ros_list { grep { length } split /\s*[,;]\s*/, ($_[0] // '') }
sub ros_vids {
    my @v;
    for (ros_list($_[0])) { if (/^(\d+)-(\d+)$/ && $2 >= $1 && $2 - $1 < 4096) { push @v, $1 .. $2 } elsif (/^\d+$/) { push @v, $_ + 0 } }
    return @v;
}
sub ros_rate { my ($r) = @_; return undef unless defined $r && $r =~ /([\d.]+)\s*([GM])/i; return int($1 * (uc $2 eq 'G' ? 1000 : 1) + .5) }

# { vid => 'u' | 't' } -> "1u,10t,20-23t"
sub vlan_compact {
    my ($m) = @_;
    my @v = sort { $a <=> $b } keys %$m;
    my @out;
    while (@v) {
        my $v0 = shift @v;
        my $t = $m->{$v0};
        my $v1 = $v0;
        while (@v && $v[0] == $v1 + 1 && $m->{ $v[0] } eq $t) { $v1 = shift @v }
        push @out, ($v1 > $v0 + 1 ? "$v0-$v1" : $v1 == $v0 + 1 ? "$v0$t,$v1" : $v0) . $t;
    }
    return join ',', @out;
}

# the RouterOS script for SSH: every part in :parse, so a command the version does not have
# (wifi on RouterOS 6, wireless on newer ones) only skips that part
sub ap_ssh_script {
    my @p = (
        [ IF   => '/interface print terse without-paging' ],
        [ VLAN => '/interface vlan print terse without-paging' ],
        [ BR   => '/interface bridge print terse without-paging' ],
        [ BP   => '/interface bridge port print terse without-paging' ],
        [ BV   => '/interface bridge vlan print terse without-paging' ],
        [ WL   => '/interface wireless print terse without-paging' ],
        [ WF   => '/interface wifi print terse without-paging' ],
        [ NB   => '/ip neighbor print terse without-paging' ],
        [ AD   => '/ip address print terse without-paging' ],
    );
    my $s = join '; ', map { qq{:put "\@\@$_->[0]"; :do {:local f [:parse "$_->[1]"]; \$f} on-error={}} } @p;
    my $eth = ':foreach i in=[/interface ethernet find] do={:do {:local m [/interface ethernet monitor \$i once as-value]; '
            . ':put (\"@E|\" . [/interface ethernet get \$i name] . \"|\" . (\$m->\"status\") . \"|\" . (\$m->\"rate\"))} on-error={}}';
    $s .= qq{; :do {:local f [:parse "$eth"]; \$f} on-error={}};
    $s .= '; :put ("@S|" . [/system identity get name] . "|" . [/system resource get version] . "|" . [/system resource get board-name] . "|" . [/system resource get uptime])';
    return $s;
}

sub ap_raw_ssh {
    my ($c) = @_;
    my ($rc, $out) = ssh_exec($c, ap_ssh_script());
    my @lines = map { s/\r//gr } split /\n/, $out;
    if ($rc == 255) {
        my @e = grep { /\S/ && !/^\*\*|WARNING|store now, decrypt later|upgraded/i } @lines;
        die(($e[0] // "exit code $rc") . "\n");
    }
    if (my ($e) = grep { /not enough permissions|^failure:|bad command name|syntax error/i } @lines) { die "$e\n" }
    my (%raw, $sec);
    my %key = (IF => 'if', VLAN => 'vlan', BR => 'br', BP => 'bp', BV => 'bv', WL => 'wl', WF => 'wf', NB => 'nb', AD => 'ad');
    for my $l (@lines) {
        if ($l =~ /^\@\@(\w+)\s*$/) { $sec = $key{$1}; $raw{$sec} ||= [] if $sec; next }
        if ($l =~ /^\@E\|([^|]*)\|([^|]*)\|(.*)$/) { $raw{eth}{$1} = { status => $2, rate => $3 }; next }
        if ($l =~ /^\@S\|([^|]*)\|([^|]*)\|([^|]*)\|(.*)$/) { $raw{sys} = { identity => RosAPI::_dec($1), version => $2, board => $3, uptime => $4 }; next }
        next unless $sec && $l =~ /=/;
        my $r = parse_terse($l);
        next unless %$r;
        my ($fl) = $l =~ /^\s*\d+\s+([A-Z]+)\s+[\w.-]+=/;
        $fl //= '';
        $r->{running}  //= $fl =~ /R/ ? 'true' : 'false';
        $r->{disabled} //= $fl =~ /X/ ? 'true' : 'false';
        $r->{dynamic}  //= $fl =~ /D/ ? 'true' : 'false';
        push @{ $raw{$sec} }, $r;
    }
    die "no answer to /interface print\n" unless @{ $raw{if} || [] };
    return \%raw;
}

sub ap_raw_api {
    my ($c) = @_;
    my $api = RosAPI->new(%$c);
    my %raw;
    for my $q ([ if => '/interface/print' ], [ vlan => '/interface/vlan/print' ], [ br => '/interface/bridge/print' ], [ bp => '/interface/bridge/port/print' ],
               [ bv => '/interface/bridge/vlan/print' ], [ wl => '/interface/wireless/print' ], [ wf => '/interface/wifi/print' ],
               [ nb => '/ip/neighbor/print' ], [ ad => '/ip/address/print' ]) {
        my ($re, $trap) = eval { $api->cmd($q->[1]) };
        $raw{ $q->[0] } = (!defined $trap && $re) ? $re : [];
    }
    die "no answer to /interface/print\n" unless @{ $raw{if} };
    my @eth = map { $_->{name} } grep { ($_->{type} // '') eq 'ether' } @{ $raw{if} };
    if (@eth) {
        my ($re, $trap) = eval { $api->cmd('/interface/ethernet/monitor', '=numbers=' . join(',', @eth), '=once=') };
        $raw{eth} = { map { ($_->{name} => { status => $_->{status}, rate => $_->{rate} }) } grep { defined $_->{name} } @{ $re || [] } } unless $trap;
    }
    my ($id) = eval { $api->cmd('/system/identity/print') };
    my ($rs) = eval { $api->cmd('/system/resource/print') };
    my $r = ($rs || [])->[0] || {};
    $raw{sys} = { identity => (($id || [])->[0] || {})->{name}, version => $r->{version}, board => $r->{'board-name'}, uptime => $r->{uptime} };
    eval { $api->close };
    return \%raw;
}

# the ports (ethernet and wireless) with their VLANs, as the compact list of a switch:
# [index, name, comment or SSID, oper (1 up), admin (1 enabled), Mbit/s, errors, uplink, "VLANs", PVID]
sub ap_ports_build {
    my ($raw) = @_;
    my %br = map { ($_->{name} => $_) } grep { defined $_->{name} } @{ $raw->{br} || [] };
    my (%vl, %pvid, %ports_of, %ssid);
    my %type = map { ($_->{name} => $_->{type} // '') } grep { defined $_->{name} } @{ $raw->{if} || [] };
    my @bp = grep { !ros_true($_->{disabled}) && defined $_->{interface} } @{ $raw->{bp} || [] };
    push @{ $ports_of{ $_->{bridge} // '' } }, $_->{interface} for @bp;
    for my $v (grep { !ros_true($_->{disabled}) } @{ $raw->{bv} || [] }) {            # bridge VLAN filtering
        my $b = $br{ $v->{bridge} // '' } or next;
        next unless ros_true($b->{'vlan-filtering'});
        my @t = ros_list(length($v->{'current-tagged'} // '') ? $v->{'current-tagged'} : $v->{tagged});
        my @u = ros_list(length($v->{'current-untagged'} // '') ? $v->{'current-untagged'} : $v->{untagged});
        for my $id (ros_vids($v->{'vlan-ids'})) { $vl{$_}{$id} = 't' for @t; $vl{$_}{$id} = 'u' for @u }
    }
    for my $p (@bp) {
        my $b = $br{ $p->{bridge} // '' } or next;
        next unless ros_true($b->{'vlan-filtering'}) && ($p->{pvid} // '') =~ /^\d+$/ && ($p->{'frame-types'} // '') !~ /only-vlan-tagged/;
        $pvid{ $p->{interface} } = $p->{pvid} + 0;
        $vl{ $p->{interface} }{ $p->{pvid} } //= 'u';
    }
    for my $v (grep { !ros_true($_->{disabled}) } @{ $raw->{vlan} || [] }) {          # VLAN interfaces
        my ($id, $par) = ($v->{'vlan-id'}, $v->{interface});
        next unless defined $id && $id =~ /^\d+$/ && defined $par;
        if ($br{$par}) {
            next if ros_true($br{$par}{'vlan-filtering'});                             # already in the bridge VLAN table
            # a bridge without filtering passes it on every port (tagged: shown on the ethernet ones)
            $vl{$_}{$id} //= 't' for grep { ($type{$_} // 'ether') eq 'ether' } @{ $ports_of{$par} || [] };
        } else {
            $vl{$par}{$id} //= 't';
        }
    }
    for my $w (@{ $raw->{wl} || [] }, @{ $raw->{wf} || [] }) {                          # the VLAN of the clients of an SSID
        my $n = $w->{name} // next;
        my $id = $w->{'datapath.vlan-id'} // ((($w->{'vlan-mode'} // '') eq 'use-tag') ? $w->{'vlan-id'} : undef);
        $vl{$n}{$id} = 'u' if defined $id && $id =~ /^\d+$/ && $id > 0;
        my $s = $w->{'configuration.ssid'} // $w->{ssid};
        $ssid{$n} = $s if defined $s && length $s;
    }
    my $eth = $raw->{eth} || {};
    my @if = grep { ($_->{type} // '') =~ /^(ether|wlan|wifi|wifiwave2)$/ && defined $_->{name} } @{ $raw->{if} || [] };
    my $nat = sub { my $x = lc shift; $x =~ s/(\d+)/sprintf('%08d', $1)/ge; $x };
    @if = sort { ($a->{type} ne 'ether') <=> ($b->{type} ne 'ether') || $nat->($a->{name}) cmp $nat->($b->{name}) } @if;
    my ($i, @pl) = (0);
    for my $f (@if) {
        my $n = $f->{name};
        my $e = $eth->{$n};
        my $up = $e ? (($e->{status} // '') eq 'link-ok' ? 1 : 2) : (ros_true($f->{running}) ? 1 : 2);
        my $vs = $vl{$n} ? vlan_compact($vl{$n}) : '';
        push @pl, [ ++$i, $n, ($f->{comment} // '') ne '' ? $f->{comment} : ($ssid{$n} // ''), $up, (ros_true($f->{disabled}) ? 2 : 1),
                    ($e ? ros_rate($e->{rate}) : undef), undef, undef, $vs, $pvid{$n} ];
    }
    die "no ethernet or wireless interface found\n" unless @pl;
    my $s = $raw->{sys} || {};
    return { ports => \@pl, sysname => $s->{identity}, descr => join(' ', grep { length } 'RouterOS', $s->{version} // '', $s->{board} // ''),
             uptime => (defined $s->{uptime} ? ros_seconds($s->{uptime}) : undef),
             # 13.6: its neighbours and addresses, for the topology
             nb => [ map { +{ port => $_->{interface} // '', mac => mac_norm($_->{'mac-address'}), name => $_->{identity} // '',
                              ips => [ grep { defined && /^\d{1,3}(?:\.\d{1,3}){3}$/ } $_->{address4}, $_->{address} ], via => 'mndp', rport => $_->{'interface-name'} // '' } } @{ $raw->{nb} || [] } ],
             ips => [ grep { defined } map { (($_->{address} // '') =~ m{^(\d{1,3}(?:\.\d{1,3}){3})/})[0] } @{ $raw->{ad} || [] } ] };
}

# SNMP (cnPilot, or a MikroTik that cannot be reached otherwise): IF-MIB, VLANs where the AP has Q-BRIDGE-MIB
sub ap_ports_snmp {
    my ($s) = @_;
    my $r = switch_snmp({ %$s, _vlan => 1 }, 0);
    my $vl = $r->{vlans} || {};
    my $i = 0;
    my @pl = map { [ $_->{i}, $_->{name}, $_->{alias}, $_->{oper} + 0, $_->{admin} + 0, $_->{speed}, undef, undef,
                     ($vl->{ports} || {})->{ $_->{i} } // '', ($vl->{pvid} || {})->{ $_->{i} } ] }
             grep { $_->{eth} || $_->{type} == 71 } @{ $r->{ports} || [] };
    die "no ethernet or wireless interface in IF-MIB\n" unless @pl;
    return { ports => \@pl, sysname => $r->{sysname}, descr => $r->{descr}, uptime => $r->{uptime} };
}

# one access point (runs in its own process)
sub ap_ports_one {
    my ($cfg, $cm, $a) = @_;
    if ($cm->{method} eq 'cnpilot') {
        return +{ %{ ap_ports_snmp({ %$cm, host => $a->{ip}, name => $a->{ip} }) }, src => 'snmp' };
    }
    my (@err, $r);
    my $to = $cm->{timeout} > 8 ? 8 : $cm->{timeout};
    my %c = (%$cm, host => $a->{ip}, port => $cm->{ap_port} || ($cm->{method} eq 'api' && !$cm->{ap_key} ? ($cm->{ssl} ? 8729 : 8728) : 22),
             user => $cm->{ap_user} || $cm->{user}, timeout => $to, name => "$cm->{name} AP " . ($a->{identity} || $a->{ip}));
    if ($cm->{method} eq 'api' && !$cm->{ap_key}) {
        $c{password} = $cm->{ap_password} // $cm->{password};
        $r = eval { +{ %{ ap_ports_build(ap_raw_api(\%c)) }, src => 'api' } } or push @err, 'API: ' . ($@ =~ s/\s+$//r);
    } else {
        $c{key} = $cm->{ap_key} || $cm->{key};
        $c{extra_options} ||= [];
        $r = eval { +{ %{ ap_ports_build(ap_raw_ssh(\%c)) }, src => 'ssh' } } or push @err, 'SSH: ' . ($@ =~ s/\s+$//r);
    }
    return $r if $r;
    my $sn = $cfg->{snmp} || {};
    my %s = (host => $a->{ip}, name => $a->{ip}, snmp_version => $sn->{version} // '2c', community => $cm->{ap_community} // $sn->{community} // 'public',
             user => $sn->{user} // '', auth_proto => $sn->{auth_proto} // 'SHA', auth_pass => $sn->{auth_pass} // '',
             priv_proto => $sn->{priv_proto} // 'AES', priv_pass => $sn->{priv_pass} // '', timeout => 2, retries => 1);
    $s{snmp_version} = '2c' if $cm->{ap_community};
    $r = eval { +{ %{ ap_ports_snmp(\%s) }, src => 'snmp' } } or push @err, 'SNMP: ' . ($@ =~ s/\s+$//r);
    return $r if $r;
    die join('; ', @err) . "\n";
}

sub ap_ports_on { my $v = $_[0]{ap_ports} // 'yes'; return $v !~ /^(0|no|ne|false|off)$/i }

# every ap_ports_minutes (failing ones every 6 hours after 3 tries); $only: one AP (--ap-ports)
sub ap_ports_collect {
    my ($cfg, $state, $now, $force, $only) = @_;
    my $g = $cfg->{general};
    return {} unless $g->{ap_ports_minutes} || $force;
    my $f = ap_ports_file($g);
    my $db = jread($f) || {};
    my (@jobs, %have);
    for my $cm (@{ $cfg->{capsman} }) {
        next if $cm->{method} eq 'msm' || !ap_ports_on($cm);
        my $caps = (($state->{capsman} || {})->{ $cm->{name} } || {})->{caps} || {};
        for my $k (keys %$caps) {
            my $a = $caps->{$k};
            $have{ $cm->{name} }{$k} = 1;
            next if $a->{missing_since} || !$a->{ip};
            next if defined $only && $only ne $a->{ip} && lc($only) ne lc($a->{identity} // '') && uc($only) ne uc($a->{mac} // '');
            my $e = ($db->{ $cm->{name} } || {})->{$k} || {};
            my $wait = ($e->{fails} // 0) >= 3 ? 6 * 3600 : ($g->{ap_ports_minutes} || 15) * 60;
            next if !$force && $e->{try} && $now - $e->{try} < $wait - 30 && $now >= $e->{try};
            push @jobs, [ $cm, $k, $a ];
        }
    }
    my %res;
    my $par = $g->{ping_parallel} > 16 ? 16 : $g->{ping_parallel};
    while (@jobs) {
        last if $reload || !$running;
        my @b = splice(@jobs, 0, $par);
        my %fh;
        for my $j (@b) {
            my $id = "$j->[0]{name}\t$j->[1]";
            my $pid = open(my $fh, '-|');
            if (!defined $pid) { $res{$id} = { err => "cannot start: $!" }; next }
            if (!$pid) {
                $SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { POSIX::_exit(1) };
                my $r = eval { ap_ports_one($cfg, $j->[0], $j->[2]) } || { err => (($@ // '') =~ s/\s+$//r) || 'unknown error' };
                binmode STDOUT;
                print JSON::PP->new->utf8->encode($r);
                close STDOUT;
                POSIX::_exit(0);
            }
            $fh{$id} = $fh;
        }
        for my $id (keys %fh) {
            my $fh = $fh{$id};
            binmode $fh;
            local $/;
            my $js = <$fh>;
            close $fh;
            $res{$id} = eval { JSON::PP->new->utf8->decode($js // '') } || { err => 'no answer from the process' };
        }
    }
    for my $id (keys %res) {
        my ($ctl, $k) = split /\t/, $id, 2;
        my $r = $res{$id};
        my $e = $db->{$ctl}{$k} ||= {};
        $e->{try} = $now + 0;
        if ($r->{ports}) {
            $e->{$_} = $r->{$_} for qw(ports sysname descr uptime src);
            $e->{$_} = $r->{$_} for grep { $r->{$_} } qw(nb ips);
            $e->{t} = $now + 0;
            $e->{fails} = 0;
            delete $e->{err};
        } else {
            $e->{fails} = ($e->{fails} // 0) + 1;
            $e->{err} = substr($r->{err} // 'unknown error', 0, 300);
            logmsg('debug', "AP ports $ctl/$k: $e->{err}");
        }
    }
    if (!defined $only) {                                  # access points that are gone
        for my $ctl (keys %$db) { for my $k (keys %{ $db->{$ctl} }) { delete $db->{$ctl}{$k} unless $have{$ctl}{$k} } delete $db->{$ctl} unless %{ $db->{$ctl} } }
    }
    jwrite($f, $db) if %res || !defined $only;
    return \%res;
}

# for the status JSON: the AP's ports in the form of a switch's SNMP data
sub ap_ports_status {
    my ($e, $now) = @_;
    return undef unless $e;
    return { kind => 'ap', src => $e->{src}, t => $e->{t}, state => ($e->{ports} ? 'ok' : $e->{err} ? 'error' : 'waiting'),
             (defined $e->{err} ? (err => $e->{err}) : ()), ports => $e->{ports} || [], sysname => $e->{sysname}, descr => $e->{descr},
             uptime => (defined $e->{uptime} && $e->{t} ? $e->{uptime} + ($now - $e->{t}) : undef), stale => ($e->{err} && $e->{ports} ? JSON::PP::true : JSON::PP::false) };
}

# --ap-ports [AP]: read now and print
sub ap_ports_cli {
    my ($cfg, $only) = @_;
    my $state = load_state($cfg->{general}{state_file});
    my $res = ap_ports_collect($cfg, $state, time, 1, (defined $only && length $only ? $only : undef));
    my $db = jread(ap_ports_file($cfg->{general})) || {};
    if (!%$res) { print "No access points to ask (ap_ports = no, no IP addresses yet, or not found).\n"; return 1 }
    for my $id (sort keys %$res) {
        my ($ctl, $k) = split /\t/, $id, 2;
        my $a = ($state->{capsman}{$ctl}{caps} || {})->{$k} || {};
        my $r = $res->{$id};
        printf "%s / %s (%s)\n", $ctl, $a->{identity} || $k, $a->{ip} // '';
        if (!$r->{ports}) { print "  not readable: $r->{err}\n"; next }
        print "  via " . uc($r->{src}) . ($r->{descr} ? ", $r->{descr}" : '') . "\n";
        for my $p (@{ $r->{ports} }) {
            my ($i, $n, $al, $op, $ad, $sp, undef, undef, $v, $pv) = @$p;
            printf "    %-14s %-9s %-10s %-22s %s\n", $n, ($ad == 2 ? 'disabled' : $op == 1 ? 'up' : 'down'), (defined $sp ? fmt_speed($sp) : ''),
                   ($v // '') . (defined $pv ? " pvid $pv" : ''), $al // '';
        }
    }
    return 0;
}

# ==========================================================================
# Inventory: models, serial numbers and versions of controllers, access points and
# switches (inventory.json, dashboard, --inventory, CSV); version mismatch per model
# ==========================================================================
sub controller_info {
    my ($cm) = @_;
    my %i;
    return { model => 'cnPilot access points (' . scalar(@{ $cm->{aps} }) . ')' } if $cm->{method} eq 'cnpilot';
    if ($cm->{method} eq 'msm') {
        my ($rc, $out) = run_cmd(($cm->{timeout} || 1) * ($cm->{retries} + 1) + 10, 'snmpget', '-On', '-Oqv', msm_auth($cm), $cm->{host}, '1.3.6.1.2.1.1.1.0');
        die "no sysDescr\n" unless $rc == 0 && $out =~ /\S/ && $out !~ /No Such/;
        ($i{model} = msm_str((split /\n/, $out)[0])) =~ s/\s+/ /g;
        ($i{version}) = $i{model} =~ /\b(?:v|version\s*)(\d+(?:\.\d+)+(?:-\d+)?)/i;
        ($i{serial}) = $i{model} =~ /serial\s*(?:number)?\s*[:=]?\s*(\w+)/i;
        $i{model} = substr($i{model}, 0, 80);
        return \%i;
    }
    if ($cm->{method} eq 'api') {
        my $api = RosAPI->new(%$cm);
        my ($re) = $api->cmd('/system/resource/print');
        my ($rb, $trap) = $api->cmd('/system/routerboard/print');
        $api->close;
        my $r = $re->[0] || {};
        my $b = (!defined $trap && $rb->[0]) || {};
        %i = (version => $r->{version}, board => $r->{'board-name'}, uptime => ros_seconds($r->{uptime}), model => $b->{model},
              serial => $b->{'serial-number'}, firmware => $b->{'current-firmware'}, upgrade => $b->{'upgrade-firmware'});
    } else {
        my $cmd = join ';', (map { qq{:put ("mtinv;$_->[0];" . [/system resource get $_->[1]])} } [ version => 'version' ], [ board => 'board-name' ], [ uptime => 'uptime' ]),
            ':do {' . join(';', map { qq{:put ("mtinv;$_->[0];" . [/system routerboard get $_->[1]])} }
                             [ model => 'model' ], [ serial => 'serial-number' ], [ firmware => 'current-firmware' ], [ upgrade => 'upgrade-firmware' ]) . '} on-error={}';
        my ($rc, $out) = ssh_exec($cm, $cmd);
        die "SSH failed\n" if $rc == 255;
        for (split /\r?\n/, $out) { $i{$1} = $2 if /^mtinv;(\w+);(.*?)\s*$/ }
        die "no answer to /system resource\n" unless $i{version};
        $i{uptime} = ros_seconds($i{uptime});
    }
    $i{model} = $i{board} if !$i{model} || $i{model} =~ /^\s*$/;
    delete $i{$_} for grep { !defined $i{$_} || $i{$_} eq '' } keys %i;
    return \%i;
}

# HP MSM access points: serial (2), firmware (9), product (11) of coDeviceDiscoveryTable - best effort
sub msm_ap_info {
    my ($cm) = @_;
    my %by;
    my ($st, $lines) = msm_walk($cm, "$MSM_BASE.3");
    return () unless $st eq 'ok';
    my $mac = {};
    for (msm_parse(@$lines)) { my ($o, $t, $v) = @$_; $mac->{$1} = msm_mac($t, $v) if $o =~ /^\Q$MSM_BASE\E\.3\.(.+)$/ }
    for my $c ([ 2, 'serial' ], [ 9, 'version' ], [ 11, 'model' ]) {
        my ($s2, $l2) = msm_walk($cm, "$MSM_BASE.$c->[0]");
        next unless $s2 eq 'ok';
        for (msm_parse(@$l2)) {
            my ($o, $t, $v) = @$_;
            next unless $o =~ /^\Q$MSM_BASE.$c->[0]\E\.(.+)$/ && $mac->{$1};
            $v = msm_str($v);
            $by{ $mac->{$1} }{ $c->[1] } = $v if length $v && $v !~ /No Such/;
        }
    }
    return %by;
}

sub inventory_build {
    my ($cfg, $state, $now, $refresh) = @_;
    my $g = $cfg->{general};
    my $f = data_file($g, 'inventory.json');
    my $old = jread($f) || {};
    my %orow = map { ($_->{key} => $_) } @{ $old->{rows} || [] };
    my (@rows, @ev);
    for my $cm (@{ $cfg->{capsman} }) {
        my $cs = $state->{capsman}{ $cm->{name} } || {};
        my $o = $orow{"ctl|$cm->{name}"} || {};
        my $ci;
        if ($refresh) {
            last if $reload || !$running;
            $ci = eval { controller_info($cm) };
            logmsg('debug', "Inventory $cm->{name}: $@") unless $ci;
        }
        $ci ||= { map { ($_ => $o->{$_}) } grep { defined $o->{$_} } qw(model serial version firmware upgrade uptime board) };
        my $uptime = $ci->{uptime};
        $uptime += $now - ($old->{t} // $now) if !$refresh && defined $uptime;
        push @rows, { key => "ctl|$cm->{name}", type => 'controller', name => $cs->{identity} || $cm->{name}, where => dev_heading($cm),
                      ip => $cm->{host}, %$ci, uptime => $uptime, status => ($cs->{down_since} ? 'down' : 'up'),
                      kind => ctl_kind($cm) };
        my %msm = ($cm->{method} eq 'msm' && $refresh) ? eval { msm_ap_info($cm) } : ();
        for my $k (sort keys %{ $cs->{caps} || {} }) {
            my $a = $cs->{caps}{$k};
            my $oa = $orow{"ap|$cm->{name}|$k"} || {};
            my $m = $msm{ uc($a->{mac} // '') } || {};
            push @rows, { key => "ap|$cm->{name}|$k", type => 'ap', name => $a->{identity} || $a->{mac}, where => dev_heading($cm), ctl => $cm->{name},
                          ip => $a->{ip}, mac => $a->{mac},
                          model => ($cm->{method} eq 'msm' ? ($m->{model} // $oa->{model}) : ($a->{board} || $oa->{model})),
                          serial => $a->{serial} || $m->{serial} || $oa->{serial}, version => $a->{version} || $m->{version} || $oa->{version},
                          status => ($a->{missing_since} ? 'missing' : 'online'), kind => ctl_kind($cm) };
            $rows[-1]{location} = $a->{board} if $cm->{method} eq 'msm' && $a->{board};
        }
    }
    for my $sw (@{ $cfg->{switches} }) {
        my $st = $state->{switches}{ $sw->[0] } || {};
        my $sn = $st->{snmp} || {};
        my $iv = $sn->{inv} || {};
        my $uptime = (!$sn->{err} && defined $sn->{uptime}) ? $sn->{uptime} + ($now - ($sn->{t} // $now)) : undef;
        push @rows, { key => "sw|$sw->[0]", type => 'switch', name => $sw->[1], ip => $sw->[0], where => $g->{_switches_title} // 'Switches',
                      model => $iv->{model}, serial => $iv->{serial}, version => $iv->{version}, firmware => $iv->{firmware},
                      descr => $sn->{descr}, sysname => $sn->{sysname}, uptime => $uptime,
                      status => (!$st->{last_ok} && !$st->{down_since} ? 'unknown' : $st->{down_since} ? 'down' : 'up'),
                      snmp => ($sw->[2]{snmp} ? ($sn->{err} ? 'error' : $sn->{t} ? 'ok' : 'waiting') : 'off') };
    }
    for my $r (@rows) { delete $r->{$_} for grep { !defined $r->{$_} || $r->{$_} eq '' } keys %$r }
    # version mismatch: devices of the same model (and kind) that do not run the version most of them run
    my %grp;
    for my $r (grep { $_->{model} && $_->{version} } @rows) { push @{ $grp{ join '|', $r->{type} eq 'controller' ? 'controller' : $r->{type}, $r->{kind} // '', lc $r->{model} } }, $r }
    for my $list (values %grp) {
        my %n;
        $n{ $_->{version} }++ for @$list;
        next if keys %n < 2;
        my ($maj) = sort { $n{$b} <=> $n{$a} || vcmp_ver($b, $a) } keys %n;
        $_->{mismatch} = "most $_->{model} run $maj" for grep { $_->{version} ne $maj } @$list;
    }
    # version changes since the last inventory -> events (not mailed)
    for my $r (@rows) {
        my $o = $orow{ $r->{key} } or next;
        next unless $o->{version} && $r->{version} && $o->{version} ne $r->{version};
        push @ev, { t => $now + 0, type => 'inv_change', name => $r->{name}, ip => $r->{ip} // '', heading => $r->{where} // '',
                    text => "$o->{version} -> $r->{version}", from => $o->{version}, to => $r->{version} };
    }
    append_jsonl($g, 'events.jsonl', @ev) if @ev;
    my $inv = { t => $now + 0, refreshed => ($refresh ? $now + 0 : $old->{refreshed}), rows => \@rows };
    jwrite($f, $inv);
    return $inv;
}

# /manual: the HTML manual installed with the package (Slovenian or English: ?lang=, else the
# browser language); shared with mtmon-admin-center
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 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 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 note_inv {
    my ($r) = @_;
    my @n;
    push @n, "MISMATCH: $r->{mismatch}" if $r->{mismatch};
    push @n, 'no SNMP' if $r->{type} eq 'switch' && ($r->{snmp} // '') eq 'off';
    push @n, $r->{status} if ($r->{status} // '') eq 'down' || ($r->{status} // '') eq 'missing';
    return join ', ', @n;
}

sub inventory_cli {
    my ($cfg, $csv) = @_;
    my $state = load_state($cfg->{general}{state_file});
    if (grep { $_->[2]{snmp} } @{ $cfg->{switches} }) {        # fresh switch data for the list
        my $ping = ping_hosts([ map { $_->[0] } @{ $cfg->{switches} } ], $cfg->{general});
        my $r = snmp_collect($cfg->{general}, [ map { $_->[2] } grep { $_->[2]{snmp} && $ping->{ $_->[0] } } @{ $cfg->{switches} } ], 1);
        for my $h (keys %$r) {
            next if $r->{$h}{err};
            my $st = $state->{switches}{$h} ||= {};
            $st->{snmp} = { %{ $st->{snmp} || {} }, inv => $r->{$h}{inv}, descr => $r->{$h}{descr}, sysname => $r->{$h}{sysname},
                            uptime => $r->{$h}{uptime}, t => time };
            $st->{last_ok} ||= time;
        }
    }
    my $inv = inventory_build($cfg, $state, time, 1);
    if ($csv) { binmode STDOUT, ':raw'; print encode('UTF-8', inventory_csv($inv->{rows})); return 0 }
    my %tn = (controller => 'Controller', ap => 'AP', switch => 'Switch');
    printf "%-10s %-26s %-15s %-22s %-16s %-18s %s\n", qw(Type Name IP Model Serial Version Note);
    for my $r (@{ $inv->{rows} }) {
        printf "%-10s %-26s %-15s %-22s %-16s %-18s %s\n", $tn{ $r->{type} }, substr($r->{name} // '-', 0, 26), $r->{ip} // '-',
            substr($r->{model} // '-', 0, 22), substr($r->{serial} // '-', 0, 16), substr($r->{version} // '-', 0, 18),
            note_inv($r);
    }
    my $mm = grep { $_->{mismatch} } @{ $inv->{rows} };
    print "\n$mm device(s) with a version different from the others of the same model.\n" if $mm;
    return 0;
}

# ==========================================================================
# Weekly / monthly report ([report]): availability, outages, Wi-Fi peaks, unstable devices,
# restarts, version changes, certificates. Computed from events.jsonl and the history files,
# so it works the same for one mtmon and per site in the mtmon-admin-center (shared code).
# ==========================================================================

# the last complete week (Monday 00:00 - Monday 00:00, local time) or month before $now
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,
    };
}

# ==========================================================================
# Device report (12.0.0): availability of the controllers, access points and devices, the
# outages (list and timeline), restarts, unstable devices, firmware changes, maintenance,
# and the switch statistics over time (ports in use, PoE, temperature, uplink traffic, errors).
# $status = the dashboard status (web_status) of the place - also what a site sends to the centre.
# Shared with mtmon-admin-center.
# ==========================================================================
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;
}

# several sites (the centre): the device reports one after another, availability weighted by devices
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),
    };
}

# kept on disk for periods that are over, like the Wi-Fi report
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 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";
}

# subject, text and HTML of a report. $o: { kind, from, to, title, footer, sites => [ { title, stats, certs, mismatch, maint_now } ] }
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 }

# mtmon: the report of one site, by mail
sub period_report {
    my ($cfg, $kind, $from, $to) = @_;
    my $g = $cfg->{general};
    my $st = period_stats($g, $from, $to);
    my $inv = jread(data_file($g, 'inventory.json')) || {};
    my ($subj, $text, $html) = report_render({ kind => $kind, from => $from, to => $to, title => $g->{location},
        footer => "mtmon $VERSION on " . hostname(),
        sites => [ { title => $g->{location}, stats => $st, certs => certs_status($cfg),
                     mismatch => [ grep { $_->{mismatch} } @{ $inv->{rows} || [] } ] } ] });
    my $mcfg = length $cfg->{report}{to} ? { %$cfg, mail => { %{ $cfg->{mail} }, to => $cfg->{report}{to} } } : $cfg;
    send_mail($mcfg, $subj, $text, $cfg->{mail}{format} eq 'html' ? $html : undef);
    logmsg('info', "Report sent: $subj");
    return 1;
}

# daemon: the weekly report on Monday, the monthly one on the 1st, at [report] time
sub report_check {
    my ($cfg, $now) = @_;
    my $rp = $cfg->{report};
    return unless $rp->{enabled} && ($rp->{weekly} || $rp->{monthly});
    my $f = data_file($cfg->{general}, 'report.json');
    my $st = jread($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 }      # first run: from the next period on
        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;                            # failed: again in half an hour
        if (eval { period_report($cfg, $kind, $from, $to) }) { $st->{$kind} = $to + 0; delete $st->{"${kind}_fail"} }
        else { logmsg('error', "Sending the " . ($kind eq 'week' ? 'weekly' : 'monthly') . " report failed: $@"); $st->{"${kind}_fail"} = $now + 0 }
        $changed = 1;
    }
    jwrite($f, $st) if $changed;
}

# --period-report week|month|Nd: send the report of the last complete week / month (or the last N days) now
sub period_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 --period-report week|month|7d   (last complete week / month, or the last N days)\n" }
    period_report($cfg, $kind, $from, $to);
    return 0;
}

# ==========================================================================
# Minimal RouterOS API client (v6.43+ and v7; legacy login supported too)
# ==========================================================================
package RosAPI;

use Encode qw(encode decode);
use Digest::MD5 qw(md5_hex);

sub new {
    my ($class, %a) = @_;
    my $sock;
    my $to = $a{timeout} || 15;
    if ($a{ssl}) {
        require IO::Socket::SSL;
        $sock = IO::Socket::SSL->new(
            PeerHost        => $a{host},
            PeerPort        => $a{port},
            Timeout         => $to,
            SSL_verify_mode => $a{ssl_verify} ? 1 : 0,
            ($a{ssl_verify} ? (SSL_verifycn_name => $a{host}) : ()),
        ) or die "SSL connection to $a{host}:$a{port} failed: " . IO::Socket::SSL::errstr() . "\n";
    } else {
        $sock = IO::Socket::INET->new(PeerAddr => $a{host}, PeerPort => $a{port},
                                      Proto => 'tcp', Timeout => $to)
            or die "Connection to $a{host}:$a{port} failed: $@\n";
    }
    binmode $sock;
    my $self = bless { sock => $sock, timeout => $to }, $class;
    $self->_login($a{user}, $a{password} // '');
    return $self;
}

sub close { my $s = shift; CORE::close($s->{sock}) if $s->{sock}; delete $s->{sock} }

sub cmd {
    my ($self, @words) = @_;
    my (@re, $trap, %done);
    local $SIG{ALRM} = sub { die "API timeout ($self->{timeout} s)\n" };
    alarm $self->{timeout};
    eval {
        $self->_write_sentence(@words);
        while (1) {
            my @s = $self->_read_sentence;
            next unless @s;
            my $type = shift @s;
            my %attr;
            for (@s) { $attr{$1} = $2 if /^=([^=]+)=(.*)$/s }
            if    ($type eq '!re')    { push @re, \%attr }
            elsif ($type eq '!trap')  { $trap = $attr{message} // 'unknown error' }
            elsif ($type eq '!fatal') { die "API fatal: " . join(' ', @s) . "\n" }
            elsif ($type eq '!done')  { %done = %attr; last }
            # !empty (7.18+) and anything else is ignored
        }
        1;
    } or do { my $e = $@; alarm 0; die $e };
    alarm 0;
    return (\@re, $trap, \%done);
}

sub _login {
    my ($self, $u, $p) = @_;
    my (undef, $trap, $done) = $self->cmd('/login', "=name=$u", "=password=$p");
    die "Login failed: $trap\n" if defined $trap;
    if (defined $done->{ret}) {                 # RouterOS < 6.43 (challenge-response)
        my $resp = '00' . md5_hex(chr(0) . encode('UTF-8', $p) . pack('H*', $done->{ret}));
        (undef, $trap) = $self->cmd('/login', "=name=$u", "=response=$resp");
        die "Login failed: $trap\n" if defined $trap;
    }
}

sub _enc_len {
    my $l = shift;
    return chr($l)                                 if $l < 0x80;
    return pack('n', $l | 0x8000)                  if $l < 0x4000;
    return substr(pack('N', $l | 0xC00000), 1)     if $l < 0x200000;
    return pack('N', $l | 0xE0000000)              if $l < 0x10000000;
    return chr(0xF0) . pack('N', $l);
}

sub _write_sentence {
    my ($self, @words) = @_;
    my $buf = '';
    for my $w (@words) { my $b = encode('UTF-8', $w); $buf .= _enc_len(length $b) . $b }
    $buf .= chr(0);
    my $off = 0;
    while ($off < length $buf) {
        my $n = syswrite($self->{sock}, $buf, length($buf) - $off, $off);
        die "API write failed: $!\n" unless defined $n;
        $off += $n;
    }
}

sub _read_n {
    my ($self, $n) = @_;
    my $buf = '';
    while (length($buf) < $n) {
        my $r = sysread($self->{sock}, $buf, $n - length($buf), length($buf));
        die "API read failed: $!\n" unless defined $r;
        die "API connection closed\n" if $r == 0;
    }
    return $buf;
}

sub _read_len {
    my $self = shift;
    my $c = ord $self->_read_n(1);
    return $c                                                     if ($c & 0x80) == 0;
    return (($c & 0x3F) << 8)  + ord($self->_read_n(1))           if ($c & 0xC0) == 0x80;
    return (($c & 0x1F) << 16) + unpack('n', $self->_read_n(2))   if ($c & 0xE0) == 0xC0;
    return (($c & 0x0F) << 24) + unpack('N', "\0" . $self->_read_n(3)) if ($c & 0xF0) == 0xE0;
    return unpack('N', $self->_read_n(4))                         if $c == 0xF0;
    die "Invalid length in API reply\n";
}

sub _read_sentence {
    my $self = shift;
    my @w;
    while (1) {
        my $l = $self->_read_len;
        last if $l == 0;
        push @w, _dec($self->_read_n($l));
    }
    return @w;
}

# RouterOS identities may be UTF-8 or cp1250 (č, š, ž) - try both
sub _dec {
    my $b = shift;
    my $s = eval { decode('UTF-8', $b, Encode::FB_CROAK | Encode::LEAVE_SRC) };
    return defined $s ? $s : decode('cp1250', $b);
}

1;
