#!/usr/bin/env perl

# by Matt Simerson
# v1.2  Feb 02, 2009 - install if version_wanted test fails
# v1.1  Jan 21, 2009 - install JSON::XS
# v1.0  Jan 14, 2009

use strict;
use warnings;

BEGIN {
   $ENV{PERL_MM_USE_DEFAULT} = 1;
}

use CPAN;
use English qw( -no_match_vars );

use lib 'lib';   # use local version if available

install_module('Config::Tiny');
install_module('JSON::XS');
install_module('LWP::UserAgent');

my $module = 'Provision::Unix';
my $version_wanted = latest_on_cpan($module);

my ($version_installed);
eval "require $module" and $version_installed = $module->VERSION;
print "installed version is: $version_installed\n" if $version_installed;

if ( $version_installed ) {
    eval "use $module $version_wanted";
    if ( ! $EVAL_ERROR ) {
        print "$module is up-to-date.\n";
        exit;
    };
    print  "upgrading Provision::Unix from CPAN\n";
} 
else {
    print  "installing Provision::Unix from CPAN\n";
};
install_module($module, undef, $version_wanted);
exit;

sub latest_on_cpan {
    my $module   = shift;
    my $cpan     = 'http://search.cpan.org/~msimerson/Provision-Unix/';

    eval "require LWP::UserAgent";
    if ( $EVAL_ERROR ) {
        warn "\t ERROR: Could not load LWP::UserAgent. Cannot look up latest version of Provision::Unix!\n";
        return;
    };

    my $ua = LWP::UserAgent->new( timeout => 10);
    my $response = $ua->get($cpan);

    die $response->status_line if ! $response->is_success;

    my $content = $response->content;

    $module =~ s/::/-/g;  # convert the :: in the module name to -
    #print "searching for $module on CPAN\n";

    my ($version) = $content =~ m/$module-([0-9\.]{3,5})</;
    $version or die "could not find latest version of $module on CPAN\n";
    print "CPAN version is $version\n";
    return $version;
};

sub install_module {

    my ($module, $info, $version) = @_;

    if ( lc($OSNAME) eq 'darwin' ) {
        my $dport = '/opt/local/bin/port';
        if ( ! -x $dport ) {
            print "Darwin ports is not installed!\n";
        } 
        else {
            my $port = "p5-$module";
            $port =~ s/::/-/g;
            system "sudo $dport install $port" 
                or warn "install failed for Darwin port $module";
        }
    }

    if ( lc($OSNAME) eq 'freebsd' ) {

        my $portname = "p5-$module";
        $portname =~ s/::/-/g;

        if (`/usr/sbin/pkg_info | /usr/bin/grep $portname`) {
            return print "$module is installed.\n";
        }

        print "installing $module";

        my $portdir = </usr/ports/*/$portname>;

        if ( $portdir && -d $portdir && chdir $portdir ) {
            print " from ports ($portdir)\n";
            system "make install clean" 
                or warn "'make install clean' failed for port $module\n";
        }
    }

    if ( lc($OSNAME) eq 'linux' ) {
        my $rpm = $info->{rpm};
        if ( $rpm ) {
            my $portname = "perl-$rpm";
            $portname =~ s/::/-/g;
            my $yum = '/usr/bin/yum';
            if ( -x $yum ) {
                system "$yum -y install $portname";
            };
        }
    };

    print " from CPAN...";

    # some Linux distros break CPAN by auto/preconfiguring it with no URL mirrors.
    # this works around that annoying little habit
    $CPAN::Config = get_cpan_config();

    if ( $module eq 'Provision::Unix' && $version ) {
        $module =~ s/\:\:/\-/g;
        $module = "M/MS/MSIMERSON/$module-$version.tar.gz";
    }
    CPAN::Shell->install($module);
}

sub get_cpan_config {

    my $ftp = `which ftp`; chomp $ftp;
    my $gzip = `which gzip`; chomp $gzip;
    my $unzip = `which unzip`; chomp $unzip;
    my $tar  = `which tar`; chomp $tar;
    my $make = `which make`; chomp $make;
    my $wget = `which wget`; chomp $wget;

    return 
{
  'build_cache' => q[10],
  'build_dir' => qq[$ENV{HOME}/.cpan/build],
  'cache_metadata' => q[1],
  'cpan_home' => qq[$ENV{HOME}/.cpan],
  'ftp' => $ftp,
  'ftp_proxy' => q[],
  'getcwd' => q[cwd],
  'gpg' => q[],
  'gzip' => $gzip,
  'histfile' => qq[$ENV{HOME}/.cpan/histfile],
  'histsize' => q[100],
  'http_proxy' => q[],
  'inactivity_timeout' => q[5],
  'index_expire' => q[1],
  'inhibit_startup_message' => q[1],
  'keep_source_where' => qq[$ENV{HOME}/.cpan/sources],
  'lynx' => q[],
  'make' => $make,
  'make_arg' => q[],
  'make_install_arg' => q[],
  'makepl_arg' => q[],
  'ncftp' => q[],
  'ncftpget' => q[],
  'no_proxy' => q[],
  'pager' => q[less],
  'prerequisites_policy' => q[follow],
  'scan_cache' => q[atstart],
  'shell' => q[/bin/csh],
  'tar' => $tar,
  'term_is_latin' => q[1],
  'unzip' => $unzip,
  'urllist' => [ 'http://www.perl.com/CPAN/', 'http://mirrors.kernel.org/pub/CPAN/', 'ftp://cpan.cs.utah.edu/pub/CPAN/', 'ftp://mirrors.kernel.org/pub/CPAN', 'ftp://osl.uoregon.edu/CPAN/', 'http://cpan.yahoo.com/', 'ftp://ftp.funet.fi/pub/languages/perl/CPAN/' ],
  'wget' => $wget, };
}


