package VM::EC2::REST::keys;

use strict;
use VM::EC2 '';  # important not to import anything!
package VM::EC2;  # add methods to VM::EC2

VM::EC2::Dispatch->register(
    DescribeKeyPairs     => 'fetch_items,keySet,VM::EC2::KeyPair',
    CreateKeyPair        => 'VM::EC2::KeyPair',
    ImportKeyPair        => 'VM::EC2::KeyPair',
    DeleteKeyPair        => 'boolean',
    );

=head1 NAME VM::EC2::REST::keys

=head1 SYNOPSIS

 use VM::EC2 ':standard';

=head1 METHODS

Implemented:
 DescribeKeyPairs
 CreateKeyPair
 ImportKeyPair
 DeleteKeyPair

Unimplemented:
 (none)

These methods let you manipulate ssh key pairs.

=head2 @keys = $ec2->describe_key_pairs(@names);

=head2 @keys = $ec2->describe_key_pairs(\%filters);

=head2 @keys = $ec2->describe_key_pairs(-key_name => \@names,
                                        -filter    => \%filters);

Searches for ssh key pairs matching the provided filters and return
a series of VM::EC2::KeyPair objects.

Optional arguments:

 -key_name      A single key name or an arrayref containing a list
                   of names

 -filter          Filter on tags and other attributes.

The full list of key filters can be found at:
http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html

=cut

sub describe_key_pairs {
    my $self = shift;
    my %args = $self->args(-key_name=>@_);
    my @params = $self->list_parm('KeyName',\%args);
    push @params,$self->filter_parm(\%args);
    return $self->call('DescribeKeyPairs',@params);
}

=head2 $key = $ec2->create_key_pair($name)

Create a new key pair with the specified name (required). If the key
pair already exists, returns undef. The contents of the new keypair,
including the PEM-encoded private key, is contained in the returned
VM::EC2::KeyPair object:

  my $key = $ec2->create_key_pair('My Keypair');
  if ($key) {
    print $key->fingerprint,"\n";
    print $key->privateKey,"\n";
  }

=cut

sub create_key_pair {
    my $self = shift; 
    my $name = shift or croak "Usage: create_key_pair(\$name)"; 
    $name =~ /^[\w _-]+$/
	or croak    "Invalid keypair name: must contain only alphanumerics, spaces, dashes and underscores";
    my @params = (KeyName=>$name);
    $self->call('CreateKeyPair',@params);
}

=head2 $key = $ec2->import_key_pair($name,$public_key)

=head2 $key = $ec2->import_key_pair(-key_name            => $name,
                                    -public_key_material => $public_key)

Imports a preexisting public key into AWS under the specified name.
If successful, returns a VM::EC2::KeyPair. The public key must be an
RSA key of length 1024, 2048 or 4096. The method can be called with
two unnamed arguments consisting of the key name and the public key
material, or in a named argument form with the following argument
names:

  -key_name     -- desired name for the imported key pair (required)
  -name         -- shorter version of -key_name

  -public_key_material -- public key data (required)
  -public_key   -- shorter version of the above

This example uses Net::SSH::Perl::Key to generate a new keypair, and
then uploads the public key to Amazon.

  use Net::SSH::Perl::Key;

  my $newkey = Net::SSH::Perl::Key->keygen('RSA',1024);
  $newkey->write_private('.ssh/MyKeypair.rsa');  # save private parts

  my $key = $ec2->import_key_pair('My Keypair' => $newkey->dump_public)
      or die $ec2->error;
  print "My Keypair added with fingerprint ",$key->fingerprint,"\n";

Several different formats are accepted for the key, including SSH
"authorized_keys" format (generated by L<ssh-keygen> and
Net::SSH::Perl::Key), the SSH public keys format, and DER format. You
do not need to base64-encode the key or perform any other
pre-processing.

Note that the algorithm used by Amazon to calculate its key
fingerprints differs from the one used by the ssh library, so don't
try to compare the key fingerprints returned by Amazon to the ones
produced by ssh-keygen or Net::SSH::Perl::Key.

=cut

sub import_key_pair {
    my $self = shift; 
    my %args;
    if (@_ == 2 && $_[0] !~ /^-/) {
	%args = (-key_name            => shift,
		 -public_key_material => shift);
    } else {
	%args = @_;
    }
    my $name = $args{-key_name}           || $args{-name}        or croak "-key_name argument required";
    my $pkm  = $args{-public_key_material}|| $args{-public_key}  or croak "-public_key_material argument required";
    my @params = (KeyName => $name,PublicKeyMaterial=>encode_base64($pkm));
    $self->call('ImportKeyPair',@params);
}

=head2 $result = $ec2->delete_key_pair($name)

Deletes the key pair with the specified name (required). Returns true
if successful.

=cut

sub delete_key_pair {
    my $self = shift; my $name = shift or croak "Usage: delete_key_pair(\$name)"; 
    $name =~ /^[\w _-]+$/
	or croak    "Invalid keypair name: must contain only alphanumerics, spaces, dashes and underscores";
    my @params = (KeyName=>$name);
    $self->call('DeleteKeyPair',@params);
}


=head1 SEE ALSO

L<VM::EC2>

=head1 AUTHOR

Lincoln Stein E<lt>lincoln.stein@gmail.comE<gt>.

Copyright (c) 2011 Ontario Institute for Cancer Research

This package and its accompanying libraries is free software; you can
redistribute it and/or modify it under the terms of the GPL (either
version 1, or at your option, any later version) or the Artistic
License 2.0.  Refer to LICENSE for the full license text. In addition,
please see DISCLAIMER.txt for disclaimers of warranty.

=cut


1;
