package Handy::Dandy::ScriptLoader;
use strict;
use Exporter;
use CGI;
use PCOM;
use Handy::Dandy::CGItools qw( :all );
use Website::AccessLog qw( pageview );
use Template::Parser qw( :all );
$Handy::Dandy::ScriptLoader::VERSION   = 1.05_8;   # 9/16/02, 12:22 am
@Handy::Dandy::ScriptLoader::ISA       = qw( Exporter );
@Handy::Dandy::ScriptLoader::EXPORT_OK = (
                            @PCOM::EXPORT_OK,
                           @Futils::EXPORT_OK,
                        @Handy::Dandy::EXPORT_OK,
                      @Template::Parser::EXPORT_OK,
                     @Website::AccessLog::EXPORT_OK,
                  @Handy::Dandy::CGItools::EXPORT_OK,
              qw( $com $pcom $cgi $tf $config $defaults ));
%Handy::Dandy::ScriptLoader::EXPORT_TAGS =
( 'minimal' => [     qw( $pcom   $com   $tf   $cgi )    ],
   'config' => [        qw( $config   $defaults )       ],
     'PCOM' => [            @PCOM::EXPORT_OK            ],
   'Futils' => [           @Futils::EXPORT_OK           ],
    'Dandy' => [        @Handy::Dandy::EXPORT_OK        ],
  'TParser' => [      @Template::Parser::EXPORT_OK      ],
'AccessLog' => [     @Website::AccessLog::EXPORT_OK     ],
'CGItools' => [   @Handy::Dandy::CGItools::EXPORT_OK   ],
      'all' => [ @Handy::Dandy::ScriptLoader::EXPORT_OK ],
'standard' => [ qw( $pcom $com $tf $cgi ),@Handy::Dandy::CGItools::EXPORT_OK ]
);

=pod

   AUTHOR
        -Tommy Butler, professional contractor and open source proponent

         Atrixnet™, for Internet Business Software®
            http://atrixnet.com
            6711 Forest Park Dr
            Dallas, TX
                 76001

   COPYRIGHT
         Copyright Tommy Butler. All rights reserved

   LISCENCE
         This software is free, and you may use and distribute it under the
         GNU GPL liscence.  If you modify the code for your own purposes
         please acknowledge its original author.

   BUGS
      Please report any of the following to me
         - bugs
         - interface inconsistencies
         - suggestions
         - comments
         - complaints
         - smart remarks

   HISTORY
      1.05_8      9/16/02, 12:22 am
                  added compulsory warning of process start and end for scripts
                  that use this module.  this should be an option, but for now
                  it is the default

=cut


# --------------------------------------------------------
# Constructor
# --------------------------------------------------------
sub new { bless({ }, shift(@_)) }


# ---------------------------------------------------------
# Prepare runtime environment, define global configuration
# ---------------------------------------------------------
use vars qw
   (
      $com   $pcom   $cgi   $tf
      $config   $defaults   $file
   );

# unfortunately, this has become necessary on sourceforge servers
BEGIN {

   ++$|;

   if ($ENV{'REQUEST_METHOD'}) {

      local(*EL); open(EL,'>>./logs/error.log'); open(STDERR,'>&EL');

      my($current) = select(STDERR); ++$|; select($current);
   }
}
BEGIN {

   $file = (caller(2))[1]||'nofile';

   warn(qq[$$ began at @{[scalar localtime]} in $file\012]);
}
END { warn(qq[$$ ended at @{[scalar localtime]} in $file\012\012]); }

# let's go!
INIT {

   $com = PCOM->new(1); $pcom = $com->main(); $$pcom{'PCOM'} = $com;

   # --------------------------------------------------------
   # pre-load special modules
   # --------------------------------------------------------

   # turns off stupid stdin hanging when run from the terminal
   # -seems to be the default in 5.005_03
   $CGI::DEBUG = 0; $CGI::DEBUG = 0; # used only once, my eye!

   # --------------------------------------------------------
   # initialize native class objects, register them with PCOM
   # --------------------------------------------------------
   $cgi  = CGI->new();
   $tf  = Template::Parser->new();

   $pcom->{'CGI'} = $cgi;
   $pcom->{'Template::Parser'} = $tf; $pcom->{'Futils'} = $tf;

   # NOTE:  Variables "$f" and "$pcom->{'Futils'}" implement a pseudo
   #        file utilities object and embedded object alias for backward
   #        compatibility with apps that still use "$f", and for apps
   #        using Template::Parser template files containing directives
   #        such as:
   #             "$pcom->{'Futils'}->..."
   #
   #        Usage of these vars is deprecated.
   #        They will be removed in next release

   # ----------------------------------
   # setup Directories
   # ----------------------------------
   use_once
      (
         $Handy::Dandy::ScriptLoader::configfile,
         $Handy::Dandy::ScriptLoader::defaultsfile,
         $Handy::Dandy::ScriptLoader::nohitlog,
      );

   $config     = $Handy::Dandy::ScriptLoader::configfile;
   $defaults   = $Handy::Dandy::ScriptLoader::defaultsfile;

   goto CONF_FILES_PARSED if ($config && $config eq q[?none]);

   $config   ||= qq[$pcom->{'PWD'}/$pcom->{'SCRIPT'}.config];
   $defaults ||= qq[$pcom->{'PWD'}/$pcom->{'SCRIPT'}.defaults];

   warn(q[RED ALERT!  I DON'T HAVE ANY CONFIG FILES!])
      and ++$Handy::Dandy::ScriptLoader::nohitlog
      and goto CONF_FILES_PARSED unless (-e $config);

   $config     = $tf->parse_file($config);
   $defaults   = $tf->parse_file($defaults);

   $config ||= ''; $defaults ||= '';

   # drop required argument markers
   $config =~ s/\*//go;

   # lose any trailing directory slashes in user config
   {
      local($^W)=0;
      $config =~ s/(?gosm)(((\\){1,})|((\/){1,}))(?:\])$\,/\]\,/;
   }

   $config     = eval($config);
   $defaults   = eval($defaults);

   foreach (keys(%{$defaults})) {

      my($section) = $_;

      if (not defined($config->{$section})) {

         $config->{$section} = $defaults->{$section};
      }

      foreach (keys(%{$defaults->{$section}})) {

         if (not defined($config->{$section}{$_})) {

            $config->{$section}{$_} = $defaults->{$section}{$_};
         }
      }
   }

   {  # closure.  no need to keep $rhtt around after this

      $$pcom{'PATH'}{'root html dir'}||='';
      $$pcom{'rhtt'} = '';

      # ! config sets receive cascading presidence from right to left
      foreach ( $config ) {

         my($cfg) = $_;

         foreach ( keys(%{ $cfg }) ) {

            my($section) = $_;

            foreach (reverse(sort(keys(%{ $cfg->{$section} })))) {

               my($key)       = $_;
               my($value)     = $cfg->{$section}{$_};
               my($default)   = $defaults->{$section}{$_};
               my($myrhtt)    = &rhtt();

               $value =~ s/(\/|\\)$//so;

               if (
                     defined($cfg->{$section}{$_})
                        and
                     length($cfg->{$section}{$_}) > 0
                  )
               {

                  $pcom->{$section}{$key} = $value;

                  if
                     (
                        $section eq 'DIR'
                           ||
                        $section eq 'PATH'
                           ||
                        $section eq 'PATH'
                     )
                  {
                     $pcom->{'PARSE_' . $section}{$key} = $value;
                     $pcom->{'PARSE_' . $section}{$key} =~ s/^.*?$myrhtt//;
                  }

                  $tf->set_token($key => $value);
               }
               else {

                  # yes, this is necessary where the defaults contain
                  # settings not present in the main configuration file
                  $pcom->{$section}{$key} = $default;
                  if
                     (
                        $section eq 'DIR'
                           ||
                        $section eq 'PATH'
                           ||
                        $section eq 'PATH'
                     )
                  {
                     $pcom->{'PARSE_' . $section}{$key} = $default;
                     $pcom->{'PARSE_' . $section}{$key} =~ s/^.*?$myrhtt//;
                  }

                  $tf->set_token($key => $default);
               }
            }
         }
      }
      sub rhtt {

         if (length($$config{'PATH'}{'root html dir'}) > 0) {

            return($$pcom{'rhtt'}) if (length($$pcom{'rhtt'}) > 0);

            $$pcom{'rhtt'} = qr/$$config{'PATH'}{'root html dir'}/;

            return($$pcom{'rhtt'})
         }

         return('')
      }
   }

   CONF_FILES_PARSED:

   $tf->set_object('name' => 'pcom', 'value' => $pcom);

   goto LOGGED_HIT if $Handy::Dandy::ScriptLoader::nohitlog;
   # --------------------------------------------------------
   # log stuff
   # --------------------------------------------------------
   $tf->write_file
      (
         'filename'  => $$pcom{'DIR'}{'logs'} . '/access.log',
         'mode'      => 'append',
         'content'   =>
            &pageview
               (
                  $tf->line_count($$pcom{'DIR'}{'logs'} . '/access.log'),

               ) . n,
      );

   LOGGED_HIT:
}
# - - -==// END ooPLoader CODE //==- - - - - - - - - - - -




# --------------------------------------------------------
# Handy::Dandy::ScriptLoader::DESTROY(), AUTOLOAD(), end class
# --------------------------------------------------------
sub DESTROY {} sub AUTOLOAD {}
1;