#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;
use JSON;

my $VERSION = 3;

my( $prettyPrint, $s3Bucket, $s3Key );
GetOptions(
	'pretty-print'	=> \$prettyPrint,
	's3-bucket'		=> \$s3Bucket,
	's3-key'		=> \$s3Key
);
if(! $s3Bucket) { $s3Bucket = { "Fn::Join" => [ "-", [ "condor-annex", { "Ref" => "AWS::Region" } ] ] }; }
if(! $s3Key) { $s3Key = "lease-${VERSION}.zip"; }

	my $template;
	$template->{ AWSTemplateFormatVersion } = "2010-09-09";
	$template->{ Description } = "HTCondor Annex Lease Implementation";

	my $lambdaBasicExecutionPolicy = {
		PolicyName => "lambda_basic_execution",
		PolicyDocument => {
			Version => "2012-10-17",
			Statement => [ {
				Effect => "Allow",
				Action => [
					"logs:CreateLogGroup",
					"logs:CreateLogStream",
					"logs:PutLogEvents"
					],
				Resource => "arn:aws:logs:*:*:*"
			} ]
		}
	};

	my $assumeRoleFromLambda = {
		Version => "2012-10-17",
		Statement => [ {
			Effect => "Allow",
			Action => [ "sts:AssumeRole" ],
			Principal => { Service => [ "lambda.amazonaws.com" ] }
		} ]
	};

	$template->{ Resources }->{ LeaseFunctionRole } = {
		Type => "AWS::IAM::Role",
		Properties => {
			AssumeRolePolicyDocument => $assumeRoleFromLambda,
			Policies => [
				$lambdaBasicExecutionPolicy,
				{
					PolicyName => "LambdaLeasePolicy",
					PolicyDocument => {
						Version => "2012-10-17",
						Statement => [
							{
								Effect => "Allow",
								Action => [
									"events:*",

									"ec2:CancelSpotFleetRequests",
									"ec2:DescribeSpotFleetRequests",

									"ec2:DescribeInstances",
									"ec2:TerminateInstances",
								],
								Resource => "*"
							}
						]
					}
				}
			]
		}
	};

	$template->{ Resources }->{ LeaseFunction } = {
		Type => "AWS::Lambda::Function",
		DependsOn => "LeaseFunctionRole",
		Properties => {
			Role => { "Fn::GetAtt" => [ "LeaseFunctionRole", "Arn" ] },
			Runtime => "nodejs4.3",
			Timeout => 60,
			Handler => "lease.handler",
			Code => {
				S3Bucket => $s3Bucket,
				S3Key => $s3Key
			}
		}
	};

	$template->{ Resources }->{ LeaseFunctionPermissions } = {
		Type => "AWS::Lambda::Permission",
		DependsOn => "LeaseFunction",
		Properties => {
			Action => "lambda:InvokeFunction",
			FunctionName => { "Fn::GetAtt" => [ "LeaseFunction", "Arn" ] },
			Principal => "events.amazonaws.com",
			SourceArn => { "Fn::Join" => [ ":", [ "arn:aws:events", { "Ref" => "AWS::Region" }, { "Ref" => "AWS::AccountId" }, "*" ] ] }
		}
	};

if( defined( $prettyPrint ) ) {
	print( to_json( $template, { utf8 => 1, pretty => 1 } ) . "\n" );
} else {
	print( encode_json( $template ) . "\n" );
}

exit( 0 );
