use strict;


my $ryba=<<'END_OF_RYBA';
use strict;
use DBI;
use CGI;
use HTML::Template::Pro;
use Log::Log4perl;
use Crypt::CBC;
use Storable qw/freeze thaw/;
use Data::Dumper;

our($dbh, $q, $log, $curruser);
our(%rootlvl, %userlvl);

our($logconfigstr)=<<'EOL';
        log4perl.rootLogger = DEBUG,LOGFILE
    
        log4perl.appender.LOGFILE = Log::Log4perl::Appender::File
        log4perl.appender.LOGFILE.filename = c:/work/perl/error.log
        log4perl.appender.LOGFILE.mode = append
   
        log4perl.appender.LOGFILE.layout = PatternLayout
        log4perl.appender.LOGFILE.layout.ConversionPattern = [%r] %F %L %c - %m%n
EOL

eval{
  main();
};

sub dnice{
 print "Content-type: text/html\n\n";
 my($msg) = @_;
 $log->fatal($msg);
 print $msg;
 die;
}

sub main{
  Log::Log4perl->init_once(\$logconfigstr);
  $log = Log::Log4perl->get_logger('');
  $dbh ||= DBI->connect('dbi:mysql:help','','',{RaiseError => 1});
  $q = new CGI;
  checkuser();

  my $action;
  $action = $q->param('action') || $q->param('action','toc');
  dnice('No such action') if $action !~ /^(\w+)$/;
  $action = 'ext_' . $1;
  my($hdrs, $result, $noncacheable);

  dnice 'No access' if !accessallowed($action, $curruser);

  $log->debug(sub { Dumper $curruser });
  $log->debug("Entering $action");
  $log = Log::Log4perl->get_logger($action);
  eval{
    ($hdrs, $result, $noncacheable) = __PACKAGE__->$action;
  };
  dnice($@) if $@;
  $log = Log::Log4perl->get_logger('');
  $log->debug("Leaving $action");
  print $q->header( -type => 'text/html',
                    -charset => 'cp1251',
		    @$hdrs);
  !$result && return;
  !ref $result && print($result) && return;
  
  my $tmpl = HTML::Template::Pro->new( filename          => $q->param('action') . '.tmpl',
				       path              => 'c:/work/perl/tmpl',
				       associate         => $q,
				       loop_context_vars => 1,
				       global_vars       => 1
				       );
  $tmpl->param(@$result);
  print $tmpl->output();
}

####################################################################################
#################################### ACTIONS #######################################
####################################################################################

END_OF_RYBA

mkdir 'tmpl' or die "Cannot create tmpl:$!";
for my $action (@ARGV){
  $ryba .=<<"END_OF_ACTION"; 
####################################################################################
sub ext_${action}{
    return [],
           [];
}

END_OF_ACTION

open FILE, ">tmpl/$action.tmpl" or die "Cannot open file tmpl/$action.tmpl : $!";
close FILE;
}
open FILE, ">main.pl" or die "Cannot open main.pl : $!";
print FILE $ryba;
close FILE;