#!/usr/bin/perl -w

use Getopt::Long;

$opt_help=0;
$opt_tarball=$opt_builddir=$opt_suffix="";

GetOptions(
    "help",
    "tarball=s",
    "builddir=s",
    "suffix=s"
) || print_help();

print_help() if ($opt_help);

chomp($MSDEV=`which msdev`);

if (!$opt_builddir) {
  $opt_builddir = "/cygdrive/c/mysql-win-build";
}

$opt_tarball =~ /(mysql[^\/]*)-win-src\.tar/;
$mysqlver=$1;
$basedir = "$opt_builddir/$mysqlver";
$scriptdir = `pwd`;

# Make sure build dir exists
mkdir($opt_builddir);
# Clean out any previous build
system("rm -rf $basedir");

# Unpack in the script directory
system("tar -zxvf $opt_tarball");
# Move to the build directory
system("mv $mysqlver $opt_builddir");

if (!chdir($basedir))
{
  print "Do-win-build error: Could not change to $basedir";
  exit 1;
}

# Check whether this is a classic edition build
if ($opt_suffix =~ /-classic/)
{
  # Blank out ha_innodb.cpp
  chmod 0644, 'sql/ha_innodb.cpp';
  open(OUT, '>', 'sql/ha_innodb.cpp');
  close(OUT);

  # Remove HAVE_INNOBASE_DB from the requisite project files
  for $dspfile ('libmysqld/libmysqld.dsp', 'mysqldemb/mysqldemb.dsp', 'mysqlserver/mysqlserver.dsp', 'sql/mysqld.dsp', 'sql/mysqldmax.dsp')
  {
    open(IN, '<', $dspfile);
    open(OUT, '>', "$dspfile.tmp");
    while (readline IN)
    {
      s/\D \"HAVE_INNOBASE_DB\" //g;
      print OUT $_;
    }
    close(IN);
    close(OUT);
    unlink $dspfile;
    rename "$dspfile.tmp", $dspfile;
  }
}

# Perform compilation
system("\"$MSDEV\" mysql.dsw /MAKE \"ALL\" /OUT $mysqlver-build.log");

# Package binary
system("./scripts/make_win_binary_distribution --suffix=$opt_suffix");

# Copy log back to script directory
system("cp $mysqlver$suffix-build.log $scriptdir");

# Move binary package to script directory
system("mv *.zip $scriptdir");

#
# Print a help text message
#
sub print_help
{
	print <<EOF;
Usage: Do-compile-win [options] source-tarball

Unpacks a Windows source distribution on the local machine and
compiles it using VC++ 6.0.

This script is intended for Cygwin Perl. You must have a working
MSDEV.EXE in your path for compilation, as well as the following:

sed
tar (GNU tar)
which


Options:

--help
Print this text.

--builddir=<dir>
Set the Cygwin path to build under; the tarball will actually
be moved to <builddir>/mysql-<version>/tarball and extracted under
<builddir>/mysql-<version>/build.
Default: /cygdrive/c/mysql-win-build

--suffix=<suffix>
If specified, the resulting binary will have the specified suffix
in its name. If the suffix is "-classic", the project files will
be stripped of all occurrences of HAVE_INNOBASE_DB and
ha_innodb.cpp will be blanked out, to create classic edition
server binaries.

--tarball=<file>
Windows source tarball to use for this build. Must be of the form
mysql[com]-x.x.x-win-src.tar.gz (REQUIRED)

EOF
	exit 1;
}
