#!/usr/bin/perl

use strict;
use warnings;

use 5.010001;

use autodie;
use File::Spec;
use File::Fetch;

my $cpanm = File::Spec->catfile( $ENV{HOME}, '.enbld', 'etc', 'cpanm' );

clear_MYMETA();
download_cpanm() unless ( -e $cpanm );

say "=====> Install Enbld to " . File::Spec->catdir( $ENV{HOME}, '.enbld' ) . ".";

my $install_path = File::Spec->catdir( $ENV{HOME}, '.enbld', 'extlib' );

print "\n";
system( '/usr/bin/perl', $cpanm, '.', '-L', $install_path );
print "\n";

print << 'EOF';
=====> Finish installation.

Please add following path to PATH.

    $HOME/.enbld/extlib/bin
    $HOME/.enbld/bin
    $HOME/.enbld/sbin

Please add following path to MANPATH.

    $HOME/.enbld/share/man
    $HOME/.enbld/man

EOF

sub download_cpanm {
    $File::Fetch::BLACKLIST = [ qw|lwp httptiny| ];

    my $ff       = File::Fetch->new( uri => 'http://xrl.us/cpanm' );
    my $location = File::Spec->catdir( $ENV{HOME}, '.enbld', 'etc' );
    my $where    = $ff->fetch( to => $location ) or die $ff->error;

    return $where;
}

sub clear_MYMETA {

    unlink( 'MYMETA.json' ) if ( -e 'MYMETA.json' );
    unlink( 'MYMETA.yml'  ) if ( -e 'MYMETA.yml'  );

}
