#!/usr/bin/perl 
use strict;
use warnings;
use File::Basename;
use File::Find;
use IO::All;

# For all directories in includes/
# look in .hxx,cxx,c,h files

# Fetch all the subdirs
my $dirname = "include";


# Add <boost> etc. to it, to  @includes
my @subdirs = map {basename $_} grep {-d} glob("$dirname/*");
push(@subdirs,"boost");

sub check_headers
{
	my ($dir,$file, @includes) = @_;
	open(my $fh,"+<",$file) or die "Couldn't open file $file $!\n";
	my @content = <$fh>;
	my $line;

	# seek to the first line, so we can replace then lines correctly
	seek $fh,0,0;
	foreach $line (@content){
		if($line =~ m/#include "(\w*)\//){
			if($1 ~~ @includes){
				print "line $line\n";
				$line =~ s/"/</;
				$line =~ s/"/>/;
				print $fh $line;
				print "line $line\n";
			}
			else {
					print $fh $line;
			}
			# -#include "com/sun/star/ucb/XWebDAVCommandEnvironment.hpp"
			# +#include <com/sun/star/task/XInteractionAbort.hpp>
			# -#include <DAVAuthListener.hxx>
			# +#include "DAVAuthListener.hxx"
		}
		# If a local file is defined global fix it
		elsif($line =~ /#include <((\w*)\.(hxx|h))>/){
			# check if file exists, then  it must be local so replace the <> to ""
			if(-e "$dir/$1" ){
				print "global header $line\n"
				$line =~ s/</"/g;
				$line =~ s/>/"/g;
				print $fh $line;
				print "converted to local header $line\n";
			}
			else {
				print $fh $line;
			}
		}
		else {
			print $fh $line;
		}
	}
	close($fh);
}

sub check_routine
{
	my ($dir) = @_; 
	opendir(DIR, $dir) or die "Program stopping, could't open directory \n";
	while(my $file = readdir(DIR)){
		if($file =~ m/\.(cxx|hxx|c|h)$/i ){
			check_headers($dir,"$dir/$file",@subdirs);
		}
	}
	closedir(DIR);
}


if(-d $ARGV[0]){
	my @directories = io->dir($ARGV[0])->All_Dirs;
	foreach my $dir (@directories){
		print "checking header files in $dir\n";
		check_routine($dir);
	}
}
else{
	print "$ARGV[0] isn't a directory\n";
}
