#!/Perl/bin/Perl.exe

use strict;
use warnings;
use Config;
use LWP::Simple;
use ExtUtils::MakeMaker;

my $libs = {
  libxml => {
    name    => 'libxml2.dll',
    version => '2.6.29',
    found   => 0,
  },
  iconv  => {
    name    => 'iconv.dll',
    version => '1.9.2',
    found   => 0,
  },
  zlib   => {
    name    => 'zlib1.dll',
    version => '1.2.3',
    found   => 0,
  },
};

# search for libraries

my @paths = split( ';', $ENV{PATH} || '' );
foreach my $lib (keys %{ $libs }) {
  foreach my $path (@paths) {
    unless ($libs->{$lib}->{found}) {
      my $dll = File::Spec->catfile( $path, $libs->{$lib}->{name} );
      $libs->{$lib}->{found} = 1 if -e $dll; 
    }
  }

  my $install = 1;
  if ( $libs->{$lib}->{found} ) {
    my $ret = prompt "You seem to have installed $libs->{$lib}->{name}.\nIs this compatible with the version $libs->{$lib}->{version}? (Y/n)", 'yes';
    if ($ret =~ /^[yY]/) {
      $install = 0;
      next;
    }
    else {
      my $ret = prompt "You can download it from http://www.zlatkovic.com/libxml.en.html afterwards, or you can download it from here.\nFetch it now? (Y/n)", 'yes';
      if ($ret !~ /^[yY]/) {
        print "ok. Be sure to install $libs->{$lib}->{name} later.\n";
        $install = 0;
        next;
      }
      else {
        print "ok. $libs->{$lib}->{name} will be installed on perl's bin directory ($Config{scriptdir}).\n";
      }
    }
  }
  else {
    my $ret = prompt "You don't seem to have installed $libs->{$lib}->{name}.\nYou can download it from http://www.zlatkovic.com/libxml.en.html afterwards, or you can download it from here.\nFetch it now? (Y/n)", 'yes';
    if ($ret !~ /^[yY]/) {
      print "ok. Be sure to install $libs->{$lib}->{name} later.\n";
      $install = 0;
      next;
    }
    else {
      print "ok. $libs->{$lib}->{name} will be installed on perl's bin directory ($Config{scriptdir}).\n";
    }
  }

  my $remote = 'http://ppm.tcool.org/libs/'.$libs->{$lib}->{name};
  my $local  = File::Spec->catfile($Config{scriptdir}, $libs->{$lib}->{name});

  if (-e $local) {
    my $ret = prompt "You seem to have installed $libs->{$lib}->{name} in the perl's bin directory.\nMay I delete it? (Y/n)", 'yes';
    if ($ret =~ /^[yY]/) {
      ### this may fail
      eval { unlink $local; };
      if ($@) {
        print "Can't delete $local ($@)\nSkip";
        next;
      }
    }
  }

  getstore($remote, $local);
  unless (-f $local) {
    print "Downloading ".$libs->{$lib}->{name}." has failed\nBe sure to install $libs->{$lib}->{name} later.\n";
  }
}
sub prompt { $_[1] };
