#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2004,2007 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 

use strict;
my $table;
my $key;
my $field;

#foreach(sort keys %ENV){ print "$_ $ENV{$_}\n"; }
while (<>)
{
	if (/#XCATVAR:([^#]+)#/)
	{
		s/#XCATVAR:([^#]+)#/envvar($1)/eg;
	}
	if (/#CSMVAR:([^#]+)#/)
	{
		s/#CSMVAR:([^#]+)#/envvar($1)/eg;
	}
	if (/#ENV:([^#]+)#/)
	{
		s/#ENV:([^#]+)#/envvar($1)/eg;
	}
	if (/#INCLUDE:([^#]+)#/)
	{
		s/#INCLUDE:([^#]+)#/includefile($1)/eg;
	}
	if (/#TABLE:([^:]+):([^:]+):([^#]+)#/)
	{
		s/#TABLE:([^:]+):([^:]+):([^#]+)#/tabdb($1,$2,$3)/eg;
	}
	if (/#COMMAND:([^#]+)#/)
	{
		s/#COMMAND:([^#]+)#/command($1)/eg;
	}
	# don't want to do this because then we can't have any comments!
	#	if(/#([^#]+)#/) {
	#		s/#([^#]+)#/envvar($1)/eg;
	#	}

	#	if(/#([^#]+)#/){
	#		s/#([^#]+)#/envvar($1)/eg;
	#	}
	print;
}

sub includefile
{
	my $file = shift;
	my $text = "";
	my $f    = $file;
	while ($f && (!-f $f))
	{

		# take off one letter
		$f =~ s/.?$//g;
	}

	if ($f eq "") { return "#INCLUDE:cannot open $file" }

	# pass include file through variable substitution:
	my $cmd = "$0 $f";
	$text = `$cmd`;

	#open(INCLUDE,$file) || \
	#	return "#INCLUDE:cannot open $file#";
	#
	#	while(<INCLUDE>) {
	#		$text .= "$_";
	#	}
	#
	#	close(INCLUDE);

	chomp($text);
	return ($text);
}

sub command
{
	my $command = shift;
	my $r;

	#	if(($r = `$command`) == 0) {
	#		chomp($r);
	#		return($r);
	#	}
	#	else {
	#		return("#$command: failed $r#");
	#	}

	$r = `$command`;
	chomp($r);
	return ($r);
}

sub envvar
{
	my $envvar = shift;

	if ($envvar =~ /^\$/)
	{
		$envvar =~ s/^\$//;
	}

	return ($ENV{$envvar});
}

sub tabdb
{
	my $table = "$ENV{XCATROOT}/etc/" . shift;
	my $key   = shift;
	my $field = shift;
	my @fields;
	my $all = 0;

	if ($key =~ /^\$/)
	{
		$key =~ s/^\$//;
		$key = $ENV{$key};
	}
	if ($field =~ /^\$/)
	{
		$field =~ s/^\$//;
		$field = $ENV{$field};
	}
	if ($field == '*')
	{
		$field = 1;
		$all   = 1;
	}

	--$field;

	if ($field < 0)
	{
		return "#TABLE:field not found#";
	}

	open(TAB, $table) || \return "#TABLE:cannot open $table#";

	while (<TAB>)
	{
		if (/^$key(\t|,| )/)
		{
			m/^$key(\t|,| )+(.*)/;
			if ($all == 1)
			{
				return "$2";
			}
			@fields = split(',', $2);
			if (defined $fields[$field])
			{
				return "$fields[$field]";
			}
			else
			{
				return "#TABLE:field not found#";
			}
		}
	}

	close(TAB);
	return "#TABLE:key not found#";
}

