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};
  #|| $ENV{CI};


use Cwd;
my $base_dir = getcwd();

use Env qw( @PATH );

use Alien::sqlite;
unshift @PATH, Alien::sqlite->bin_dir;
my @dep_aliens = ('Alien::sqlite');
my $have_alien_curl = eval 'require Alien::curl';
if ($have_alien_curl) {
  unshift @PATH, 'Alien::curl'->bin_dir;
  push @dep_aliens, 'Alien::curl';
}
#  does not exist at the time of writing
my $have_alien_tiff = eval 'require Alien::libtiff';
if ($have_alien_tiff) {
  unshift @PATH, 'Alien::tiff'->bin_dir;
  push @dep_aliens, 'Alien::tiff';
}
#do {
#  #  limit scope
#  #use Env qw / @PKG_CONFIG_PATH /;
#  if (Alien::sqlite->install_type eq 'share') {
#    #unshift @PKG_CONFIG_PATH,
#    $ENV{PKG_CONFIG_PATH} .= 
#      ':' . Alien::sqlite->dist_dir . '/lib/pkgconfig';
#    $ENV{PKG_CONFIG_PATH} =~ s/^://;
#  }
#};
#  we should just add path to $ENV{PKG_CONFIG_PATH}
#  but are hitting sep char issues
$ENV{SQLITE3_CFLAGS} = Alien::sqlite->cflags;
$ENV{SQLITE3_LIBS} = Alien::sqlite->libs;
say "Alien::sqlite has sqlite version " . Alien::sqlite->version;

plugin 'Build::SearchDep' => (
  aliens   => [ @dep_aliens ],
  public_I => 1,
  public_l => 1,
);

my $min_target_version = '4.9.0';

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


share {

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

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

  my $proj_version = get_proj_version() // 'not yet defined';
  say "Downloaded proj version is $proj_version";
  
  plugin Extract => (format => 'tar.gz');


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

  my $build_static = $on_windows ? '' : '--disable-shared';
  $build_static = '';
  $build_static = '--enable-static=no';  #  override - needed?  leftover from gdal
  $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
    #  but not github workflows
    if (!$ENV{CI}) {
      plugin 'Cleanse::BuildDir';
    }
  }
  
  my $config_args = $ENV{ALIEN_PROJ_CONFIG_ARGS} // '';
  $config_args =~ s/[^-\s\w,=]//g;  #  overkill?
  my $with_tiff = '';
  if (!$have_alien_tiff && $proj_version ge 7) {
    $with_tiff = '--disable-tiff';
  }
  my $with_curl = '--without-curl';  #  until Alien::libcurl provides dynamic curl-config
  if (!$have_alien_curl && $proj_version ge 7) {
    $with_curl = '--without-curl';  #  until Alien::libcurl provides dynamic curl-config
  }
  $config_args = "$with_local $with_cpp11 $with_tiff $with_curl $build_static $config_args";
  
  build [
    \&update_pkg_conf_path,
    "%{configure} $config_args",
    \&pause,
    $make_cmd,
    $make_inst_cmd,
    #@make_clean,
    \&rename_la_files,
  ];

};

#gather [
#    \&rename_la_files,
#];
#

sub update_pkg_conf_path {
    return if !$on_windows;
    use Env qw /@PKG_CONFIG_PATH/;
    say 'Modifying drive paths in PKG_CONFIG_PATH';
    say $ENV{PKG_CONFIG_PATH};
    #  msys-ificate drive paths
    @PKG_CONFIG_PATH = map {s{^([a-z]):}{/$1}ri} @PKG_CONFIG_PATH;
    say $ENV{PKG_CONFIG_PATH};
    return;
}

sub rename_la_files {
    #  need to return if not share
    return if !$on_windows;
    
    use File::Find::Rule;
    my @la_files
      = File::Find::Rule->file()
                        ->name( '*.la' )
                        ->in( $base_dir );
    foreach my $file (@la_files) {
        say "Renaming $file so it will not interfere with gdal compilation";
        rename $file, $file . '.bak';
    }

}


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 get_proj_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;
}

