#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Std;
use English;
use POSIX;
use Data::Dumper;
use JSON::PP;

#
# A simple CLI wrapper around libvnode_docker::analyzeImageWithBusyboxCommand.
#
sub usage()
{
    print "Usage: analyze-image-with-busybox [-d <level>] [-c] <image> [command... ]\n".
	  "\n".
          "  -d <level>  Debug mode\n".
	  "  -c <json>   Customize the temporary container config according".
	  "              to JSON passed to the Docker run API command.\n";
    exit(1);
}
my $optlist = "hd:c:";
my $debug = 0;
my $config = {};

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (!getopts($optlist,\%options)) {
    usage();
}
if (defined($options{"h"})) {
    usage();
}
if (defined($options{"d"})) {
    $debug = $options{"d"};
}
if (defined($options{"c"})) {
    $config = decode_json($options{"c"});
}
usage()
    if (@ARGV < 2);

#
# Must be root.
# 
if ($UID != 0) {
    die("*** $0:\n".
	"    Must be root to run this script!\n");
}

#
# Turn off line buffering on output
#
$| = 1;

# Drag in path stuff so we can find emulab stuff.
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }

use libsetup;
use libvnode_docker;

if ($debug) {
    TBDebugTimeStampsOn();
    libvnode_docker::setDebug($debug);
}
my $ret;
my $image = shift(@ARGV);
my $rc = libvnode_docker::analyzeImageWithBusyboxCommand(
    $image,$config,\$ret,@ARGV);
if ($rc) {
    fatal("ERROR: failed to analyze $image with busybox!\n");
}
else {
    print "Successfully analyzed $image with busybox:\n$ret";
}
exit(0);
