# MIT No Attribution

# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import boto3
import os
ec2client = boto3.client('ec2')


def lambda_handler(event, context):
    # TODO Create volume from the Snapshot ID passed in the event
    print(event)
    volumestorage = ec2client.create_volume(
        AvailabilityZone=event.get('availabilityZone'),
        # response['Instances'][0]['Placement']['AvailabilityZone'],
        Size=int(os.environ['VolumeSize']),
        SnapshotId=event.get('snapshotID'),
        TagSpecifications=[
            {
                'ResourceType': 'volume',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': 'Isolated VOLUME backup'
                    },
                    {
                        'Key': 'Source',
                        'Value': event.get('instanceID')
                    }
                ]
            },
        ]
    )
    volumeresponse = ec2client.create_volume(
        AvailabilityZone=event.get('availabilityZone'),
        # response['Instances'][0]['Placement']['AvailabilityZone'],
        Size=int(os.environ['VolumeSize']),
        TagSpecifications=[
            {
                'ResourceType': 'volume',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': 'Isolated VOLUME'
                    },
                ]
            },
        ]
    )
    waiter = ec2client.get_waiter('volume_available')

    waiter.wait(
        VolumeIds=[
         volumeresponse['VolumeId']
        ]
    )
    response = ec2client.attach_volume(
        InstanceId=event.get('ForensicInstanceId'),
        VolumeId=volumeresponse['VolumeId'],
        Device='/dev/xvdf',

    )
    storage = ec2client.attach_volume(
        InstanceId=event.get('ForensicInstanceId'),
        VolumeId=volumestorage['VolumeId'],
        Device='/dev/xvdg',

    )
    #Adds wait time for SSM
    event['wait_time'] = 60
    return event
