#!/usr/bin/perl
# vim:ft=perl:cindent:ts=8: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
# "@(#)dwww:$Id: dwww-format-man 511 2009-01-10 23:59:42Z robert $"
#
use strict;

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

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


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 },       
         @ARGV );


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

        print "$file\n" if $opt_verbose;
        system("dwww-convert man \"$file\" > /dev/null");
}        
