#-*-Perl-*-

# Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl test.t'

use strict;
use ExtUtils::MakeMaker;
use File::Temp qw(tempfile);
use FindBin '$Bin';
use lib "$Bin/lib","$Bin/../lib","$Bin/../blib/lib","$Bin/../blib/arch";

use constant TEST_COUNT => 11;
use Test::More tests => TEST_COUNT;
use EC2TestSupport;

# this script tests the keypairs functions

setup_environment();

require_ok('VM::EC2');
SKIP: {
skip "account information unavailable",TEST_COUNT-1 unless setup_environment();

my $ec2 = VM::EC2->new(-print_error=>1,-region=>'us-east-1') or BAIL_OUT("Can't load VM::EC2 module");

# make a key
my $kn      = 'VM-EC2 Test Key';
$ec2->delete_key_pair($kn);  # in case it was already there
my $key     = $ec2->create_key_pair($kn);
ok($key,'create key');
is($key->name,$kn,'create key name matches');

my @keys    = $ec2->describe_key_pairs;
ok(scalar @keys,'describe keys');

my @i = grep {$_->name eq $key} @keys;
is(scalar @i,1,'get keys');
is($i[0]->fingerprint,$key->fingerprint,'fingerprints match');
ok($ec2->delete_key_pair($key),'delete key');

$ec2->print_error(0); # disable error message
@keys = $ec2->describe_key_pairs($kn);
is(scalar @keys,0,'delete key works');
$ec2->print_error(1); # reenable

# this is a public key generated by ssh-keygen; the corresponding private key has been deleted
my $bogus_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8o5qe3vdaONNbM3tnGKZwZWwPvTNTP69m3N8BNCqArsIellAuKzb9XwgQ85i5xiScetCMW99Pci9s9ky3WpctkJAxl645AiGF5u3xg7y+lDHTO0VI/hSWamIYtsP34nvM6eSkqaIoRZjgLvQE2kIoJQZFWMEY3cCPFBojWWWhSrpLh8YTra7IrjONGMzyq97bbqMg/1B146f2ZZKBpQEVNmeObf8LsNLJhWOLy6YsEytmH3kp5GrMmlTZoGBFHX7w+dkxIVgpm+5/zHDJuBgzB2DICR/mBmlTNZnPGEvvIzlPWsehdamoGWbDIssiGpTvGj21uhvtzCwhcni1jusn BogusKey';

$key = $ec2->import_key_pair('MyBogusKeyPair'=>$bogus_key) or warn $ec2->error_str;
ok($key,'import key pair');
BAIL_OUT($ec2->error_str) unless $key;
@keys = $ec2->describe_key_pairs('MyBogusKeyPair');
ok(scalar @keys,'import key pair');
ok($ec2->delete_key_pair($key),'delete imported key');
}

exit 0;
