#!/usr/bin/perl -w
#
# Zymonic Business Process and Information Management System
# Copyright Zednax Limited 2008 -
# For Authors and Changelog see the subversion history
use strict;

# Modules
use Zymonic::Config;
use Zymonic::DB;
use Zymonic::Auth;
use Zymonic::Locking;
$Zymonic::system  = '';
$Zymonic::session = '';

use Data::Dumper;

# Library path
BEGIN
{
    use Zymonic::Utils qw(clean death_handler debug);
    $main::SIG{__DIE__} = \&death_handler;
}

$Zymonic::system = clean( $ARGV[0], '_' );
my $log_file = clean( $ARGV[1], '-_./\\' );
unless ($Zymonic::system)
{
    print "build_documentation.pl [system] [logfile (optional)]\n";
    exit(1);
}

# make sure user understands the risks of running this
print 'This process has super-user permissions and should therefore only be '
  . 'run on systems where the data in the system can be legitimately shown to anyone who can read the manual.'
  . "\nProceed (Y/N)? ";
my $confirmation = <STDIN>;
chomp($confirmation);
unless ( $confirmation =~ /^y$/i )
{
    print "Documentation for $Zymonic::system not built.\n";
    exit(0);
}

if ($log_file)
{
    my $fh;
    if ($log_file)
    {
        if ( $log_file eq '-' )
        {
            open $fh, ">&STDOUT" or die "Unable to open STDOUT for writing";
        }
        else
        {
            open $fh, '>', $log_file or die "Unable to open $log_file for writing";
        }
        $Zymonic::Utils::debugfile = $fh;
    }
    else
    {
        $Zymonic::Utils::debugs_written = 1;
    }
}

print "Preparing to build documentation for $Zymonic::system.\n";
$Zymonic::ZCONFIG{$Zymonic::system} = Zymonic::Config->new(
    system_name => $Zymonic::system,
    config_dir  => "/etc/zymonic",
    ip_address  => '127.0.0.1',
    protocol    => 'http'
);

my $db = Zymonic::DB->new( config => $Zymonic::ZCONFIG{$Zymonic::system} );

# make it use manual auth
$Zymonic::ZCONFIG{$Zymonic::system}->{authtype} = 'Manual';
my $auth = Zymonic::Auth->new(
    config     => $Zymonic::ZCONFIG{$Zymonic::system},
    session    => undef,
    DB         => $db,
    ip_address => $Zymonic::ZCONFIG{$Zymonic::system}->ip_address,
);
$Zymonic::ZCONFIG{$Zymonic::system}->{auth} = $auth;

# load locking so we can grab lock specific messages for the manual
$Zymonic::locking = Zymonic::Locking->new( config => $Zymonic::ZCONFIG{$Zymonic::system}, auth => $auth, DB => $db, );

print "Building documentation for $Zymonic::system.\n";
$Zymonic::ZCONFIG{$Zymonic::system}->build_documentation($auth);
print "Built documentation for $Zymonic::system.\n";
