#!/usr/bin/perl
#############################################################################
## Crytek Source File
## Copyright (C) 2007, Crytek Studios
##
## Creator: Sascha Demetrio
## Date: Apr 10, 2007
## Description: GNU-make based build system
#############################################################################

# Fix the GCC generated dependency files for Cygwin make.

use warnings;
use strict;

use Getopt::Std;

getopts('b:h');
our($opt_b, $opt_h);

if ($opt_h)
{
	print <<EOF
fixdeps.pl: Script for fixing compiler generated dependency files.
This script is part of the VisualStudio integration layer.
Synopsis:
  \$PERL fixdeps.pl -b BASEDIR <DEPS.orig >DEPS.fixed
Options:
-b BASEDIR
	The base directory in Windows notation (drive:path).  If this option is
	specified, then the base directory is translated to '/base/' in the fixed
	output file.
EOF
  ;
	exit 0;
}

my $basedir;
if ($opt_b)
{
	$basedir = $opt_b;
	$basedir =~ s#\\#/#g;
	$basedir =~ s#//+#/#g;
	#while ($basedir =~ s#[^/]+/\.\./##g) { }
	#$basedir =~ s#/[^/]+/\.\.$##;
}

our @lines = ( );
while (<STDIN>) { push @lines, $_; }
my $line;
foreach $line (@lines)
{
	$line =~ s#\\(\S)#/$1#g;
	$line =~ s#//+#/#g;
	#while ($line =~ s#[^/]+/\.\./##g) { }
	if (defined $basedir)
	{
		# Replace references to the basedir.
		my $index = index lc $line, lc $basedir;
		if ($index >= 0)
		{
			# Make sure the base dir is a prefix of a filename.
			if ($index > 0 and (substr $line, $index - 1, 1) ne ' ') { $index = -1; }
		}
		if ($index >= 0)
		{
			my $prefix = substr $line, 0, $index;
			my $suffix = substr $line, $index + length $basedir, -1;
			$line = $prefix . '/base/' . $suffix;
			$line =~ s#//+#/#g;
		}
	}
	if ($line =~ /^(\s+)([a-z]):\/(.*$)/i)
	{
		my $driveLetter = lc $2;
		$line = "$1/cygdrive/$driveLetter/$3\n";
	}
	elsif ($line =~ /^(\S+:\s+)([a-z]):\/(.*$)/i)
	{
		my $driveLetter = lc $2;
		$line = "$1/cygdrive/$driveLetter/$3\n";
	}
	if ($line =~ /^([a-z]):(.*$)/i)
	{
		my $driveLetter = lc $1;
		$line = "/cygdrive/$driveLetter$2\n";
	}
	$line =~ s/\s+$//;
	print "$line\r\n";
}

# vim:ts=2:sw=2

