#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(getcwd);

sub find_output($);
sub gendep($);
sub dep_cpp($$);
sub dep_dir($);
sub run();

my %f2dep;

run;
exit 0;

sub run() {
	my $build = $ENV{BUILDPATH};
	mkdir $build;
	chdir $build or die "Could not open build directory: $!";
	symlink "$ENV{SOURCEPATH}/include", 'include';
	mkdir $_ for qw/bin modules obj/;
# BSD make has a horribly annoying bug resulting in an extra chdir of the make process
# Create symlinks to work around it
	symlink "../$_", "obj/$_" for qw/bin modules obj/;

	$build = getcwd();
	open MAKE, '>real.mk' or die "Could not write real.mk: $!";
	chdir "$ENV{SOURCEPATH}/src";

	print MAKE <<END;
# DO NOT EDIT
# Autogenerated by calcdep
VPATH = \$(SOURCEPATH)/src

all: inspircd commands modules

END
	my(@core_deps, @cmdlist, @modlist);
	for my $file (<*.cpp>, <modes/*.cpp>, <socketengines/*.cpp>, "threadengines/threadengine_pthread.cpp") {
		my $out = find_output $file;
		dep_cpp $file, $out;
		next if $file =~ m#^socketengines/# && $file ne "socketengines/$ENV{SOCKETENGINE}.cpp";
		push @core_deps, $out;
	}

	for my $file (<commands/*.cpp>) {
		my $out = find_output $file;
		dep_cpp $file, $out;
		push @cmdlist, $out;
	}

	opendir my $moddir, 'modules';
	for my $file (sort readdir $moddir) {
		next if $file =~ /^\./;
		if (-e "modules/extra/$file" && !-l "modules/$file") {
			# Incorrect symlink?
			print "Replacing symlink for $file found in modules/extra\n";
			rename "modules/$file", "modules/$file~";
			symlink "extra/$file", "modules/$file";
		}
		if ($file =~ /^m_/ && -d "modules/$file" && dep_dir "modules/$file") {
			mkdir "$build/obj/$file";
			push @modlist, "modules/$file.so";
		}
		if ($file =~ /^m_.*\.cpp$/) {
			my $out = find_output "modules/$file";
			dep_cpp "modules/$file", $out;
			push @modlist, $out;
		}
	}
	
	my $core_mk = join ' ', @core_deps;
	my $cmds = join ' ', @cmdlist;
	my $mods = join ' ', @modlist;
	print MAKE <<END;

bin/inspircd: $core_mk
	\$(RUNCC) -o \$\@ \$(CORELDFLAGS) \$(LDLIBS) \$^ \$>

inspircd: bin/inspircd

commands: $cmds

modules: $mods

.PHONY: inspircd commands modules

END
}

sub find_output($) {
	my $file = shift;
	my($path,$base) = $file =~ m#^((?:.*/)?)([^/]+)\.cpp# or die "Bad file $file";
	if ($path eq 'modules/' || $path eq 'commands/') {
		return "modules/$base.so";
	} elsif ($path eq '' || $path eq 'modes/' || $path =~ /^[a-z]+engines\/$/) {
		return "obj/$base.o";
	} elsif ($path =~ m#modules/(m_.*)/#) {
		return "obj/$1/$base.o";
	} else {
		die "Can't determine output for $file";
	}
}

sub gendep($) {
	my $f = shift;
	my $basedir = $f =~ m#(.*)/# ? $1 : '.';
	return $f2dep{$f} if exists $f2dep{$f};
	$f2dep{$f} = '';
	my %dep;
	my $link = readlink $f;
	if (defined $link) {
		$link = "$basedir/$link" unless $link =~ m#^/#;
		$dep{$link}++;
	}
	open my $in, '<', $f or die "Could not read $f";
	while (<$in>) {
		if (/^\s*#\s*include\s*"([^"]+)"/) {
			my $inc = $1;
			next if $inc eq 'inspircd_version.h' && $f eq '../include/inspircd.h';
			my $found = 0;
			for my $loc ("$basedir/$inc", "../include/$inc") {
				next unless -e $loc;
				$found++;
				$dep{$_}++ for split / /, gendep $loc;
				$loc =~ s#^\.\./##;
				$dep{$loc}++;
			}
			if ($found == 0 && $inc ne 'inspircd_win32wrapper.h') {
				print STDERR "WARNING: could not find header $inc for $f\n";
			} elsif ($found > 1 && $basedir ne '../include') {
				print STDERR "WARNING: ambiguous include $inc in $f\n";
			}
		}
	}
	close $in;
	$f2dep{$f} = join ' ', sort keys %dep;
	$f2dep{$f};
}

sub dep_cpp($$) {
	my($file, $out) = @_;
	gendep $file;

	print MAKE "$out: $file $f2dep{$file}\n";
	print MAKE "\t@\$(SOURCEPATH)/make/unit-cc.pl \$(VERBOSE) \$\@ \$< \$>\n";
}

sub dep_dir($) {
	my($dir) = @_;
	my @ofiles;
	opendir DIR, $dir;
	for my $file (sort readdir DIR) {
		next unless $file =~ /(.*)\.cpp$/;
		my $ofile = find_output "$dir/$file";
		dep_cpp "$dir/$file", $ofile;
		push @ofiles, $ofile;
	}
	closedir DIR;
	if (@ofiles) {
		my $ofiles = join ' ', @ofiles;
		print MAKE "$dir.so: $ofiles\n\t\$(RUNCC) \$(PICLDFLAGS) -o \$\@ \$^ \$>\n";
		return 1;
	} else {
		return 0;
	}
}

