#!/usr/bin/perl -w
######################################################################
#
# Synchronizes Qt header files - internal Trolltech tool.
#
# Copyright (C) 1997-%THISYEAR% by Trolltech AS.  All rights reserved.
#
######################################################################

# use packages -------------------------------------------------------
use File::Basename;
use File::Path;
use Cwd;
use Config;
use strict;

die "syncqt: QTDIR not defined" if ! $ENV{"QTDIR"}; # sanity check

# global variables
my $isunix = 0;
my $basedir = $ENV{"QTDIR"};
$basedir =~ s=\\=/=g;
my %modules = ( # path to module name map
	    "QtGui" => "$basedir/src/gui",
	    "QtOpenGL" => "$basedir/src/opengl",
	    "QtCore" => "$basedir/src/core",
	    "QtXml" => "$basedir/src/xml",
	    "QtSql" => "$basedir/src/sql",
	    "QtNetwork" => "$basedir/src/network",
	    "QtCanvas" => "$basedir/src/canvas",
	    "Qt3Compat" => "$basedir/src/compat",
	    "ActiveQt" => "$basedir/extensions/activeqt/container;$basedir/extensions/activeqt/control",
	    "QtMotif" => "$basedir/extensions/motif/src",
	    "QtNsPlugin" => "$basedir/extensions/nsplugin/src",
);
$modules{"QtCore"} .= ";mkspecs" . $ENV{"MKSPEC"} if defined $ENV{"MKSPEC"};

# global variables (modified by options)
my $module = 0;
my $showonly = 0;
my $remove_stale = 1;
my $force_win = 0;
my $force_relative = 0;
my @modules_to_sync;
$force_relative = 1 if ( -d "/System/Library/Frameworks" );
my $includedir = $basedir . "/include";
$includedir =~ s=\\=/=g;

# functions ----------------------------------------------------------

######################################################################
# Syntax:  showUsage()
# Params:  -none-
#
# Purpose: Show the usage of the script.
######################################################################
sub showUsage
{
    print "$0 usage:\n";
    print "  -remove-stale         Removes stale headers              (default: " . ($remove_stale ? "yes" : "no") . ")\n";
    print "  -relative             Force relative symlinks            (default: " . ($force_relative ? "yes" : "no") . ")\n";
    print "  -windows              Force platform to Windows          (default: " . ($force_win ? "yes" : "no") . ")\n";
    print "  -showonly             Show action but not perform        (default: " . ($showonly ? "yes" : "no") . ")\n";
    print "  -outdir <PATH>        Specify include directory for sync (default: $includedir)\n";
    print "  -help                 This help\n";
    exit 0;
}

######################################################################
# Syntax:  checkUnix()
# Params:  -none-
#
# Purpose: Check if script runs on a Unix system or not, and sets the
#          global variable $isunix to the result. Cygwin systems are
#          _not_ ounted as Unix systems.
######################################################################
sub checkUnix {
    my ($r) = 0;
    if ( $force_win != 0) {
        return 0;
    } elsif ( -f "/bin/uname" ) {
        $r = 1;
        (-f "\\bin\\uname") && ($r = 0);
    } elsif ( -f "/usr/bin/uname" ) {
        $r = 1;
        (-f "\\usr\\bin\\uname") && ($r = 0);
    }
    if($r) {
        $_ = $Config{'osname'};
        $r = 0 if( /(ms)|(cyg)win/i );
    }
    return $r;
}

######################################################################
# Syntax:  shouldMasterInclude(iheader)
# Params:  iheader, string, filename to verify inclusion
#
# Purpose: Determines if header should be in the master include file
######################################################################
sub shouldMasterInclude {
    my ($iheader) = @_;
    return 0 if($iheader =~ /_/);
    return 0 if($iheader =~ /qconfig/);
    if(open(F, "<$iheader")) {
        while(<F>) {
	    chomp;
	    return 0 if(/^\#pragma qt_no_master_include$/);
	}
	close(F);
    } else {
	return 0;
    }
    return 1;
}

######################################################################
# Syntax:  classNames(iheader)
# Params:  iheader, string, filename to parse for classname "symlinks"
#
# Purpose: Scans through iheader to find all classnames that should be
#          synced into library's include structure
######################################################################
sub classNames {
    my @ret;
    my ($iheader) = @_;
    if(basename($iheader) eq "qglobal.h") {
	push @ret, "QtGlobal";
    } elsif(basename($iheader) eq "qalgorithms.h") {
	push @ret, "QtAlgorithms";
    }

    my $parsable = "";
    if(open(F, "<$iheader")) {
        while(<F>) {
            my $line = $_;
            chomp $line;
            if($line =~ /^\#/) {
                if($line =~ /\\$/) {
                    while($line = <F>) {
                        chomp $line;
                        last unless($line =~ /\\$/);
                    }
                } else {
                    $line = 0;
                }
            }
            $line =~ s,//.*$,,; #remove c++ comments
            $parsable .= $line if($line);
        }
        close(F);
    }

    my $last_definition = 0;
    for(my $i = 0; $i < length($parsable); $i++) {
        my $definition = 0;
        my $character = substr($parsable, $i, 1);
        if($character eq "/" && substr($parsable, $i+1, 1) eq "*") { #I parse like this for greedy reasons
            for($i+=2; $i < length($parsable); $i++) {
                my $end = substr($parsable, $i, 2);
                if($end eq "*/") {
                    $last_definition = $i+2;
                    $i++;
                    last;
                }
            }
        } elsif($character eq "{") {
            my $brace_depth = 1;
            my $block_start = $i + 1;
          BLOCK: for($i+=1; $i < length($parsable); $i++) {
              my $ignore = substr($parsable, $i, 1);
              if($ignore eq "{") {
                  $brace_depth++;
              } elsif($ignore eq "}") {
                  $brace_depth--;
                  unless($brace_depth) {
                      for(my $i2 = $i+1; $i2 < length($parsable); $i2++) {
                          my $end = substr($parsable, $i2, 1);
                          if($end eq ";" || $end ne " ") {
                              $definition = substr($parsable, $last_definition, $block_start - $last_definition) . "}";
                              $i = $i2 if($end eq ";");
                              $last_definition = $i + 1;
                              last BLOCK;
                          }
                      }
                  }
              }
          }
        } elsif($character eq ";") {
            $definition = substr($parsable, $last_definition, $i - $last_definition + 1);
            $last_definition = $i + 1;
        }
        if($definition) {
            my $symbol = 0;
            if($definition =~ m/^ *typedef *.*\(\*([^\)]*)\)\(.*\);$/) {
                $symbol = $1;
            } elsif($definition =~ m/^ *typedef +(.*) +([^ ]*);$/) {
                $symbol = $2;
            } elsif($definition =~ m/^ *(template *<.*> *)?(class|struct) +([^ ]* +)?([^ <]+) ?(<[^>]*> ?)?((,|:) *(public|private) *.*)? *\{\}$/) {
                $symbol = $4;
            }
            if($symbol && $symbol =~ /^Q/) {
		push @ret, $symbol;
            }
        }
    }
    return @ret;
}

######################################################################
# Syntax:  syncHeader(header, iheader)
# Params:  header, string, filename to create "symlink" for
#          iheader, string, destination name of symlink
#
# Purpose: Syncronizes header to iheader
######################################################################
sub syncHeader {
    my ($header, $iheader) = @_;
    $iheader =~ s=\\=/=g;
    $header =~ s=\\=/=g;
    if(-e "$iheader") {
        my $iheader_no_basedir = $iheader;
        $iheader_no_basedir =~ s,^$basedir/?,,;

	unless(-e "$header") {
	    my $header_dir = dirname($header);
	    mkpath $header_dir, 0777;

	    #write it
	    my $iheader_out = fixPaths($iheader, $header);
	    open HEADER, ">$header" || die "Could not open $header for writing!\n";
	    print HEADER "#include \"$iheader_out\"\n";
	    close HEADER;
	    return 1;
	}
    }
    return 0;
}

######################################################################
# Syntax:  fixPaths(file1, file2)
# Params:  file1, string, filepath to be made relative to POO
#          file2, string, filepath for point of origin (POO)
#
# Purpose: file1 is made relative (if possible) of file2 and returned
######################################################################
sub fixPaths {
    my ($file1, $file2) = @_;
    $file1 =~ s=\\=/=g;
    $file2 =~ s=\\=/=g;

    #setup
    my $ret = $file1;
    my $file1_dir = $file1;
    $file1_dir = dirname($file1) unless(-d "$file1_dir");
    my $file2_dir = $file2;
    $file2_dir = dirname($file2) unless(-d "$file2_dir");
    return basename($file1) if("$file1" eq "$file2");
    if($file1_dir eq ".") {
        $file1_dir = getcwd();
        $file1_dir =~ s=\\=/=g;
    }
    $file1_dir =~ s,/cygdrive/([a-zA-Z])/,$1:,g;
    if($file2_dir eq ".") {
        $file2_dir = getcwd();
        $file2_dir =~ s=\\=/=g;
    }
    $file2_dir =~ s,/cygdrive/([a-zA-Z])/,$1:/,g;

    #guts
    my $match_dir = 0;
    for(my $i = 1; $i < length($file1_dir); $i++) {
        my $slash = index($file1_dir, "/", $i);
        last if($slash == -1);
        my $tmp = substr($file1_dir, 0, $slash);
        last unless($file2_dir =~ m,^$tmp/,);
        $match_dir = $tmp;
        $i = $slash;
    }
    if($match_dir) {
        my $after = substr($file2_dir, length($match_dir));
        my $count = ($after =~ tr,/,,);
        my $dots = "";
        for(my $i = 0; $i < $count; $i++) {
            $dots .= "../";
        }
        $ret =~ s,^$match_dir,$dots,;
    }
    $ret =~ s,/+,/,g;
    return $ret;
}

######################################################################
# Syntax:  symlinkFile(file,ifile)
# Params:  file, string, filename to create "symlink" for
#          ifile, string, destination name of symlink
#
# Purpose: File is symlinked to ifile (or copied if filesystem doesn't
#          support symlink)
######################################################################
sub symlinkFile
{
    my ($file,$ifile, $fast,$copy,$knowdiff,$filecontents,$ifilecontents) = @_;

    if ($isunix) {
        print "symlink created for $file ";
        if ( $force_relative && ($ifile =~ /^$basedir/)) {
            my $t = getcwd();
            my $c = -1;
            my $p = "../";
            $t =~ s-^$basedir/--;
            $p .= "../" while( ($c = index( $t, "/", $c + 1)) != -1 );
            $file =~ s-^$basedir/-$p-;
            print " ($file)\n";
        }
        print "\n";
        symlink($file, $ifile);
        return;
    } else {
        # Bi-directional synchronization
        open( I, "< " . $file ) || die "Could not open $file for reading";
        local $/;
        binmode I;
        $filecontents = <I>;
        close I;
        if ( open(I, "< " . $ifile) ) {
            local $/;
            binmode I;
            $ifilecontents = <I>;
            close I;
            $copy = (stat($ifile))[9] <=> (stat($file))[9];
            $knowdiff = 0,
        } else {
            $copy = -1;
            $knowdiff = 1;
        }
    }

    if ( $knowdiff || ($filecontents ne $ifilecontents) ) {
        if ( $copy > 0 ) {
            open(O, "> " . $file) || die "Could not open $file for writing";
            local $/;
            binmode O;
            print O $ifilecontents;
            close O;
            print "$file written\n";
        } elsif ( $copy < 0 ) {
            open(O, "> " . $ifile) || die "Could not open $ifile for writing";
            local $/;
            binmode O;
            print O $filecontents;
            close O;
            print "$ifile written\n";
        }
    }
}

######################################################################
# Syntax:  findFiles(dir, match, descend)
# Params:  dir, string, directory to search for name
#          match, string, regular expression to match in dir
#          descend, integer, 0 = non-recursive search
#                            1 = recurse search into subdirectories
#
# Purpose: Finds files matching a regular expression.
#
# Examples:
#   findFiles("/usr","\.cpp$",1)  - finds .cpp files in /usr and below
#   findFiles("/tmp","^#",0)      - finds #* files in /tmp
######################################################################
sub findFiles {
    my ($dir,$match,$descend) = @_;
    my ($file,$p,@files);
    local(*D);
    $dir =~ s=\\=/=g;
    ($dir eq "") && ($dir = ".");
    if ( opendir(D,$dir) ) {
        if ( $dir eq "." ) {
            $dir = "";
        } else {
            ($dir =~ /\/$/) || ($dir .= "/");
        }
        foreach $file ( readdir(D) ) {
            next if ( $file  =~ /^\.\.?$/ );
            $p = $file;
            ($file =~ /$match/) && (push @files, $p);
            if ( $descend && -d $p && ! -l $p ) {
                push @files, &findFiles($p,$match,$descend);
            }
        }
        closedir(D);
    }
    return @files;
}

# --------------------------------------------------------------------
# "main" function
# --------------------------------------------------------------------

while ( @ARGV ) {
    my $var = 0;
    my $val = 0;

    #parse
    my $arg = shift @ARGV;
    if ("$arg" eq "-h" || "$arg" eq "-help" || "$arg" eq "?") {
	$var = "show_help";
	$val = "yes";
    } elsif("$arg" eq "-o" || "$arg" eq "-outdir") {
	$var = "output";
	$val = shift @ARGV;
    } elsif("$arg" eq "-showonly" || "$arg" eq "-remove-stale" || "$arg" eq "-windows" || "$arg" eq "-relative") {
	$var = substr($arg, 1);
	$val = "yes";
    } elsif("$arg" =~ /^-no-(.*)$/) {
	$var = $1;
	$val = "no";
	#these are for commandline compat
    } elsif("$arg" eq "-inc") {
	$var = "output";
	$val = shift @ARGV;
    } elsif("$arg" eq "-module") {
	$var = "module";
	$val = shift @ARGV;
    } elsif("$arg" eq "-show") {
	$var = "showonly";
	$val = "yes";
    }

    #do something
    if(!$var || "$var" eq "show_help") {
	print "Unknown option: $arg\n\n" if(!$var);
	showUsage();
    } elsif ("$var" eq "showonly") {
	if("$val" eq "yes") {
	    $showonly++;
	} elsif($showonly) {
	    $showonly--;
	}
    } elsif ("$var" eq "remove-stale") {
	if("$val" eq "yes") {
	    $remove_stale++;
	} elsif($remove_stale) {
	    $remove_stale--;
	}
    } elsif ("$var" eq "windows") {
	if("$val" eq "yes") {
	    $force_win++;
	} elsif($force_win) {
	    $force_win--;
	}
    } elsif ("$var" eq "relative") {
	if("$val" eq "yes") {
	    $force_relative++;
	} elsif($force_relative) {
	    $force_relative--;
	}
    } elsif ("$var" eq "module") {
	die "No such module: $val" unless(defined $modules{$val});
	push @modules_to_sync, $val;
    } elsif ("$var" eq "output") {
	my $outdir = $val;
	if($outdir !~ /^\//) {
	    $includedir = getcwd();
	    chomp $includedir;
	    $includedir .= "/" . $outdir;
	} else {
	    $includedir = $outdir;
	}
	# \ -> /
	$includedir =~ s=\\=/=g;
    }
}
@modules_to_sync = keys(%modules) if($#modules_to_sync == -1);

$isunix = checkUnix; #cache checkUnix

# create path
mkpath $includedir, 0777;

my @ignore_headers = ();
my @ignore_for_master_contents = ( "qt.h", "qpaintdevicedefs.h" );

foreach (@modules_to_sync) {
    #iteration info
    my $lib = $_;
    my $dir = "$modules{$lib}";

    #information used after the syncing
    my $master_contents = "";
    my $install_classes = "";
    my $install_files = "";

    #remove the old files
    if($remove_stale) {
	my @subdirs = ("$includedir/$lib");
	foreach (@subdirs) {
	    my $subdir = "$_";
	    opendir DIR, "$subdir";
	    while(my $t = readdir(DIR)) {
		my $file = "$subdir/$t";
		if(-d "$file") {
		    push @subdirs, "$file" unless($t eq "." || $t eq ".." || $t eq "arch");
		} else {
		    my @files = ("$file");
		    push @files, "$includedir/Qt/$t" if(-e "$includedir/Qt/$t");
                    foreach (@files) {
                       my $file = $_;
		       my $remove_file = 0;
		       if(open(F, "<$file")) {
			    while(<F>) {
			        my $line = $_;
			        chomp $line;
			        if($line =~ /^\#include \"([^\"]*)\"$/) {
				    my $include = $1;
				    $include = $subdir . "/" . $include unless(substr($include, 0, 1) eq "/");
				    $remove_file = 1 unless(-e "$include");
			        } else {
				    $remove_file = 0;
				    last;
			        }
		 	    }
			    close(F);
                	    unlink "$file" if($remove_file);
                        }
		    }
		}
	    }
	    closedir DIR;
	}
    }

    #create the new ones
    foreach (split(/;/, $dir)) {
	my $current_dir = "$_";
        #calc subdirs
        my @subdirs = ($current_dir);
        foreach (@subdirs) {
            my $subdir = "$_";
            opendir DIR, "$subdir";
            while(my $t = readdir(DIR)) {
                push @subdirs, "$subdir/$t" if(-d "$subdir/$t" && !($t eq ".") && !($t eq "..") && !($t eq "arch"));
            }
            closedir DIR;
        }

        #calc files and "copy" them
        foreach (@subdirs) {
            my $subdir = "$_";
            my @headers = findFiles("$subdir", "^[-a-z0-9_]*\\.h\$" , 0);
            foreach (@headers) {
                my $header = "$_";
                foreach (@ignore_headers) {
                    $header = 0 if("$header" eq "$_");
                }
                if($header) {
		    my $header_copies = 0;
		    #figure out if it is a public header
		    my $public_header = $header;
		    if($public_header =~ /_p.h$/) {
			$public_header = 0;
		    } else {
			foreach (@ignore_for_master_contents) {
			    $public_header = 0 if("$header" eq "$_");
			}
		    }

                    my $iheader = $subdir . "/" . $header;
		    my @classes = $public_header ? classNames($iheader) : ();
                    if($showonly) {
                        print "$header [$lib]\n";
			foreach(@classes) {
			    print "SYMBOL: $_\n";
			}
                    } else {
			#find out all the places it goes..
			my @headers;
			if ($public_header) {
			    @headers = ( "$includedir/Qt/$header", "$includedir/$lib/$header" );
			} else {
			    @headers = ( "$includedir/Qt/private/$header", "$includedir/$lib/private/$header" );
			}
			foreach(@classes) {
			    push @headers, "$includedir/$lib/$_";
			}
                        #do the syncing..
			foreach(@headers) {
			    $header_copies++ if(syncHeader($_, $iheader));
			}

			if($public_header) {
			    #put it into the master file
			    $master_contents .= "#include \"$public_header\"\n" if(shouldMasterInclude($iheader));

			    #deal with the install file
			    if($public_header) {
				my $install_iheader = substr($iheader, length($current_dir)+1);
				foreach(@classes) {
				    $install_classes .= " \\\n  \$\$quote(\"" .
					(length($install_classes) ? "\\n\\t" : "") .
					"-\$(INSTALL_FILE) \"$install_iheader\" \"PREFIXPATH/$_\"\")";
				}
				$install_files .= "$install_iheader ";;
			    }
			}
                    }
		    print "header created for $iheader ($header_copies)\n" if($header_copies > 0);
                }
            }
        }
    }

    unless($showonly) {
        #generate the "master" include file
        my $master_include = "$includedir/$lib/$lib";
	$install_files .= fixPaths($master_include, "$basedir/src/$lib/$lib") . " "; #get the master file installed too
        if(-e "$master_include") {
            open MASTERINCLUDE, "<$master_include";
            local $/;
            binmode MASTERINCLUDE;
            my $oldmaster = <MASTERINCLUDE>;
            close MASTERINCLUDE;
            $oldmaster =~ s/\r//g; # remove \r's , so comparison is ok on all platforms
            $master_include = 0 if($oldmaster eq $master_contents);
        }
        if($master_include) {
            my $master_dir = dirname($master_include);
            mkpath $master_dir, 0777;
            print "header (master) created for $lib\n";
            open MASTERINCLUDE, ">$master_include";
            print MASTERINCLUDE "$master_contents";
            close MASTERINCLUDE;
        }

        #handle the install.pri for each module
	my $install_contents = "";
	$install_contents .= "HEADER_FILES = $install_files\n";
	$install_contents .= "CLASSES_COPY = $install_classes\n";
        my $install_file = "$includedir/$lib/install.pri";
        if(-e "$install_file") {
            open INSTALLFILE, "<$install_file";
            local $/;
            binmode INSTALLFILE;
            my $oldinstall = <INSTALLFILE>;
            close INSTALLFILE;
            $oldinstall =~ s/\r//g; # remove \r's , so comparison is ok on all platforms
            $install_file = 0 if($oldinstall eq $install_contents);
        }
        if($install_file) {
            my $install_dir = dirname($install_file);
            mkpath $install_dir, 0777;
            print "install file created for $lib\n";
            open INSTALLFILE, ">$install_file";
            print INSTALLFILE "$install_contents";
            close INSTALLFILE;
        }
    }
}

if(!$isunix) {
    unlink "$basedir/Makefile";
    symlinkFile("$basedir/dist/win/Makefile", "$basedir/Makefile");
    symlinkFile("$basedir/dist/win/Makefile.win32-g++", "$basedir/Makefile.win32-g++");
}
