#!/bin/bash

# $Id: generate 588 2009-11-23 13:57:24Z glx $

ROOT_DIR="`pwd`/.."
if ! [ -d "$ROOT_DIR/src" ]
then
	ROOT_DIR="`pwd`"
fi
if ! [ -d "$ROOT_DIR/src" ]
then
	echo "Can't find src dir, needed in order to make this run. Please go to either"
	echo " the project dir, or the root dir of a clean SVN checkout."
	exit 1
fi

generate_data()
{
ls -Rp "$ROOT_DIR/$1" | awk '
BEGIN {
	path = "";
	previous = ":"
	deep = 0
	tab = ""
}
/:/ {
	gsub("'$ROOT_DIR/'", "");
	gsub(":", "");
	if ($0 ~ previous) {
		tab = tab "	";
	} else {
		while (deep > 0) {
			print tab "		</Filter>";
			deep--;
			sub("/[^/]+$", "", previous);
			if ($0 ~ previous) break;
			sub("	", "", tab);
		}
	}
	previous = $0;
	gsub("/", "\\");
	path = $0;
	deep++;
	len = split($0, a, "\\");
	print tab "		<Filter";
	print tab "			Name=\"" a[len] "\"";
	print tab "			>";
	next;
}
/(c|h)$/ {
	print tab "			<File";
	print tab "				RelativePath=\"..\\" path "\\" $0 "\"";
	print tab "				>";
	split($0, a, ".");
	if (a[2] == "c") {
		print tab "				<FileConfiguration";
		print tab "					Name=\"Debug|Win32\"";
		print tab "					>";
		print tab "					<Tool";
		print tab "						Name=\"VCCLCompilerTool\"";
		print tab "						ObjectFile=\"$(IntDir)\\" path "\\\"";
		print tab "					/>";
		print tab "				</FileConfiguration>";
		print tab "				<FileConfiguration";
		print tab "					Name=\"Release|Win32\"";
		print tab "					>";
		print tab "					<Tool";
		print tab "						Name=\"VCCLCompilerTool\"";
		print tab "						ObjectFile=\"$(IntDir)\\" path "\\\"";
		print tab "					/>";
		print tab "				</FileConfiguration>";
	}
	print tab "			</File>";
}
END {
	while (deep > 0) {
		print tab "		</Filter>";
		sub("	", "", tab);
		deep--;
	}
}'
}

# Everything above the !!FILES!! marker
cat "$ROOT_DIR/projects/opendune.vcproj.in" | tr '\r' '\n' | awk '
	/^$/ { next }
	/!!FILES!!/ { stop = 1; }
	{
		if (stop == 0) { print $0 }
	}
' > "$ROOT_DIR/projects/opendune.vcproj"

# Get all source files
generate_data decompiled >> "$ROOT_DIR/projects/opendune.vcproj"
generate_data include >> "$ROOT_DIR/projects/opendune.vcproj"
generate_data src >> "$ROOT_DIR/projects/opendune.vcproj"

# Everything below the !!FILES!! marker
cat "$ROOT_DIR/projects/opendune.vcproj.in" | tr '\r' '\n' | awk '
	BEGIN { stop = 1; }
	/^$/ { next }
	/!!FILES!!/ { stop = 2; }
	{
		if (stop == 0) { print $0 }
		if (stop == 2) { stop = 0 }
	}
' >> "$ROOT_DIR/projects/opendune.vcproj"
