#!/usr/bin/perl
#    OpaL Perl Modules
#    Copyright (C) 2000,2007-2008  Ola Lundqvist <ola@inguza.com>
#
#    For full COPYRIGHT notice see the COPYING document.
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of either:
#
#	a) the GNU General Public License as published by the Free
#	Software Foundation; either version 1, or (at your option) any
#	later version, or
#
#	b) the "Artistic License" which comes with this Kit.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either
#    the GNU General Public License or the Artistic License for more details.
#
#
#    For more information take a look at the official homepage at:
#      http://inguza.com/software/opalmod
#    or contact the author at:
#      ola@inguza.com
#

package OpaL::action;

#use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
use POSIX qw(strftime);

require Exporter;

@ISA = qw(Exporter AutoLoader);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
@EXPORT = qw();
@EXPORT_OK = qw(pdebug exitlvl action cmdaction
		setDebugLevel setQuitLevel
		getDebugLevel getQuitLevel
		setErrorHandler);

# If you are using CVS/RCS this can be quite handy.
#$VERSION = do{my@r=q$Revision: 1.31 $=~/\d+/g;sprintf '%d.'.'%02d'x$#r,@r};

# If that is not what you want use this instead. Will be rewritten by
# create release.
my $version = '0.01';
$VERSION = $version;

###############################################################################
############################ PACKAGE GLOBALS ##################################
###############################################################################
# First exported ones (those in @EXPORT or @EXPORT_OK)
# No exportet variables.

# Then package other global ones. (not exported ones)
# Can be accessed through $OpaL::action::variablename
# No such too.

# All file-scooped variables must be created before any method that uses them.
my %ERRLVL =
    (
     1 => 'Critical',
     2 => 'Error',
     3 => 'Warning',
     4 => 'Message',
     5 => 'Debug'
     );

my $debuglvl = 3;
my $qlvl = 2;
my $errorHandler;

###############################################################################
########################### PRELOADED METHODS #################################
###############################################################################
# Preloaded methods go here.

###############################################################################
# Name:		setErrorHandler
# Description:	Sets the error handler function.
# Arguments:	$function (no arguments).
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2002-01-22
###############################################################################
sub setErrorHandler (&) {
    ($errorHandler) = @_;
}

###############################################################################
# Name:		setDebugLevel
# Description:	Sets the debug level to something.
# Arguments:	$level (1 to 5)
# Changes:	The localy scooped $debuglvl
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-05-01
###############################################################################
sub setDebugLevel ($) {
    $debuglvl = shift;
}

###############################################################################
# Name:		getDebugLevel
# Description:	returns the debug level.
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-07-06
###############################################################################
sub getDebugLevel () {
    return $debuglvl;
}

###############################################################################
# Name:		setQuitLevel
# Description:	Sets the quit level to something.
# Arguments:	$level (1 to 5)
# Changes:	The localy scooped $qlvl
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-05-01
###############################################################################
sub setQuitLevel ($) {
    $qlvl = shift;
}

###############################################################################
# Name:		getQuitLevel
# Description:	returns the quit level.
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-07-06
###############################################################################
sub getQuitLevel () {
    return $qlvl;
}

###############################################################################
# Name:		pdebug
# Description:	Prints a debug message and exit the program if the level are
#		to critical.
# Arguments:	$level, $message, [exit ref function]
# Uses:		exitlvl
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-05-01
#		2000-05-04	Minor modifications.
#		2000-06-27	Removed comment.
#		2002-01-22	Added exit ref function.
###############################################################################
sub pdebug ($$;&) {
    my ($lvl,$message,$ref) = @_;
    if ($debuglvl >= $lvl) {
	if ($message !~ /\n$/) {
	    $message = $message . "\n";
	}
	print ("$ERRLVL{$lvl}: $message");
    }
    exitlvl($lvl,$ref);
    return;
}

###############################################################################
# Name:		exitlvl
# Description:	Exit the program if the level are to critical.
# Arguments:	$level, [exit ref function]
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-05-01
#		2000-06-27	Added argument definition ($).
#		2002-01-22	Added exit ref function.
#               2009-03-16      Make sure to exit with error code and not 0.
###############################################################################
sub exitlvl ($;&) {
    my ($lvl, $ref) = @_;
    if ($qlvl >= $lvl) {
	if (! defined $ref) {
	    $ref = $errorHandler;
	}
	if (! defined $ref) {
	    print "EXIT: $lvl\n" if ($debuglvl >= $lvl);
	    exit $lvl;
	}
	if ($ref =~ /^$/ ||
	    $ref =~ /exit/i) {
	    print "EXIT: $lvl\n" if ($debuglvl >= $lvl);
	    exit $lvl;
	}
	elsif ("CODE" == ref $ref) {
	    &$ref;
	}
	elsif ("SCALAR" == ref $ref) {
	    &$ref;
	}
	else {
	    print "EXIT: $lvl\n" if ($debuglvl >= $lvl);
	    print("Really strange error handler: (".(ref $ref).") ".$ref);
	    exit $lvl;
	}
    }
}

###############################################################################
# Name:		action
# Description:	If eval is true then print out an error message.
# Arguments:	$eval, $message, [$errlvl default 2], [exit ref function]
# Uses:		pdebug
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-05-01
#		2000-06-27	Added a $ to make sure that errlvl is ok.
#				Added argument definition ($$:$).
#		2000-07-09	Layout changes and a bug fix. (From orat.)
#		2002-01-22	Added exit ref function.
###############################################################################
sub action ($$;$&) {
    my ($eval, $message, $errlvl,$ref) = @_;
    if ($errlvl =~ /^\s*$/) {
	$errlvl = 2;
    }
    if ($eval) {
	&pdebug($errlvl,"$message\n",$ref);
    }
    else {
	&pdebug(5,"$message\n",$ref);
    }
}

###############################################################################
# Name:		cmdaction
# Description:	If system(command) is erronious then call action.
# Arguments:	$command, $message, [$errorlevel default 2], [$quiet]
# Uses:		pdebug, action
# Author:	Ola Lundqvist <ola@inguza.com>
# Date:		2000-05-01
#		2000-05-19	Fixed quietcmd?
#		2000-06-27	Added a $ to make sure that errlvl is ok.
#				Added argument definition ($$:$).
#		2000-07-06	More readable argument getting.
#		2002-01-22	Better error handling.
###############################################################################
sub cmdaction ($$;$$&) {
    my ($cmd, $message, $errlvl, $qt, $ref) = @_;

    if ($errlvl =~ /^\s*$/) {
	$errlvl = 2;
    }
    if ($qt =~ /^\s*$/) {
	$qt = 0;
    }
    if ($message !~ /\n$/) {
	$message = $message . "\n";
    }
    &pdebug(4,$message);
    &pdebug(5,"CMD: $cmd\n");
    my $quietcmd = "";
    my $tcmd = $cmd;
    while ($tcmd =~ /\"[^\"]*\"/) {
	$tcmd =~ s/\"[^\"]*\"//;
    }
    if ($tcmd !~ />/) {
	$quietcmd = " \> /dev/null" if ($debuglvl == 4 || $qt == 1);
	$quietcmd = " \> /dev/null 2\>\&1" if ($debuglvl < 4);
	$quietcmd = "" if ($qt == 2);
    }
    &action(system("$cmd$quietcmd"),$message,$errlvl,$ref);
}

# Autoload methods go after =cut, and are processed by the autosplit program.

# Modules must return true.
1;
__END__

###############################################################################
############################# DOCUMENTATION ###################################
###############################################################################
# Below is the stub of documentation for your module. You better edit it!

=head1 NAME

OpaL::action - Perl extension for easier handling of what information that
should be presented when a action is made.

=head1 SYNOPSIS

  use OpaL::action qw(functionnames);

No functions or variables are exported automaticly so you have to specify
them here. 

=head1 DESCRIPTION

OpaL::action is a module to allow some better bugtracking and information to
be sent to the user/developer.

All functions are autoloaded so they will not be loaded into memory if you
have not used them before.

There are 5 different levels of the information/action.

=over 4

=item 1

critical

=item 2

error

=item 3

warning

=item 4

message

=item 5

debug

=back

=head1 FUNCTIONS

=over 4

=item B<setQuitLevel>

You can set on what errorlevel the program should exit if an error occur.
The default level is 2 and you canges it like this:

USAGE:
    C<setQuitLevel>(level);

=item B<setErrorHandler>

You can set an alternative error handler function (no arguments). The default
one is exit.

USAGE:
    C<setErrorHandler>(\funcname);

=item B<setDebugLevel>

You can set on what errorlevel the program should output messages if an error
occur. The debug level indicates what type of information that should be
presented to the user.
    
USAGE:
    C<setDebugLevel>(level);

=item B<getQuitLevel>

You can set on what errorlevel the program should exit if an error occur.

USAGE:
    $foo = C<getQuitLevel>;

=item B<getDebugLevel>

You can get the debuglevel on which the program should output messages, if an
error occurs.

USAGE:
    $foo = C<getDebugLevel>;

=item B<pdebug>

You can set on what errorlevel the program should exit if an error occur.
With the pdebug method you can present information and mark it with a
debuglevel using:

USAGE:
    C<pdebug>(level, "A sample informational text." [,funcref]);

=item B<action>

With this function you can handle and print a message if a function does
not work correctly.

It will exit the program and print a message with the error level before if
the action returns true and if the action_critic is lower or equal to the set
error level.

If the debug level is high enough it will present the message but without the
trailing error message.

USAGE:
    C<action>(some_action,
           "A sample informational text about the action.",
            how_critical [,funcref]);

The last parameter (how_critical) is optional.

=item B<cmdaction>

Actually the same as B<action> with the difference that it executes a external
command instead.

It is almost identical to action(system"a command to execute", ...);

USAGE:
    C<cmdaction>("a command to execute.",
              "A sample informational text about the action.",
               how_critical,
	       how_quiet [,funcref]);

The two last parameter (how_critical) is optional.
The last parameter tells how quiet the executing command should be:
  0 - extremely quiet (ie: >& /dev/null)
  1 - quiet           (ie: >& /dev/null)
  2 - everything sent to stdout.
=back

=head1 AUTHOR

Ola Lundqvist <ola@inguza.com>

=head1 SEE ALSO

perl(1).

=cut

###############################################################################
########################### AUTOLOAD METHODS ##################################
###############################################################################
