use 5.010;
use alienfile;
use Sort::Versions;

my $on_windows = $^O =~ /mswin/i;
my $on_automated_rig
  =  $ENV{PERL_CPAN_REPORTER_DIR}
  || $ENV{PERL_CPAN_REPORTER_CONFIG}
  || $ENV{AUTOMATED_TESTING}
  || $ENV{TRAVIS}
  || $ENV{APPVEYOR};

#  make sure we get GEOS support
use Alien::geos::af;
my $sep_char = $on_windows ? ';' : ':';
$ENV{PATH} .= $sep_char . join ($sep_char, Alien::geos::af->bin_dir);

#  make libtool noisy for debug purposes
#$ENV{LTFLAGS} = "--debug --verbose" if $on_windows;

#  add existing alien files to path etc
#  not very elegant...
#  disable for now - config tests fail
#  it looks to be already noted in https://github.com/Perl5-Alien/Alien-Build/issues/12
#  might also be able to access via old hash via https://metacpan.org/pod/Alien::Build#install_prop
my $have_alien_gdal = eval 'require Alien::gdal';
if (0 && $have_alien_gdal && Alien::gdal->install_type eq 'share') {
    my $ag_version = Alien::gdal->version;
    say "Found existing gdal via alien ($ag_version) in " .  Alien::gdal->dist_dir;
    #  append the relevant path
    $ENV{PKG_CONFIG_PATH}
      = Alien::gdal->dist_dir . '/lib/pkgconfig/'
      . $sep_char
      . ($ENV{PKG_CONFIG_PATH} // '');
    $ENV{PATH} = Alien::gdal->bin_dir . $sep_char . $ENV{PATH};
}

use Cwd;
my $base_dir = getcwd();
my $patch_file_isnan
  = "$base_dir/patch_isnan_gcc.patch";
my $patch_file_configure
  = "$base_dir/0001-Enable-shared-build-on-freebsd-10.patch";

my $min_target_version = '2.2.0';

plugin 'PkgConfig' => (
    pkg_name => 'gdal',
    minimum_version => $min_target_version,
);


share {

  my $with_local = '';
  my $with_cpp11 = '';

  start_url 'http://download.osgeo.org/gdal/CURRENT';
  #start_url "file://$base_dir";  #  debug
  plugin Download => (
    filter  => qr/^gdal-([0-9\.]+)\.tar\.gz$/,
    version => qr/^gdal-([0-9\.]+)\.tar\.gz$/,
  );

  my $gdal_version = get_gdal_version() // 'not yet defined';
  say "Downloaded gdal version is $gdal_version";
  
  plugin Extract => (format => 'tar.gz');

  if (versioncmp($gdal_version, '2.3.0') == -1) {
    if ($^O =~ /mswin/i) {
      #  fix known issue in 2.2.3, harmless in 2.2.4.
      patch [
        '%{patch} port/cpl_port.h < ' . $patch_file_isnan,
      ];
    }
    elsif ($^O =~ /freebsd/i) {
      #  make sure we run a shared install on freebsd by default
      #  (before libtool files were updated for gdal 2.3.0)
      patch [
        '%{patch} configure < ' . $patch_file_configure,
      ];
      $with_cpp11 = ' --without-cpp11 ';  #  issues with cad lib pre 2.3.0
    }
  }

  plugin 'Build::Autoconf' => ();

  my $build_static = ($^O =~ /mswin/i) ? '' : '--disable-shared';
  $build_static = '';
  $build_static = '--enable-static=no';  #  override - HUGE files if static
  $build_static = '' if $ENV{FORCE_DYNAMIC};
  
  
  if ($^O =~ /bsd/) {
    plugin 'Build::Make' => 'gmake';
    if (-d '/usr/local') {
        $with_local = ' --with-local=/usr/local ';
    }
  }
  elsif ($^O =~ /dragonfly/) {
    #  might need to be combined with bsd check above
    #  but not sure if /usr/local is needed yet
    plugin 'Build::Make' => 'gmake';
  }

  my $make_cmd = '%{make}';
  my $make_inst_cmd = '%{make} install';
  my @make_clean;
  #  try not to exceed the cpan-testers log limits
  if ($on_automated_rig) {
    say "Running under CI or automated testing";
    $make_cmd      .= q/ | perl -ne "BEGIN {$|=1; open our $log, q|>|, q|build.log|};   print qq|\n| if 0 == ($. %% 100); print q|.|; print {$log} $_;" || type build.log/;
    $make_inst_cmd .= q/ | perl -ne "BEGIN {$|=1; open our $log, q|>|, q|install.log|}; print qq|\n| if 0 == ($. %% 100); print q|.|; print {$log} $_;" || type install.log/;
    if (!$on_windows) {
        $make_cmd =~ s/%%/%/;
        $make_cmd =~ s/type/cat/;
        $make_cmd =~ s/"/'/g;
        $make_inst_cmd =~ s/%%/%/;
        $make_inst_cmd =~ s/type/cat/;
        $make_inst_cmd =~ s/"/'/g;
    }
    #if (! ($ENV{TRAVIS} || $ENV{APPVEYOR})) {
    #    push @make_clean, '%{make} clean';
    #}
    #  clean up the build dir on cpan testers etc
    plugin 'Cleanse::BuildDir';
  }
  
  build [
    "%{configure} --with-libtiff=internal $with_local $with_cpp11 $build_static",
    \&update_makefile,
    \&pause,
    $make_cmd,
    \&patch_pkgconfig,
    $make_inst_cmd,
    @make_clean
  ];

};

sub update_makefile {
    return;  #  should not be needed now
    return if !$on_windows;
    system ($^X, '-p', '-i.bak', q{-e"s/\$\(GDAL_ROOT\)/\./"}, "GNUmakefile");
}

sub pause {
    return;  #  re-enable in case of debug
    return if $on_automated_rig;
    return if !$on_windows;

    say "CONTINUE?";
    my $response = <>;
    while (not $response =~ /yes/) {
        $response = <>;
    }
}


sub patch_pkgconfig {
    #my $gdal_config_file = 'bin/gdal-config';
    #my $pkg_config_file  = 'lib/pkgconfig/gdal.pc';
    use File::Find::Rule;
    my @gdal_configs
      = File::Find::Rule->file()
                        ->name( 'gdal-config' )
                        ->in( '.' );
    my @pkg_configs
      = File::Find::Rule->file()
                        ->name( 'gdal.pc' )
                        ->in( '.' );
    say 'gdal-configs: ' . join ' ', @gdal_configs;
    say 'pkg-configs:  ' . join ' ', @pkg_configs;
    
    return if !@gdal_configs || !@pkg_configs;
    
    open my $gc_fh, '<', $gdal_configs[0] or die $!;
    my $dep_libs = '';
    while (defined (my $line = <$gc_fh>)) {
        if ($line =~ /CONFIG_DEP_LIBS=(.+)$/) {
            $dep_libs = $1;
            last;
        }
    }
    close $gc_fh;

    #  trim quotes (could do in prev check, but...)
    $dep_libs =~ s/^\"//;
    $dep_libs =~ s/\"$//;
    
    open my $pk_fh, '<', $pkg_configs[0] or die $!;
    my @pkg_conf;
    while (defined (my $line = <$pk_fh>)) {
        push @pkg_conf, $line;
    }
    close $pk_fh;

    #  change all (we should be more nuanced and do only the one that matters)
    foreach my $pkg_config_file (@pkg_configs) {
        say "Adding gdal dep_libs to $pkg_config_file";
        #  now add the dep libs to the pkg_conf file
        open $pk_fh, '>', $pkg_config_file or die $!;
        foreach my $line (@pkg_conf) {
            if ($line =~ /^CONFIG_INST_LIBS/) {
                chomp $line;
                $line .= " $dep_libs\n";
            }
            print {$pk_fh} $line;
        }
        close $pk_fh;
    }
}

sub get_gdal_version {
    my $h = get_alien_state_hash();
    return $h->{runtime}{version};
}

sub get_alien_state_hash {
    use JSON::PP;
    my $root = "$base_dir/_alien";
    my $f = "$root/state.json";
    my $h = {};
    if (-e $f) {
        open my $fh, '<', $f or die $!;
        my $d = do {
            local $/ = undef;
            <$fh>;
        };
        $h = JSON::PP::decode_json($d);
    }
    return $h;
}
