#!/perl -w
# NAME: inctrail.pl
# AIM: Given an in C/C++ file, check for #include "file" and #include <file>
# statements, and follow the trail, listing ALL included files, included ...
# 07/10/2007 - geoff mclane - http://geoffair.net/mperl/
###################################################################
use strict;
use warnings;
use File::Basename;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
	my @tmpsp = split(/\\/,$pgmname);
	$pgmname = $tmpsp[-1];
}
my $outfile = "temp.$pgmname.txt";
open_log($outfile);
prt( "$0 ... Hello, World ...\n" );
# debug
my $dbg1 = 0;	# show all config lines
my $dbg2 = 0;	# show 'Processing ...'
my $dbg3 = 0;	# show expansionss ...
my $dbg4 = 0;	# show vc8 BAT loading ...
my $dbg5 = 0;	# show folder about to be searched
my $dbg6 = 0;	# show INVALID INCLUDE folders ...
my $dbg7 = 0;	# show ALL paths TRIED ...

my @warnings = ();
###my $fin_file = 'C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\include\winbase.h';
###my $fin_file = 'C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\include\olectl.h';
my $fin_file = 'C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\include\http.h';
###my $fin_file = 'C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\include\windows.h';
##my $fin_file = 'C:\FG\FGCOM\xmlrpc-c1156\lib\abyss\src\file.c';
my @included = ();
my $inccount = 0;
my %byfolder = ();

my $cicnt = 0;
my $i = 0;
my $addcnt = 0;
my $oldcnt = 0;
my $newcnt = 0;
my $diffcnt = 0;
my @rel_folders = ( '..\..\..', '..\..\..\include' );
my ($fin_name, $fin_folder) = fileparse($fin_file);
my @include_folders = get_INCLUDE_Folders($fin_folder);
my $incfcnt = scalar @include_folders;
prt( "Got $incfcnt INCLUDE folders ...\n" );
process_file($fin_file);
$cicnt = scalar @included;
prt( "Got $cicnt from [$fin_file] ...\n" );
for ($i = 0; $i < $cicnt; $i++) {
	my $f = $included[$i][0];
	my $ord = $included[$i][1];
	$oldcnt = scalar @included;
	process_file($f);
	$newcnt = scalar @included;
	$diffcnt = $newcnt - $oldcnt;
	prt( "Got $diffcnt from [$f] ...\n" );
}
$cicnt = scalar @included;
while ($i < $cicnt) {
	my $f = $included[$i][0];
	my $ord = $included[$i][1];
	$oldcnt = scalar @included;
	process_file($f);
	$i++;
	$cicnt = scalar @included;
	$diffcnt = $cicnt - $oldcnt;
	prt( "Got $diffcnt from [$f] ...\n" );
}

prt( "\nGot TOTAL $cicnt includes from [$fin_file] ...\n" );
for ($i = 0; $i < $cicnt; $i++) {
	my $f = $included[$i][0];
	my $ord = $included[$i][1];
	prt( "$ord $f\n" );
	my ($nam, $dir) = fileparse($f);
	if (defined $byfolder{$dir}) {
		$byfolder{$dir} .= '*'.$nam;
	} else {
		$byfolder{$dir} .= $nam;
	}
}

prt( "\nBY FOLDER - TOTAL $cicnt includes from [$fin_file] ...\n" );
foreach my $dir (sort (keys(%byfolder))) {
	my $fnms = $byfolder{$dir};
	my @nms = split(/\*/,$fnms);
	my @nmss = sort @nms;
	prt( "$dir - ".scalar @nms." headers ...\n" );
	prt( join(", ", @nmss)."\n" );
}

close_log($outfile,1);
exit(0);

sub add_2_included {
	my ($fil, $in) = @_;
	my $lcfil = lc($fil);
	my $cicnt = scalar @included;
	for (my $j = 0; $j < $cicnt; $j++) {
		my $got = $included[$j][0];	# extract full file name
		my $lcgot = lc($got);		# to lower case
		if ($lcfil eq $lcgot) {		# if equal
			my $cin = $included[$j][2];	# get (list) of in
			my @carr = split(/\*/,$cin);	# split list
			my $fnd = 0;	# not found yet
			foreach my $tin (@carr) {	# process each in
				if ($tin eq $in) {
					$fnd = 1;	# found it
					last;
				}
			}
			if (!$fnd) {
				$cin .= '*'.$in;	# append a new 'in'
				$included[$j][2] = $cin;	# store this included in ...
			}
			return 0;				# do NOT add
		}
	}
	$inccount++;
	push(@included, [$fil, $inccount, $in]);
	return 1;
}

sub process_file {
	my ($inf) = shift;
	if (open INF, "<$inf") {
		my @lines = <INF>;
		close INF;
		my ($nm, $dir) = fileparse( $inf );
		my $lc = scalar @lines;
		prt( "\nGot $lc lines of [$inf] to process ...\n" );
		my $ic = 0;
		my $msg = '';
		my $rpt = 0;
		foreach my $line (@lines) {
			chomp $line;
			$line = trim_all($line);
			if ($line =~ /^#\s*include\s+(.+)\s*/) {
				$ic++;
				my $lbal = $1;
				my $ifil = '';
				if ($lbal =~ /<(.+)>/) {
					$ifil = $1;
				} elsif ($lbal =~ /"(.*)"/) {
					$ifil = $1;
				}
				if (length($ifil) == 0) {
					prt( "CHECK ME: line[$line] tail[$lbal] ...\n" );
					next;
				}
				my $fnd = 0;
				#$ifil =~ s/<//;
				#$ifil =~ s/>//;
				#$ifil =~ s/"//g;
				my $ff = $dir;
				$ff .= "\\" if !(substr($dir,-1) =~ /(\\|\/)/);
				$ff .= $ifil;
				$msg = "FAILED";
				$rpt = 0;
				prt( "Trying [$ff] LOCAL\n" ) if ($dbg7);
				if (-f $ff) {
					$msg = "OK";
					my $add = add_2_included( $ff, $inf );
					if ($add) {
						$msg .= " ADDED";
						$addcnt++;
					} else {
						$msg .= " REPEAT";
						$rpt = 1;
					}
					$fnd = 1;
				} else {
					# NOT found in LOCAL folder
					foreach my $rfld (@rel_folders) {
						my $ff1 = $dir;
						$ff1 .= "\\" if !(substr($ff1,-1) =~ /(\\|\/)/);
						$ff1 .= $rfld;
						$ff1 .= "\\" if !(substr($ff1,-1) =~ /(\\|\/)/);
						$ff1 .= $ifil;
						$ff1 = fix_rel($ff1);
						prt( "Trying [$ff1] RELATIVE\n" ) if ($dbg7);
						if (-f $ff1) {
							$ff = $ff1;
							$msg = "OK";
							my $add = add_2_included( $ff, $inf );
							if ($add) {
								$msg .= " ADDED";
								$addcnt++;
							} else {
								$msg .= " REPEAT";
								$rpt = 1;
							}
							$fnd = 1;
							last;
						}
					}
					if (!$fnd) {
						foreach my $ifld (@include_folders) {
							my $ff2 = $ifld;
							$ff2 .= "\\" if !(substr($ff2,-1) =~ /(\\|\/)/);
							$ff2 .= $ifil;
							prt( "Trying [$ff2] SYSTEM\n" ) if ($dbg7);
							if (-f $ff2) {
								$ff = $ff2;
								$msg = "OK";
								my $add = add_2_included( $ff, $inf );
								if ($add) {
									$msg .= " ADDED";
									$addcnt++;
								} else {
									$msg .= " REPEAT";
									$rpt = 1;
								}
								$fnd = 1;
								last;
							}
						}
					}
				}
				prt( "$addcnt:$ic $line - $ifil - [$ff] - $msg\n" ) if (!$rpt);
			}
		}
	} else {
		prt( "ERROR: Failed to open file [$inf] ...\n" );
	}
}

#####################################################################
######### getting the INCLUDE folders, either from the ENVIRONMENT
######### or from where MSVC8 stroes its stuff

sub load_vc8_cfg {
	my ($vc8c) = shift;
	my @v8_incs = ();
	if (open INF, "<$vc8c") {
		my @clns = <INF>;
		close INF;
		foreach my $cln (@clns) {
			chomp $cln;
			$cln = trim_all($cln);
			prt( "$cln\n" ) if ($dbg1);
			if ($cln =~ /include=\"(.+)\"/i) {
				my $iln = $1;
				my @vc8i = split(';',$iln);
				prt( "INCLUDE=[$iln]\n" );
				foreach my $itm (@vc8i) {
					push(@v8_incs, $itm);
				}
			}
		}
	} else {
		prt( "WARNING: can not open [$vc8c] ... $! ...\n" );
	}
	return @v8_incs;
}


sub load_vc8_bat {
	my ($vc8b) = shift;
	my @v8_folders = ();
	my @v8_incs = ();
	my %v8_hash = ();
	if (open INB, "<$vc8b") {
		my @lns = <INB>;
		close INB;
		foreach my $ln (@lns) {
			chomp $ln;
			$ln = trim_all($ln);
			if ($ln =~ /\@*SET\s+(.*)/) {
				my @arr = split(/=/,$1);
				my $sz = scalar @arr;
				if ($sz == 2) {
					my $ky = uc($arr[0]);
					my $val = $arr[1];
					$v8_hash{$ky} = $val;
					prt( "[$ky]=[$val]\n" ) if ($dbg4);
					if ($ky =~ /^VCINSTALLDIR$/i) {
						# got the INSTALL DIECTORY
						my $vc8_cfg = $val. "\\vcpackages\\vcprojectengine.dll.config";
						if (-f $vc8_cfg) {
							@v8_incs = load_vc8_cfg($vc8_cfg);
						} else {
							prt( "WARNING: [$vc8_cfg] does not exist ...\n" );
						}
					}

				} else {
					prt( "SET $1\n" );
				}
			}
		}
		foreach my $item (@v8_incs) {
			# expand
			if ($item =~ /.*\$\((.+)\).+/) {
				my $eit = uc($1);
				prt( "Item [$eit] in [$item] needs expansion ...\n" ) if ($dbg3);
				foreach my $key (keys %v8_hash) {
					if ($key eq $eit) {
						$item =~ s/\$\($key\)/$v8_hash{$key}\\/i;
						prt( "New item = [$item] ...\n" ) if ($dbg3);
						last;
					}
				}
			}
			push(@v8_folders, $item) if (length($item));
		}
	} else {
		prt( "WARNING: No open of [$vc8b] ... $! ...\n" );
	}
	return @v8_folders;
}


sub get_INCLUDE_Folders {
	my ($inf) = shift;	# this is the LOCAL folder
	my @fldrs1 = ();
	my @fldrs2 = ();
	my @fldrs3 = ();
	my @fldrsok = ();
	my $okcnt = 0;
	my $failed = 0;
	my $valcnt = 0;
	my $envstg = $ENV{"INCLUDE"};	# check INLCUDE in environment
	my $vc8_env = $ENV{"VS80COMNTOOLS"};
	my $psdk = $ENV{"PSDK_DIR"};
	my $dxsdk = $ENV{"DXSDK_DIR"};	# =C:\Program Files\Microsoft DirectX SDK (October 2006)\
	my $fdr = '';
	if (defined $envstg) {
		@fldrs1 = split(';',$envstg);
	} else {
		prt( "INLCUDE NOT found in environment ...\n" );
	}
	if (defined $vc8_env) {
		# we have MSVC8
		my $vc8_bat = $vc8_env . "vsvars32.bat";
		if (-f $vc8_bat) {
			push(@fldrs2, load_vc8_bat($vc8_bat));
		} else {
			prt( "WARNING: [$vc8_bat] not found ...\n" );
		}
	}
	if (defined $psdk) {
		push(@fldrs3,$psdk);
	} else {
		prt( "PSDK_DIR NOT found in environment ...\n" );
	}
	if (defined $dxsdk) {
		push(@fldrs3,$dxsdk);
	} else {
		prt( "DXSDK_DIR NOT found in environment ...\n" );
	}
	foreach $fdr (@fldrs1) {
		if (-d $fdr) {
			push(@fldrsok, $fdr) if (!same_folder($fdr,$inf));
			prt( "VALID [$fdr] ...\n" );
			$valcnt++;
		} else {
			prt( "Discarding [$fdr] as INVALID ...\n" ) if ($dbg6);
			$failed++;
		}
	}
	foreach $fdr (@fldrs2) {
		if (-d $fdr) {
			push(@fldrsok, $fdr) if (!same_folder($fdr,$inf));
			prt( "VALID [$fdr] ...\n" );
			$valcnt++;
		} else {
			prt( "Discarding [$fdr] as INVALID ...\n" ) if ($dbg6);
			$failed++;
		}
	}
	foreach $fdr (@fldrs3) {
		if (-d $fdr) {
			push(@fldrsok, $fdr) if (!same_folder($fdr,$inf));
			prt( "VALID [$fdr] ...\n" );
			$valcnt++;
		} else {
			prt( "Discarding [$fdr] as INVALID ...\n" ) if ($dbg6);
			$failed++;
		}
	}
	$okcnt = scalar @fldrsok;
	prt( "Found $okcnt ($valcnt) folders, and $failed failed ...\n" );
	return @fldrsok;
}

#####################################################################

sub unix_2_dos {
	my ($f) = shift;
	$f =~ s/\//\\/g;
	return $f;
}

sub fix_rel {
	my ($path) = shift;
	$path = unix_2_dos($path);	# ensure DOS separator
	my @a = split(/\\/, $path);	# split on DOS separator
	my $npath = '';
	my $wmsg = '';
	my $max = scalar @a;
	my @na = ();
	for (my $i = 0; $i < $max; $i++) {
		my $p = $a[$i];
		if ($p eq '.') {
			# ignore this
		} elsif ($p eq '..') {
			if (@na) {
				pop @na;	# discard previous
			} else {
				$wmsg = "WARNING: Got relative .. without previous!!! [$path]";
				prt( "$wmsg\n" );
				push(@warnings,$wmsg);
			}
		} else {
			push(@na,$p);
		}
	}
	foreach my $pt (@na) {
		$npath .= "\\" if length($npath);
		$npath .= $pt;
	}
	return $npath;
}


sub same_folder {
	my ($fd1, $fd2) = @_;
	$fd1 = unix_2_dos($fd1);
	$fd2 = unix_2_dos($fd2);
	$fd1 =~ s/\\$//;
	$fd2 =~ s/\\$//;
	my $lfd = length($fd1);
	if ($lfd != length($fd2)) {
		return 0;	# NOT same length
	}
	for (my $k = 0; $k < $lfd; $k++) {
		if (lc(substr($fd1,$k,1)) ne lc(substr($fd2,$k,1))) {
			return 0;	# different
		}
	}
	return 1;	# ARE THE DOS SAME
}

# eof - inctrail.pl
