#!/usr/bin/perl
# ----------------------------------------------------------------------------
# This software is Copyright (C) 2007, All Rights Reserved
# ----------------------------------------------------------------------------
# This program is protected by local and international copyright laws. Any
# use of this program is subject to the the terms of the license agreement
# included as part of this distribution archive. Any other uses are strictly
# prohibited without the written permission of the Vendor and all
# other rights are reserved.
# -----------------------------------------------------------------------------
# Warning : Modifying this program violates your license agreement!
# -----------------------------------------------------------------------------

package IT::AutoLoader;

use strict;

# ignore "Use of inherited AUTOLOAD for non-method module::function() is deprecated" warnings
$SIG{__WARN__} = sub {
    return if $_[0] =~ /^Use of inherited AUTOLOAD for non-method /;
    warn @_;
};

# ---------------------------------------------------------------------------------
# Function    :
# Description : load IT modules and functions on demand at runtime
# Usage       : use IT::AutoLoader;
# ---------------------------------------------------------------------------------

sub UNIVERSAL::AUTOLOAD {

  # skip DESTROY methods
  if ($UNIVERSAL::AUTOLOAD =~ /::DESTROY$/) { return; }

  # skip non-IT modules
  unless ($UNIVERSAL::AUTOLOAD =~ /^IT::/) {
    die "Couldn't find module/function: $UNIVERSAL::AUTOLOAD\n";
    exit;
  }

  # get module and function names
  my $moduleAndFunction = $UNIVERSAL::AUTOLOAD;
  $moduleAndFunction    =~ /^(.*)::(.*?)$/ || die "couldn't get module and function name from: '$moduleAndFunction'\n";
  my $moduleName        = $1;
  my $functionName      = $2;

  # attempt to load IT:: modules
  my $returnValue = eval "require $moduleName";
  if ($@) {
    print "Content-type: text/plain\n\n";
    print "Error loading $moduleName\n\n$@\n";
    exit;
  }
  eval "import $moduleName";

  # check if function exists
  if (!defined &{$moduleAndFunction}) {
    die "Couldn't find $functionName() in $moduleName!\n";
  }

  # redirect to function
#  *$UNIVERSAL::AUTOLOAD       = sub { &IT:: };
#  goto &$UNIVERSAL::AUTOLOAD;    # Restart the new routine - use goto so we erase the stack frame
   goto \&{$moduleAndFunction};

  # display error for unknown modules
  print "Content-type: text/plain\n\n";
  print "Attempt to call $functionName in $moduleName failed.\n";
  print "AUTOLOAD Args: @_\n";
  exit;
}

# ----------------------------------------------------------------------------
# end of file
1;

