#!/usr/bin/perl 

use strict;
use LWP;
use Data::Dumper;
use JSON;
use Getopt::Long;
use AppConfig;

my $help = 0;
my $host_ip = "";
my $level = "";
my $keyfile ="";
my $api_base  = "";
my $api_key   = "";
my $configfile = undef;

my $config = AppConfig->new( { CREATE => 1 } );

$config->define("api_url=s");
$config->define("api_keyfile=s");

foreach ( 
	"/usr/local/etc/hermes/hermes_config",
	"/usr/local/etc/hermes/config",
	"/etc/hermes/config",
	$ENV{"HOME"} . "/.hermes/config",
	$ENV{"HOME"} . "/.hermes_config",
) { $configfile = $_ if ( -f $_ ); }

GetOptions(
	"help"		=> \$help,
	"host=s"  	=> \$host_ip,
	"access=s" 	=> \$level,
	"configfile=s" 	=> \$configfile,
);

if (
	(not $configfile) ||
	(( $configfile ) && ( not -f $configfile )) 
)
{
	$help = 1;
}
else
{
	$config->file( $configfile );
	$api_base = $config->api_url;
	$keyfile = $config->api_keyfile;
}
if ( 
 ( ( $level ne "limited_read" ) &&
   ( $level ne "full_read" ) &&
   ( $level ne "read_write" ) ) ||
 ( not $api_base ) ||
 ( not $api_base =~ m/^http:\/\/\w+/ ) ||
 ( not $keyfile ) ||
 ( not -f $keyfile )
) {
	$help = 1;
}

if ( $help )
{
	print <<END_HELP;
$0 invalid usage.
   --help	Show help

 Required parameters:

  --host=host_ip_addr 
  --access=limited_read|full_read|read_write
  --configfile=/path/to/config/file  (--config, -c)

(c) 2012, Gjøvik University College, jonl. Licence: MIT.
END_HELP
	exit 0;
}


open KEY, "<" . $keyfile;
chomp( $api_key = <KEY> );
close KEY;

my ($g_ua, $session, $auth_key, $data);

$g_ua = LWP::UserAgent->new;
$g_ua->cookie_jar({}); # In-memory jar, look at HTTP::Cookies for persistant

login_apikey();

$data = exec_apinode('auth/new_apikey', { 'host_ip' => $host_ip, 'access' => $level });
print Dumper($data);
undef $data;

logout();
################################################################################################
sub exec_apinode($$)
{
	my $node = shift;
	my $param = shift;

	my ( $response, $data );

	$session = "" if not defined $session;
	$auth_key = "" if not defined $auth_key;
	my $url = $api_base . "/" . $node;

	$param->{'session'} = $session;
	$param->{'auth_key'} = $auth_key;

	$response = $g_ua->post( $url, $param );
	if ( $response->is_success )
	{
		if ( $response->content =~ m/\s*{/ )
		{
			$data = decode_json( $response->content);
		}
		else
		{
			$data = $response->content;
		}

	}
	return $data;
}

sub login_apikey
{
	my $response = $g_ua->post( $api_base . "/auth/login",
		[ "api_key" => $api_key ] );

	my $data = decode_json( $response->content) if $response->is_success;
	die("HTTP error") unless $response->is_success;

	if ( $data->{'response'} eq "ok" )
	{
		$session = $data->{'session'};
		$auth_key = $data->{'auth_key'};
	}
	else
	{
		exit;
	}
	undef $data; undef $response;
}

sub logout
{
	my $response = $g_ua->post( $api_base . "/auth/logout",
		[ "session" => $session ] );
	die("HTTP error") unless $response->is_success;
	undef $session; undef $auth_key;
}
