/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper

//sdk imports
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.IpPermission;


def ch = new CommandHelper(new File('.'));
def apTool = new AirPluginTool(this.args[0], this.args[1]);
def props = apTool.getStepProperties();

def accessKeyId = props['accessKeyId'];
def secretKey = props['secretKey'];
def name = props['name'];
def description = props['description'];
def vpcId = props['vpcId'];
def secGroupFileProp = props['secGroupFile'];


def ipPermissions = null;
if (secGroupFileProp) {
    File secGroupFile = new File(secGroupFileProp);
    def slurper = new XmlSlurper().parse(secGroupFile);
    name = slurper.@name.text();
    vpcId = slurper.@vpcId.text();
    description = slurper.@description.text();

    ipPermissions = new ArrayList<IpPermission>();
    slurper.ipPermission.each { ipPerm ->
        IpPermission ipPermission = new IpPermission()
                                    .withFromPort(Integer.valueOf(ipPerm.@fromPort.text()))
                                    .withToPort(Integer.valueOf(ipPerm.@toPort.text()))
                                    .withIpProtocol(ipPerm.@protocol.text());

        List<String> ipRanges = new ArrayList<String>();
        ipPerm.ipRange.each { range ->
              ipRanges << range.@value.text();
        }
        
        ipPermission = ipPermission.withIpRanges(ipRanges);
        ipPermissions << ipPermission;
    }
}
       

AWSCredentials creds = null;
creds = new BasicAWSCredentials(accessKeyId, secretKey);

AmazonEC2 ec2 = new AmazonEC2Client(creds);

println "Creating Security Group name : $name \n with description : $description";
CreateSecurityGroupRequest secGroupReq = new CreateSecurityGroupRequest(name, description);

if (vpcId) {
    secGroupReq = secGroupReq.withWpcId(vpcId);
}

ec2.createSecurityGroup(secGroupReq);

if (ipPermissions) {
    println "Creating Permissions based on input xml file";
    AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(name, ipPermissions);
    ec2.authorizeSecurityGroupIngress(ingressRequest);
}
