package Apt::Utils;

=head1 NAME

Apt::Utils - General utility module

=head1 AUTHOR

Robert Hanson, Aptegrity Inc.

=head1 SYNOPSYS

 use Apt::Utils qw/handleIncludes/;
 handleIncludes($filename, $base_dir);
 handleIncludes($html, $basedir);

=head1 METHODS

=head2 handleIncludes(<filename/html>, <base dir>)

This method takes either a filename or text and handles
includes in that document/text.  If the first argument is
a filename it will open that file and search for
#include and #exec directives.  If the first argument passed
is the actual text, it will handle directives in that file.

The function searches recursively, so you can embed an
include inside of another include.  The base directory
is used when handling virtual paths to includes.

The return value is the text with all of the includes
handled.

The method looks specifically for includes and exec's
in the following format:

<!--#include virtual="path"-->

There should be no spaces before or after the pound (#)
sign, and the path must be wrapped in double quotes (").
Also, the script currently handles "virtual" only for
includes, and of course "cmd" for exec statements.

=head1 TO-DO

1. It would be nice to allow both "virtual" and "file"
in the include directives.

2. The search should be broadened to allow a more general
syntax for the includes such as optional spaces before the
pound sign as well as the option to use either single
or double quotes.

=cut

use Exporter;
use vars qw(@EXPORT_OK @ISA);

@ISA = qw(Exporter);
@EXPORT_OK = qw(handleIncludes);


sub handleIncludes {
    #grab arguments
    my ($text,$basedir) = @_;

    # Check if it is a file
    if ( length($text) < 100 and -e $text ) {
	open IN, $text;
	$text = join('', <IN>);
	close IN;
    }

    while ( $text =~ /(<!--\#(include|exec)(.*?)-->)/ig ) {
	my ( $include, $action, $data ) = ( lc($1), $2, $3 );
	if ( $action eq 'include' ) {
	    if ( $data =~ /virtual="(.*?)"/ ) {
		my $file = $basedir.$1;
		$text =~ s/\Q$include\E/handleIncludes($file,$basedir)/e;
	    }       
	}
	elsif ( $action eq 'exec' ) {
	    if ( $data =~ /cmd="(.*?)"/ ) {
		my $file = $1;
		$text =~ s/\Q$include\E/`$file`/e; 
	    }       
	}
    }
    return $text;
}


1;

