#!/usr/bin/perl
# vim:ft=perl:cindent:ts=4:et:fdm=marker:cms=\ #\ %s
#
# Script to format all manual pages in one or more directories into the
# dwww cache (/var/cache/dwww).
#
# Usage: $0 directory ...
# Example: $0 /usr/share/man/man1 /usr/local/man3
# Example: $0 `manpath -q | tr : ' '`
#
# Lars Wirzenius
#
use strict;

use Debian::Dwww::Initialize;
use File::Find qw/find/;
use POSIX;

my $dwwwvars = &DwwwInitialize("/etc/dwww/dwww.conf");
my $dwww_cgi_user = $dwwwvars->{'DWWW_CGIUSER'};

my $opt_verbose = ($#ARGV >= 0) && ($ARGV[0] eq "-v" or $ARGV[0] eq "--verbose");
shift @ARGV if $opt_verbose;

if (! defined $ARGV[0]) {
    print STDERR "usage: $0 [-v|--verbose] directory ...\n";
    exit(1);
}

# Dup STDOUT as $stdout, and redirect STDOUT to /dev/null to avoid usage
# of shell with its '> /dev/null' in the system() call in CacheFile() below.
open(my $stdout, ">&STDOUT")  or die "Cannot dup STDOUT: $!\n";
open(STDOUT,'>','/dev/null')  or die "Cannot reopen STDOUT to /dev/null: $!\n";

my ($login,$pass,$uid,$gid) = getpwnam($dwww_cgi_user)
                              or die "Failed to get UID of user `$dwww_cgi_user': $!\n";

$>=$uid; $! == 0 or die "Cannot seteuid to $dwww_cgi_user($uid): $!\n";
$<=$uid; $! == 0 or die "Cannot setuid to $dwww_cgi_user($uid): $!\n";


&find( { wanted => \&CacheFile,
         follow_fast => 1 ,
         follow_skip => 2 },
         @ARGV );

sub CacheFile() {
    return unless -f _;
    my $file = $File::Find::name;

    print $stdout $file ."\n" if $opt_verbose;

    # Note the follwing system() call depends on STDOUT being
    # redirected to /dev/null.
    if (system("dwww-convert", "man", $file) != 0)
    {
        die "Failed to execute dwww-convert: $!\n" if $? == -1;
        # Perl by default blocks INT and QUIT signals while
        # executing system(), handle them manually here
        # in order to break the script.
        die "Interrupted\n" if ($? & 127) == POSIX::SIGINT;
        die "Quit\n" if ($? & 127) == POSIX::SIGQUIT;
        # Ignore other errors.
    }
}
