#!/usr/bin/awk

function which(c,path) {
	cmd = "test -x " c;

	if (system(cmd)==0) {
		return c;
	} 

	sub(/\/.*\//,"",c);
  for (dir in path) {
			cmd = "test -x " path[dir] "/" c;
			if (system(cmd)==0) {
					return path[dir] "/" c;
			} 
	}


	return c;
}

# used to replace "use lib utils.pm" with "use lib @libexecdir"
#
function led() {
	led1 = "@libexecdir@";
	led2 = "@exec_prefix@";
	led3 = "@prefix@";
	if ( match(led1, /^\$\{exec_prefix\}/ ) != 0 ) {
		return "\"" led3 "/libexec\" " ;
	
	}
	return "\"" led1 "\"" ;
}

BEGIN {
	split(ENVIRON["PATH"] ":/sbin:/usr/sbin",path,/:/);

}

# Plugin revision
/@NP_VERSION@/ {sub(/@NP_VERSION@/,ENVIRON["NP_VERSION"]);}

# scripting language (first line)

/^#! ?\/.*\/python/ {sub(/^#! ?\/.*\/python/,"#! @PYTHON@");}
/^#! ?\/.*\/perl/ {sub(/^#! ?\/.*\/perl/,"#! @PERL@");}
/^#! ?\/.*\/[a-z]{0,2}awk/ {sub(/^#! ?\/.*\/[a-z]{0,2}awk/,"#! @AWK@");}
/^#! ?\/.*\/sh/ {sub(/^#! ?\/.*\/sh/,"#! @SHELL@");}

# If a script contains a reference to a fully qualified command,
# subst will replace the fully qualified command with whatever is
# returned from the which subroutine. run before changes to INC to add libexecdir
# FIXME: Prepend executables with a substitution keyword instead.
#
/^[^#]/ && /(\/.*)?\/(bin|sbin|lib|libexec)\// {
	match($0,/(\/.*)?\/(bin|sbin|lib|libexec)\/[-_a-zA-Z0-9]+/);
	c=substr($0,RSTART,RLENGTH);
	sub(c,which(c,path));
}

# add to libexecdir to INC for perl utils.pm
/^use/ { if (/lib/) { if (/utils.pm|"."/ ) {sub(/utils.pm|"."/,led() )} } }


# Trusted path mechanism (deprecated)

/^[ \t]*\$ENV[ \t]*\{[ \t'"]*PATH[ \t"']*\}[ \t]*=/ {
	sub(/\=[ \t]*['"][^"']+["']/,"='@with_trusted_path@' # autoconf-derived");
}

/^[\t ]*(export[\t ]*)?PATH[\t ]*=['"]+.+["']$/ {
	sub(/\=.*$/,"='@with_trusted_path@' # autoconf-derived");
}

{
	print;
}