#!/usr/bin/env perl

# This is a script to configure the distribution. Its primary audience
# are the core developers and halo developers, and not end-users. Please
# see the INSTALL file for proper building instructions using cmake.
#
# "Tatzer" (Taf-Tzadik-Reish) is the Hebrew word for "configure!".

use strict;
use warnings;

use File::Path qw(rmtree);
use File::Basename qw(dirname);
use File::Spec;
use Getopt::Long;

my %BOOL_OPTS_WITH_FALSE_DEFAULTS =
(
    'avoid-tcmalloc' => 'FCS_AVOID_TCMALLOC',
    'break-back-compat-1' => 'FCS_BREAK_BACKWARD_COMPAT_1',
    'disable-patsolve' => 'FCS_DISABLE_PATSOLVE',
    'disable-simple-simon' => 'FCS_DISABLE_SIMPLE_SIMON',
    'fc-only' => 'FCS_FREECELL_ONLY',
    'omit-frame' => 'OPTIMIZATION_OMIT_FRAME_POINTER',
    'rcs' => 'FCS_ENABLE_RCS_STATES',
    'secondary' => 'FCS_ENABLE_SECONDARY_HASH_VALUE',
    'single-ht' => 'FCS_SINGLE_HARD_THREAD',
    'static' => 'FCS_LINK_TO_STATIC',
    'tracemem' => 'FCS_TRACE_MEM',
    'with-compact-moves' => 'FCS_USE_COMPACT_MOVE_TOKENS',
    'without-depth-field' => 'FCS_WITHOUT_DEPTH_FIELD',
    'without-fc-pro' => 'FCS_WITHOUT_FC_PRO_MOVES_COUNT',
    'without-visited-iter' => 'FCS_WITHOUT_VISITED_ITER',
);

my @BOOL_OPTS_WITH_FALSE_DEFAULTS__KEYS = keys %BOOL_OPTS_WITH_FALSE_DEFAULTS;

my %bool_opts_with_false_defaults__values =
(
    map { $_ => 0 } @BOOL_OPTS_WITH_FALSE_DEFAULTS__KEYS
);

my %TRUE_BOOL_OPTS =
(
    'build-docs' => 'FCS_BUILD_DOCS',
    'test-suite' => 'FCS_WITH_TEST_SUITE',
    'with-ctx-var' => 'FCS_WITH_CONTEXT_VARIABLE',
);
my @TRUE_BOOL_KEYS = keys %TRUE_BOOL_OPTS;
my %true_bool_opts__values = map { $_ => 1 } @TRUE_BOOL_KEYS;

my %INT_OPTS =
(
    'max-bench-threads-num' => 'MAX_NUM_BENCHMARK_THREADS',
    'nfc' => 'FCS_HARD_CODED_NUM_FCS_FOR_FREECELL_ONLY',
    'num-stacks' => 'MAX_NUM_STACKS',
    'pack-size' => 'FCS_IA_PACK_SIZE',
    'scan-buckets-num' => 'FCS_MAX_NUM_SCANS_BUCKETS',
);

my @INT_OPS__KEYS = keys %INT_OPTS;

my %int_opts__values =
(
    map { $_ => undef() } @INT_OPS__KEYS
);
$int_opts__values{'max-bench-threads-num'} = 4;

my %STR_OPTS =
(
    'arch' => { param => 'CPU_ARCH', },
    'c|cols' => {prefix => 'FCS_STATE_STORAGE_', param => 'FCS_STATE_STORAGE'},
    'dbm' => { param => 'FCS_DBM_BACKEND', },
    'libavl2-c' => { param => 'FCS_STACK_STORAGE_LIBAVL2_TREE_TYPE' },
    'libavl2-p' => { param => 'FCS_STATE_STORAGE_LIBAVL2_TREE_TYPE' },
    'prefix' => {param => 'CMAKE_INSTALL_PREFIX',},
    'p|pos' => {prefix => 'FCS_STACK_STORAGE_', param => 'FCS_STACK_STORAGE'},
    'rcs-cache-storage' => { prefix => 'FCS_RCS_CACHE_STORAGE_', param => 'FCS_RCS_CACHE_STORAGE' },
    'states-type' => { param => 'STATES_TYPE', },
);

my @STR_OPTS__KEYS = keys %STR_OPTS;
for my $k (@STR_OPTS__KEYS)
{
    $STR_OPTS{$k}{'value'} = undef();
    $STR_OPTS{$k}{'prefix'} //= '';
}

$STR_OPTS{'rcs-cache-storage'}{value} = 'KAZ_TREE';
$STR_OPTS{'prefix'}{value} = '/usr';

my $build_type = "debug";

my $google_stack_storage;
my $google_state_storage;

sub set_both
{
    my $val = shift;
    foreach my $k ('c|cols', 'p|pos')
    {
        $STR_OPTS{$k}{'value'} = $val;
    }
    return;
}

sub set_hash
{
    return set_both("INTERNAL_HASH");
}

set_hash();

sub _google_set_both
{
    my $val = shift;

    $google_state_storage = $google_stack_storage = $val;

    return;
}
_google_set_both("SPARSE");
sub _set_to_google_hash
{
    set_both("GOOGLE_DENSE_HASH");
    _google_set_both(shift);
    return;
}

my %themes =
(
    tt => [qw(-r --notest-suite --static)],
    bench => [qw(-l tt --omit-frame --without-visited-iter --single-ht)],
    fc_bench => [qw(
        -l bench --fc-only --without-depth-field
        )
    ],
    mem_reduction_settings => [qw(
        --rcs --with-compact-moves --without-depth-field
    )],
    reduce_mem => [ qw(-l bench -l mem_reduction_settings) ],
    fc_reduce_mem => [ qw(-l fc_bench -l mem_reduction_settings --scan-buckets-num=1) ],
    testing => [qw(--rwd --dbm=kaztree --test-suite --num-stacks=13),],
);

foreach my $rec (
    {id => "p4", a => "pentium4"},
    {id => "x64", a => "barcelona"},
    {id => "c2", a => "core2",},
    {id => "ci7", a => "corei7-avx",}
)
{
    my $id = $rec->{id};
    my $arch = $rec->{a};

    $themes{$id} = ["--arch=$arch"];
    # Benchmark for freecell only
    $themes{$id.'b'} = [qw(-l fc_bench -l), $id];
    # Generalised benchmark - not freecell-only - should pass the tests.
    $themes{$id.'bb'} = [qw(-l bench -l), $id];
    # Memory conserving theme - for freecell only
    $themes{$id.'m'} = [qw(-l fc_reduce_mem -l), $id];
    # Generalised Memory conserving theme - not only for freecell
    $themes{$id.'mm'} = [qw(-l reduce_mem -l), $id];
    # Testing theme - aims to run the tests quickly
    $themes{$id.'t'} = ['-l', $id.'bb', qw(-l testing),];

    # For use by PySolFC
    $themes{$id . "_pysol"} = ['-l', $id.'bb', '--num-stacks=14', "--prefix=$ENV{HOME}/apps/fcs-for-pysol",];
}

my @new_argv = @ARGV;

CALC_NEW_ARGV:
for (my $idx = 0; $idx < @new_argv ; $idx++)
{
    if ($new_argv[$idx] =~ m{\A-l(.*)\z}ms)
    {
        my $start_idx = $idx;

        my $param = $1 || $new_argv[++$idx];

        if (! (my $cmd = $themes{$param}) )
        {
            die "Unknown -l argument $param!";
        }
        else
        {
            splice (@new_argv, $start_idx, $idx-$start_idx+1, @$cmd);
        }

        $idx = $start_idx;
        redo CALC_NEW_ARGV;
    }
}

@ARGV = @new_argv;

if ($ENV{VERBOSE})
{
    print "<@ARGV>";
}

GetOptions(
    'd|debug' => sub {
        my ($opt, $val) = @_;
        if ($val)
        {
            $build_type = "debug";
        }
        return;
    },
    'r|release' => sub {
        my ($opt, $val) = @_;
        if ($val)
        {
            $build_type = "release";
        }
        elsif ($build_type eq "release")
        {
            $build_type = "debug";
        }
        return;
    },
    'rwd' => sub {
        my ($opt, $val) = @_;

        $build_type = "RelWithDebInfo";

        return;
    },
    'kazlib' => sub { $STR_OPTS{'p|pos'}{value} = $STR_OPTS{'rcs-cache-storage'}{value} = 'KAZ_TREE'; },
    'judy' => sub { return set_both("JUDY"); },
    'hash' => \&set_hash,
    'lrb|libredblack' => sub { return set_both("LIBREDBLACK_TREE"); },
    'dense' => sub { return _set_to_google_hash("DENSE"); },
    'sparse' => sub { return _set_to_google_hash("SPARSE"); },
    'profile' => sub {
        my ($opt, $val) = @_;
        if ($val)
        {
            $build_type = "profile";
        }
        elsif ($build_type eq "profile")
        {
            $build_type = "debug";
        }
        return;
    },
    'minsize' => sub {
        $build_type = "MinSizeRel";
        return;
    },
    (map {; "$_!" => \($bool_opts_with_false_defaults__values{$_}) } @BOOL_OPTS_WITH_FALSE_DEFAULTS__KEYS),
    (map {; "$_!" => \($true_bool_opts__values{$_}) } @TRUE_BOOL_KEYS),
    (map {; "$_=i" => \($int_opts__values{$_}) } @INT_OPS__KEYS),
    (map {; "$_=s" => \($STR_OPTS{$_}{value}) } @STR_OPTS__KEYS),
) or
    die "Wrong options";

my $path_to_source_dir;

if (@ARGV)
{
    $path_to_source_dir = shift(@ARGV);

    if (@ARGV)
    {
        die "Junk at the end of ARGV - <@ARGV>";
    }
}
else
{
    $path_to_source_dir = dirname($0);
}

if ($bool_opts_with_false_defaults__values{rcs})
{
    $STR_OPTS{'states-type'}{'value'} = 'COMPACT_STATES';
}

if ($STR_OPTS{'livavl2-p'}{value})
{
    $STR_OPTS{'p|pos'}{value} = 'LIBAVL2_TREE';
}

if ($STR_OPTS{'livavl2-c'}{value})
{
    $STR_OPTS{'c|cols'}{value} = 'LIBAVL2_TREE';
}

if ($build_type eq "debug")
{
    $STR_OPTS{dbm}{value} ||= 'kaztree';
}

# This cache is sometimes causing problems.
unlink("CMakeCache.txt");
rmtree(['_Inline', 't/_Inline']);
unlink(glob("*.so"));

my @cmd= ("cmake",
    "-DCMAKE_BUILD_TYPE=$build_type",
    "-DDATADIR=$STR_OPTS{prefix}{value}/share",
    "-DBUILD_STATIC_LIBRARY=",
    "-DFCS_WHICH_COLUMNS_GOOGLE_HASH=FCS_WHICH_COLUMNS_GOOGLE_HASH__$google_stack_storage",
    "-DFCS_WHICH_STATES_GOOGLE_HASH=FCS_WHICH_STATES_GOOGLE_HASH__$google_state_storage",
    # Specifying a -D variable explicitly if it's not used gives a warning,
    # so we need to check that it is used.
    ((($STR_OPTS{'libavl2-c'}{value} || $STR_OPTS{'libavl2-p'}{value}) && exists($ENV{"LIBAVL2_SOURCE_DIR"}))
        ? ("-DLIBAVL2_SOURCE_DIR=$ENV{LIBAVL2_SOURCE_DIR}")
        : ()
    ),
    ($STR_OPTS{dbm}{value} ? ("-DFCS_ENABLE_DBM_SOLVER=1") : ()),
    (map { $bool_opts_with_false_defaults__values{$_} ? ("-D" . $BOOL_OPTS_WITH_FALSE_DEFAULTS{$_} . "=1") : () } @BOOL_OPTS_WITH_FALSE_DEFAULTS__KEYS),
    (map { '-D' . $TRUE_BOOL_OPTS{$_} . '=' . ($true_bool_opts__values{$_} ? '1': '') } @TRUE_BOOL_KEYS),
    (map { defined($int_opts__values{$_}) ? ("-D" . $INT_OPTS{$_} . "=" . $int_opts__values{$_}) : () } @INT_OPS__KEYS),
    (map { my $k = $_; my $r = $STR_OPTS{$k}; my $v = $r->{value}; defined($v) ? ("-D$r->{param}=$r->{prefix}$v") : () } @STR_OPTS__KEYS),
);


if (defined ($path_to_source_dir))
{
    push @cmd, $path_to_source_dir;
}

print(join(" ", @cmd), "\n");
my $exit_code = system(@cmd);
exit($exit_code);

=head1 COPYRIGHT AND LICENSE

Copyright (c) 2009 Shlomi Fish

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

=cut

