#! /usr/local/bin/perl
use lib '/usr/local/news/lib/perl'; use INN::Config;

##  History manipulation utility for hissqlite.
##
##  Initial version written in 2026 by Kevin Bowling, modeled on ovsqlite-util.

use strict;
use warnings;

use Getopt::Std;
use POSIX qw(strftime);

$0 =~ s!.*/!!;

# Version of this tool.
my $VERSION = "1.3";

# Bail out if the needed DBI Perl module is not installed.
eval {
    require DBI;
    require DBD::SQLite;
    1;
} or die "DBI Perl module with SQLite driver needed"
  . " (usually packaged as libdbd-sqlite3-perl, perl-DBD-SQLite,"
  . " or p5-DBD-SQLite)";

# Name of the database file.
my $dbfile = "history.sqlite";

my $usage = "Usage:
  $0 [-AcdhsvV] [-O order] [-p path]

Options:
  -A             Audit the history database for problems, and report them to
                 standard error, without trying to fix them.  This is the
                 default action.
  -c             Print total, real, and remembered entry counts.
  -d             Dump all history records as text, one per line.
  -h             Print this help message.
  -O order       Sort history records by order time when dumped with -d.
                 order can be \"arrival\", \"expiration\" or \"posting\".
  -p path        Read $dbfile database file in path directory instead of
                 default pathhistory directory as set in inn.conf.
  -s             Print database storage and history entry statistics.
  -v             Vacuum the database (rewrite to reclaim freelist space).
  -V             Print the version of this tool and the database schema
                 version.
";

sub HELP_MESSAGE {
    print $usage;
    exit(0);
}

my @unique_hash_keys_unused = qw(sqlite_open_flags);    # perltidy -wuk

my %opt;
getopts("AcdhO:p:svV", \%opt) || die $usage;

HELP_MESSAGE() if defined($opt{'h'});

my $modes = 0;
$modes++ if defined($opt{'A'});
$modes++ if defined($opt{'c'});
$modes++ if defined($opt{'d'});
$modes++ if defined($opt{'s'});
$modes++ if defined($opt{'v'});
$modes++ if defined($opt{'V'});

die "Only one action allowed at the same time\n\n$usage"
  if $modes > 1;
die "Can't use -O without -d\n\n$usage"
  if defined($opt{'O'})
  and not defined($opt{'d'});
die "Invalid order given to -O\n\n$usage"
  if defined($opt{'O'})
  and $opt{'O'} ne "arrival"
  and $opt{'O'} ne "expiration"
  and $opt{'O'} ne "posting";

my $dbdir;
{
    no warnings 'once';    ##  no critic (ProhibitNoWarnings)
    $dbdir = $opt{'p'} || $INN::Config::pathhistory;
}
my $dbpath = "$dbdir/$dbfile";
my $datasource = "dbi:SQLite:dbname=$dbpath";
my $pausemsg = "hissqlite-util vacuum";
my $ispaused = 0;

# Read-only modes open the database read-only.  Vacuum needs write access.
# SQLITE_OPEN_READONLY is 0x00000001.
my $SQLITE_OPEN_READONLY = 0x00000001;
my $need_write = defined($opt{'v'});

# Open the connection.  The username and password fields are left empty.
# Enabling RaiseError permits not checking every return error codes.
my %connect_attr = (
    PrintError => 0,
    RaiseError => 1,
    AutoCommit => 1,
);
$connect_attr{sqlite_open_flags} = $SQLITE_OPEN_READONLY
  if not $need_write;

my $dbh = DBI->connect($datasource, '', '', \%connect_attr);

# Extra safety net against any accidental write in the read-only modes.
$dbh->do("pragma query_only = 1;")
  if not $need_write;

# Raise the busy timeout value to a huge number of milliseconds to prevent
# timeouts because of database locks while innd holds the writer.
$dbh->sqlite_busy_timeout(999999999);

if (defined($opt{'V'})) {
    print_version();
} elsif (defined($opt{'c'})) {
    count_entries();
} elsif (defined($opt{'d'})) {
    dump_history();
} elsif (defined($opt{'s'})) {
    dump_statistics();
} elsif (defined($opt{'v'})) {
    pause_if_running();
    vacuum_database();
} else {
    # Default action: audit.
    audit_history();
}

# Close the connection properly.
$dbh->disconnect;

exit(0);

END {
    # In case we bail out while being paused, make sure that the show goes on!
    if ($ispaused) {
        if (system "$INN::Config::newsbin/ctlinnd -s go '$pausemsg'") {
            die "$0: failed to resume INN with "
              . "\"ctlinnd -s go '$pausemsg'\" command "
              . "=> please check why and *manually* resume it\n";
        }
    }
}

# Return the schema version stored in the misc table, or undef if absent.
sub get_version {
    my $statement = $dbh->prepare("select value from misc where key = ?;");
    my ($version) = $dbh->selectrow_array($statement, undef, "version");
    return $version;
}

# Return a list of (total, real, remembered, explicitly expiring, earliest
# arrival, latest arrival).  Compute them in one table scan; callers that only
# need the first values can ignore the remainder.
sub get_counts {
    my @array = $dbh->selectrow_array(
        q{
            select count(*),
                   coalesce(sum(token is not null), 0),
                   coalesce(sum(token is null), 0),
                   coalesce(sum(token is not null and expires > 0), 0),
                   min(arrived),
                   max(arrived)
                from hist;
        },
    );
    return @array;
}

# Print the tool version and the database schema version (-V option).
sub print_version {
    my $version = get_version();
    $version = defined($version) ? $version : "unknown";
    print "$0 version $VERSION\n";
    print "hissqlite database schema version $version\n";
}

# Print total, real, and remembered entry counts (-c option).
sub count_entries {
    my (
        $total, $real, $remembered, $explicit_expiration_unused,
        $minarrived_unused,
        $maxarrived_unused,
    ) = get_counts();
    print "total $total\n";
    print "real $real\n";
    print "remembered $remembered\n";
}

# Dump all history records (-d option).
sub dump_history {
    my $statement;

    my $order = $opt{'O'};
    my $sql_extraclause = '';

    if (defined($order)) {
        if ($order eq "arrival") {
            $sql_extraclause = "order by arrived,posted";
        } elsif ($order eq "expiration") {
            $sql_extraclause = "order by expires,posted";
        } elsif ($order eq "posting") {
            $sql_extraclause = "order by posted,arrived";
        }
    }
    # hex() renders a BLOB as uppercase hex, or an empty string for a
    # remembered entry's missing token.
    $statement = $dbh->prepare(
        qq{
            select hex(hash), arrived, posted, expires, hex(token)
                from hist $sql_extraclause;
        },
    );
    $statement->execute();

    while (my @row = $statement->fetchrow_array()) {
        my ($hash, $arrived, $posted, $expires, $token) = @row;
        $posted = defined($posted) ? $posted : '0';
        $expires = defined($expires) ? $expires : '0';
        if (!defined($token) || $token eq '') {
            $token = 'remembered';
        } else {
            # The token column stores the raw storage API token, so its hex
            # surrounded with @ is exactly INN's textual token form, as
            # rendered by TokenToText() and used in a hisv6 history file.
            $token = '@' . $token . '@';
        }
        print "$hash $arrived $posted $expires $token\n";
    }
}

# Return the size of a file, or 0 if the file does not exist.
sub file_size {
    my $path = shift;
    my $size = -s $path;
    return defined($size) ? $size : 0;
}

# Collect page and freelist statistics for vacuum before/after reporting.
sub page_stats {
    my ($page_size) = $dbh->selectrow_array("pragma page_size;");
    my ($page_count) = $dbh->selectrow_array("pragma page_count;");
    my ($freelist_count) = $dbh->selectrow_array("pragma freelist_count;");
    my $logical_size = $page_count * $page_size;
    my $freelist_size = $freelist_count * $page_size;
    return (
        $page_size, $page_count, $freelist_count, $logical_size,
        $freelist_size,
    );
}

# Pause a running innd so it is not writing during VACUUM.  If innd is not
# running (or ctlinnd is unavailable, as when this script is run from the
# source tree with -p), proceed offline.
sub pause_if_running {
    my $ctlinnd;
    {
        no warnings 'once';    ##  no critic (ProhibitNoWarnings)
        $ctlinnd
          = defined($INN::Config::newsbin)
          ? "$INN::Config::newsbin/ctlinnd"
          : undef;
    }
    return if !defined($ctlinnd) || !-x $ctlinnd;

    # ctlinnd mode fails when innd is not running.
    return if system("$ctlinnd -s mode >/dev/null 2>&1") != 0;

    if (system("$ctlinnd -s pause '$pausemsg'")) {
        die "$0: failed to pause INN, aborting\n";
    }
    $ispaused = 1;
}

# Rewrite the database to reclaim freelist pages (-v option).
sub vacuum_database {
    my (
        $page_size, $page_count, $freelist_count, $logical_size,
        $freelist_size,
    ) = page_stats();
    my $file_size = file_size($dbpath);

    print "Database file: $dbpath\n";
    print "Page size: $page_size bytes\n";
    print "Before vacuum:\n";
    print "  Page count: $page_count\n";
    print "  Freelist pages: $freelist_count\n";
    print "  Logical database size: $logical_size bytes\n";
    print "  Freelist size: $freelist_size bytes\n";
    print "  Database file size: $file_size bytes\n";

    if ($freelist_count == 0) {
        print "No freelist pages to reclaim; vacuuming anyway to "
          . "compact the file.\n";
    }

    # VACUUM rewrites the whole database.  Free disk space roughly equal to
    # the current file size is required for the temporary copy.
    print "Running VACUUM (this may take a while)...\n";
    $dbh->do("vacuum;");

    (
        $page_size, $page_count, $freelist_count, $logical_size,
        $freelist_size,
    ) = page_stats();
    $file_size = file_size($dbpath);

    print "After vacuum:\n";
    print "  Page count: $page_count\n";
    print "  Freelist pages: $freelist_count\n";
    print "  Logical database size: $logical_size bytes\n";
    print "  Freelist size: $freelist_size bytes\n";
    print "  Database file size: $file_size bytes\n";
    print "Vacuum complete.\n";
}

# Print database storage and entry statistics (-s).
sub dump_statistics {
    # DBD::SQLite's begin_work uses BEGIN IMMEDIATE, which requests a write
    # lock.  Start a deferred transaction explicitly for this read-only
    # snapshot.
    $dbh->do("begin transaction;");
    my ($sqlite_version) = $dbh->selectrow_array("select sqlite_version();");
    my $schema_version = get_version();
    my ($journal_mode) = $dbh->selectrow_array("pragma journal_mode;");
    my ($auto_vacuum) = $dbh->selectrow_array("pragma auto_vacuum;");
    my ($page_size) = $dbh->selectrow_array("pragma page_size;");
    my ($page_count) = $dbh->selectrow_array("pragma page_count;");
    my ($freelist_count) = $dbh->selectrow_array("pragma freelist_count;");
    my (
        $total, $real, $remembered, $explicit_expiration, $minarrived,
        $maxarrived,
    ) = get_counts();
    $dbh->commit();

    my $used_pages = $page_count - $freelist_count;
    my $logical_size = $page_count * $page_size;
    my $used_size = $used_pages * $page_size;
    my $freelist_size = $freelist_count * $page_size;
    my $freelist_share
      = $page_count > 0 ? 100 * $freelist_count / $page_count : 0;
    my $real_percent = $total > 0 ? 100 * $real / $total : 0;
    my $remembered_percent = $total > 0 ? 100 * $remembered / $total : 0;
    my @auto_vacuum_names = qw(none full incremental);
    my $auto_vacuum_name
      = defined($auto_vacuum_names[$auto_vacuum])
      ? $auto_vacuum_names[$auto_vacuum]
      : "unknown ($auto_vacuum)";
    my $database_file_size = file_size($dbpath);
    my $wal_file_size = file_size("$dbpath-wal");
    my $shm_file_size = file_size("$dbpath-shm");
    my $journal_file_size = file_size("$dbpath-journal");
    my $total_file_size
      = $database_file_size
      + $wal_file_size
      + $shm_file_size
      + $journal_file_size;

    $schema_version = defined($schema_version) ? $schema_version : "unknown";
    print "Database file: $dbpath\n";
    print "SQLite version: $sqlite_version\n";
    print "Schema version: $schema_version\n";
    print "Journal mode: $journal_mode\n";
    print "Auto-vacuum: $auto_vacuum_name\n";
    print "Page size: $page_size bytes\n";
    print "Page count: $page_count\n";
    print "Non-freelist pages: $used_pages\n";
    print "Freelist pages: $freelist_count\n";
    printf "Freelist share: %.1f%%\n", $freelist_share;
    print "Logical database size: $logical_size bytes\n";
    print "Non-freelist page capacity: $used_size bytes\n";
    print "Freelist size: $freelist_size bytes\n";
    print "Database file size: $database_file_size bytes\n";
    print "WAL file size: $wal_file_size bytes\n";
    print "Shared-memory file size: $shm_file_size bytes\n";
    print "Rollback journal file size: $journal_file_size bytes\n";
    print "Total SQLite file size: $total_file_size bytes\n";
    print "Total entries: $total\n";
    printf "Real entries: %d (%.1f%%)\n", $real, $real_percent;
    printf "Remembered entries: %d (%.1f%%)\n",
      $remembered, $remembered_percent;
    print "Real entries with explicit expiration: $explicit_expiration\n";

    if (defined($minarrived) && defined($maxarrived)) {
        printf "Arrived range: %s .. %s\n",
          strftime('%Y-%m-%d %H:%M:%S', localtime($minarrived)),
          strftime('%Y-%m-%d %H:%M:%S', localtime($maxarrived));
    } else {
        print "Arrived range: (empty database)\n";
    }
}

# Audit the history database for problems and report them (-A option, default).
sub audit_history {
    my $problems = 0;

    # Schema version.
    my $version = get_version();
    if (defined($version)) {
        print "Schema version: $version\n";
    } else {
        print STDERR "No schema version found in misc table\n";
        $problems++;
    }

    # Entry counts and arrival range.
    my (
        $total, $real, $remembered, $explicit_expiration_unused, $minarrived,
        $maxarrived,
    ) = get_counts();
    print "Total entries: $total\n";
    print "Real entries (token not null): $real\n";
    print "Remembered entries (token null): $remembered\n";

    if (defined($minarrived) and defined($maxarrived)) {
        printf "Arrived range: %s .. %s\n",
          strftime('%Y-%m-%d %H:%M:%S', localtime($minarrived)),
          strftime('%Y-%m-%d %H:%M:%S', localtime($maxarrived));
    } else {
        print "Arrived range: (empty database)\n";
    }

    # Rows with a NULL arrived value (arrived is declared not null, so any
    # such row indicates corruption).
    my ($nullarrived)
      = $dbh->selectrow_array(
          "select count(*) from hist where arrived is null;");
    if (defined($nullarrived) and $nullarrived > 0) {
        print STDERR "$nullarrived row(s) with NULL arrived value\n";
        $problems++;
    }

    # SQLite low-level integrity check.
    my $statement = $dbh->prepare("pragma integrity_check;");
    $statement->execute();
    while (my @row = $statement->fetchrow_array()) {
        next if $row[0] eq 'ok';
        print STDERR "integrity_check: $row[0]\n";
        $problems++;
    }

    if ($problems > 0) {
        printf STDERR (
            "%d problem%s found\n",
            $problems, ($problems > 1) ? "s" : "",
        );
        exit(1);
    } else {
        print "No problems found\n";
    }
}
