###########################################################################
# CLOUD SERVER API DOCUMENTATION
#
# Name: createServer
# Language: Perl
#
# Description: this function creates a new server
###########################################################################
use strict;
use LWP::UserAgent;
use URI::Escape;
use JSON;
require Http::Request::Common;

#ID access to API
my $TOKEN = "{YOUR_API_TOKEN}"; # e.g.: "f03c3c76cc853ee690b879909c9c6f2a"
my $url = "https://cloudpanel-api.1and1.com/v1";

sub _createServer
{
	my ($content) = @_;
	my $_command = $url ."/servers";
	my $_method = 'POST';

	#Create the request
	my $ua = LWP::UserAgent->new;
	my $request = HTTP::Request->new($_method => $_command);
	$request->header('X-TOKEN' => $TOKEN);
	$request->content_type('application/json');
	
	#Add additional parameters
	$request->content($content);

	#Get the response
	my $response = $ua->request($request);

	if($response)
	{
		#Get the response and close the handlers
		print $response->headers()->as_string ."\n";
		return $response->content;
		$response->close;
		$request->close;
	}
	else
	{
		#Get the error and close the handlers
		return "Http Error Code: ", $response->code, "\n";
		$request->close;
	}			
}

#Parameters
my $name = "My server";
my $description = "My server description";
my $appliance_id = "{YOUR_APPLIANCE_ID}"; # e.g.: "5340033E7FBBC308BC329414A0DF3C20"

#Hardware resources
my $vcore = 1;
my $cores_per_processor = 1;
my $ram = 1;
my $hdds = [{"size" => 40, "is_main" => JSON::true()}, {"size" => 20, "is_main" => JSON::false()}];

my $hardware = {"vcore" => $vcore, 
                "cores_per_processor" => $cores_per_processor, 
				"ram" => $ram,
				"hdds" => $hdds};

my %_query = ("name" => $name, "description" => $description, "hardware" => $hardware, "appliance_id" => $appliance_id);
my $query = encode_json \%_query;

#Create server
print _createServer($query);