#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

BEGIN
{
 eval
 {
  require JSON;
 };

 if ($@)
 {
  warn "Trying to auto-install the Perl JSON module... it may fail!";
  system("sudo yum -y install perl-JSON"); # you may want to disable this
  require JSON;
 }
}

my $verbose = scalar @ARGV;

use constant CODER => JSON->new()->relaxed()->utf8()->allow_nonref();
use constant CAN_CODER => JSON->new()->canonical()->utf8()->allow_nonref();

my $get = 'GET "http://169.254.169.254/latest';

my @todo = qw,dynamic/ meta-data/,;

my $crawled = {};

crawl();
print '%ec2_metadata=', CAN_CODER()->encode($crawled), "\n";

sub crawl
{
 while (scalar @todo)
 {
  my $item = shift @todo;

  # don't dump these
  next if $item =~ m,meta-data/public-keys/,;

  print "$item..." if $verbose;
  my $data = `$get/$item"`;

  if ($item =~ m,/$,) # it was a directory
  {
   foreach my $line (split "\n", $data)
   {
    if ($item =~ m,/$,)
    {
     push @todo, "$item$line";
    }
   }
  }
  else # a single item
  {
   if ($data)
   {
    my $d;
    eval
    {
     $d = CODER()->decode($data);
    };

    if (defined $d)
    {
     print "got JSON key $item, value [$data]\n" if $verbose;
     $crawled->{$item} = $d;
    }
    else
    {
     print "got key $item, value [$data]\n" if $verbose;
     $crawled->{$item} = $data;
    }
   }
  }
 }
}
