#!/usr/bin/perl
#
# Generate initial configugration files for a new INN server.
#
# Written by Tim Skirvin <tskirvin@stanford.edu>
# Updates by Russ Allbery <eagle@eyrie.org>
# Copyright 2020, 2023 Russ Allbery <eagle@eyrie.org>
# Copyright 2008
#     The Board of Trustees of the Leland Stanford Junior University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

use 5.028;
use autodie;
use warnings;

use Carp qw(croak);
use File::Basename qw(basename dirname);
use Getopt::Long ();
use IPC::System::Simple qw(systemx);
use Net::NNTP;
use Pod::Usage qw(pod2usage);

##############################################################################
# Configuration
##############################################################################

# Where will these three files end up?
my $ACTIVE = '/var/lib/news/db/active';
my $NEWSGROUPS = '/var/lib/news/db/newsgroups';
my $HISTORY = '/var/lib/news/db/history';

# What is the server where we'll get default information?
my $SERVER = 'usenet.stanford.edu';

# Used to create history files.
my $MAKEDBZ = '/usr/lib/news/bin/makedbz';

##############################################################################
# Utility functions
##############################################################################

# Change ownership of files to news:news.
#
# @files - The paths to the files.
sub chown_files_to_news {
    my (@files) = @_;
    my (undef, undef, $uid, $gid) = getpwnam('news');
    chown($uid, $gid, @files);
    return;
}

# Count the lines in a file.
#
# $file - The path to the file
#
# Returns: The number of lines in the file, or undef if the file cannot be
#          opened
sub lines_in_file {
    my ($file) = @_;
    open(my $fh, '<', $file) or return;
    my @lines = <$fh>;
    close($fh);
    return scalar(@lines);
}

# Open a connection to the given NNTP server.  The connection is cached and an
# existing connection is returned if one is available.
#
# $server - The server to which to connect.
#
# Returns: An open NNTP connection
#  Raises: A text exception on failure to connect
sub open_server {
    my ($server) = @_;
    state $nntp;
    state $open_server;
    if ($nntp && $server eq $open_server) {
        return $nntp;
    }
    $nntp = Net::NNTP->new($server)
      or die "$0: cannot connect to $server: $!\n";
    $open_server = $server;
    return $nntp;
}

# print with error checking and an explicit file handle.  autodie
# unfortunately can't help us with these because they can't be prototyped and
# hence can't be overridden.
#
# $fh   - Output file handle
# @args - Remaining arguments to print
#
# Returns: undef
#  Throws: Text exception on output failure
sub print_fh {
    my ($fh, @args) = @_;
    print {$fh} @args or croak('print failed');
    return;
}

# Say with error checking.  autodie unfortunately can't help us with this
# because say cannot be prototyped and hence can't be overridden.
#
# @args - Arguments to say
#
# Throws: Text exception on output failure
sub say_checked {
    my (@args) = @_;
    say @args or croak('say failed');
    return;
}

##############################################################################
# Implementation
##############################################################################

# Create the active file if it doesn't exist or if the one we have looks like
# the default file.
#
# $server - The server from which to retrieve the file
sub create_active {
    my ($server) = @_;
    if (-e $ACTIVE && lines_of_file($ACTIVE) >= 20) {
        say_checked("$ACTIVE already exists");
        return;
    }
    my $nntp = open_server($server);
    my $groups = $nntp->active;
    if (!$groups) {
        warn "$0: cannot retrieve active file from $server\n";
        return;
    }
    open(my $active, '>', $ACTIVE);
    for my $group (sort(keys($groups->%*))) {
        my $mode = $groups->{$group}[2];
        print_fh($active, "$group 0000000000 0000000001 $mode\n");
    }
    close($active);
    chown_files_to_news($ACTIVE);
    say_checked("Created new $ACTIVE");
    return;
}

# Create the newsgroups file if it doesn't exist or if the one we have looks
# like the default file.
#
# $server - The server from which to retrieve the file
sub create_newsgroups {
    my ($server) = @_;
    if (-e $NEWSGROUPS && lines_of_file($NEWSGROUPS) >= 20) {
        say_checked("$NEWSGROUPS already exists");
        return;
    }
    my $nntp = open_server($server);
    my $groups = $nntp->newsgroups;
    if (!$groups) {
        warn "$0: cannot retrieve newsgroups from $server\n";
        return;
    }
    open(my $newsgroups, '>', $NEWSGROUPS);
    for my $group (sort(keys($groups->%*))) {
        print_fh($newsgroups, join("\t", $group, $groups->{$group}), "\n");
    }
    close($newsgroups);
    chown_files_to_news($NEWSGROUPS);
    say_checked("Created new $NEWSGROUPS");
    return;
}

# Create the history database if it doesn't exist.
sub create_history {
    if (-e $HISTORY) {
        say_checked("$HISTORY already exists");
        return;
    }
    my $dir = dirname($HISTORY);
    my $file = basename($HISTORY);
    chdir($dir);
    open(my $history, '>', $HISTORY);
    close($history);
    systemx($MAKEDBZ, '-i', '-f', $file);
    opendir(my $dirfh, $dir);
    my @files = grep { m{ ^ \Q$file\E }xms } readdir($dirfh);
    closedir($dirfh);
    chown_files_to_news(@files);
    say_checked("Created $HISTORY");
    return;
}

##############################################################################
# Main routine
##############################################################################

# Clean up the name of this program for error messages.
$0 =~ s{ .*/ }{}xms;

# Parse command-line options.
my $parser = Getopt::Long::Parser->new();
my %opts;
$parser->getoptions(\%opts, 'h|help', 's|server=s')
  or pod2usage(-verbose => 0, -exitval => 1);
if ($opts{help}) {
    pod2usage(-verbose => 2);
}
my $server = $opts{server} // $SERVER;

# Create the active and newsgroups files.
create_active();
create_newsgroups();

# Create the history database.
create_history();

__END__

##############################################################################
# Documentation
##############################################################################

=for stopwords
inn-purestart Allbery Skirvin

=head1 NAME

inn-purestart - Generate initial config files for a new server

=head1 SYNOPSIS

B<inn-purestart> [B<-h>] [B<-s> I<server>]

=head1 DESCRIPTION

Creates a default set of active, newsgroups, and history files in
F</var/lib/news>, based on the data from the server I<server> (defaults to
usenet.stanford.edu).

=head1 OPTIONS

=over 4

=item B<-h>, B<--help>

Print out this documentation.

=item B<-s> I<server>, B<--server>=I<server>

Name of the server to connect to to get default information.

=back

=head1 AUTHOR

Russ Allbery <eagle@eyrie.org> and Tim Skirvin.

=cut
