#! /usr/bin/perl

use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use File::Path;
use FindBin;
use LWP::Simple;
use File::Temp qw/tempfile/;

our $VERSION = "2.0.0";

my ($opt_list, $opt_mkdir);

GetOptions(
    p => \$opt_mkdir,
    list => \$opt_list,
    help => sub {
        pod2usage(1);
    },
    version => sub {
        print "$VERSION\n";
        exit 0;
    }
) or exit 1;

my $suites_txt = `curl -s "https://raw.githubusercontent.com/linux-noah/noahstrap-suites/master/SUITES"`
    or die "could not fetch suite database";

my %suites;
foreach my $line (split(/\n/, $suites_txt)) {
    my ($name, $url) = split(/\t/, $line);
    $suites{$name} = $url;
}

if ($opt_list) {
    foreach my $suite (keys %suites) {
        print $suite, "\n";
    }
    exit 0;
}

if ($#ARGV + 1 != 2) {
    pod2usage(1);
}

my ($suite, $target) = @ARGV;

die "unknown suite: $suite" unless $suites{$suite};

if ($opt_mkdir) {
    if (! -d $target) {
        `mkdir -p $target`;
    }
}

if ($< != 0) {
    print "must run as root\n";
    exit 1;
}

my ($fh, $archive) = tempfile();
system "curl -o $archive $suites{$suite}" and die "could not fetch the suite";
system "/opt/local/bin/pv $archive | /opt/local/bin/gnutar xzf - -C $target --strip-components=1" and die "could not extract fs tree from suite";

print "$suite is successfully installed into $target\n";

__END__

=head1 NAME

noahstrap -- boostrap a linux system for noah

=head1 SYNOPSIS

  noahstrap [OPTION...] SUITE TARGET
  noahstrap [OPTION...] --list

=head1 DESCRIPTION

noahstrap bootstraps a linux system of SUITE for noah into TARGET directory from the repository.

=head1 OPTIONS

=head2 --list

Synchronizes the suite database and lists all available suites.

=head2 -p

Creates TARGET directory if it does not exists.

=head2 --help

Shows this message.

=head2 --version

Shows version information.

=head1 AUTHOR

Yuichi Nishiwaki
