#! /usr/bin/perl -w

# Maybe I should have used PHP instead?  ;)

use strict;
$| = 1;

-f "libmysql.c" or die "$0 must be run from the libmysql directory\n";

my $command = shift || usage();
$command =~ /^--(?:update|huh|restore)$/ or usage();

my $from = shift || '/my/mysql';
my @source_dirs = qw/dbug strings mysys libmysql include/;
my $source_re = qr/\.(?:cc?|h)$/;
my %skip = (
  'ctype_autoconf.c' => 1,              # PHP uses a pre-made one
  'ctype_extra_sources.c' => 1,         # same here
  'my_config.h' => 1,                   # we use php_config.h
);

opendir D, "."
	or die "can't opendir .: $!\n";
my @files = grep { /$source_re/ and !$skip{$_} } readdir D;
closedir D;

if ($command eq '--restore')
{
  foreach (@files)
  {
    -f "$_.orig" and
        system("mv -f $_.orig $_") and die "can't restore $_: $!\n";
  }
  exit 0;
}

if ($command eq '--huh')
{
  diff_files();
  exit 0;
}

my %sources;
foreach my $d (@source_dirs)
{
  opendir D, "$from/$d" or die "opendir $from/$d: $!\n";
  foreach (grep { /$source_re/ } readdir D)
  {
    $sources{$_} ||= "$d/$_";
  }
  closedir D;
}

foreach my $f (@files)
{
  my $s = $sources{$f} or die "can't find source file for $f\n";
  unlink "$f.orig";
  system("mv $f $f.orig") and die "can't move $f: $!\n";
  #print ">>  ", scalar(`ls -l $from/$s`), "\n";
  print ">>  $s\n";
  system("cp $from/$s $f") and die "can't copy $from/$s: $!\n";
  #print "]]  ", scalar(`ls -l $f`), "\n";
}

system("chmod u+w @files") and die "can't set perms on files: $!\n";
system("./fix_copyright @files") and die "can't fix copyright: $!\n";
diff_files();

exit 0;


sub usage
{
  die <<"EOF";
usage: $0 --update [mysql-source-dir]
       $0 --huh
       $0 --restore

    Typical use is:
        \$ $0 --update 2>&1 > /tmp/php-update.diff
        \$ @{[$ENV{EDITOR}||'vi']} /tmp/php-update.diff      #does it look okay?
	\$ Monkey around a bit
	\$ cvs diff -u | less		# does this look okay?
        \$ rm *.orig
EOF
}

sub diff_files {
  foreach my $f (@files)
  {
    if (!-f "$f.orig" or !system("diff -u $f.orig $f"))
    {
      print STDERR "SAME: $f\n";
      unlink "$f.orig";
    }
    else
    {
      print STDERR "DIFF: $f\n";
      $f eq 'config-win.h' and
	print STDERR "/n/nDon't forget to undefine HAVE_COMPRESS in $f/n/n/n";
    }
  }
}
