'''
Created on 21 sept. 2020

@author: hagimont
'''

import boto3
from botocore.exceptions import ClientError
import time


def cleanDC(region):
    
    print("==================")
    print("     "+region)
    print("==================")
    
    my_session = boto3.session.Session(
        aws_access_key_id='xxxxxxxxxxxxxxxxxxxx',
        aws_secret_access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        region_name=region)

    # #### AUTO SCALING GROUPS
    clientasg = my_session.client('autoscaling')
    response = clientasg.describe_auto_scaling_groups()
    for asg in response['AutoScalingGroups']:
        try:
            print('AUTOSCALINGGROUP:'+asg['AutoScalingGroupName'])
            clientasg.delete_auto_scaling_group(AutoScalingGroupName=asg['AutoScalingGroupName'], ForceDelete=True)
        except Exception as e:
            print("pb with delete_auto_scaling_group")
            print(e)
 
    #### LAUNCH CONFIGURATIONS
    response = clientasg.describe_launch_configurations()
    for lc in response['LaunchConfigurations']:
        try:
            print('LAUNCHCONFIGURATION:'+lc['LaunchConfigurationName'])
            clientasg.delete_launch_configuration(LaunchConfigurationName=lc['LaunchConfigurationName'])
        except Exception as e:
            print("pb with delete_launch_configuration")
            print(e)

    #### LOAD BALANCERS
    clientlb = my_session.client('elbv2')
    response = clientlb.describe_load_balancers()
    for lb in response['LoadBalancers']:
        try:
            print('LOADBALANCER:'+lb['LoadBalancerName'])
            clientlb.delete_load_balancer(LoadBalancerArn=lb['LoadBalancerArn'])
        except Exception as e:
            print("pb with delete_load_balancer")
            print(e)

    #### TARGET GROUPS
    response = clientlb.describe_target_groups()
    for tg in response['TargetGroups']:
        while True:
            try:
                print('TARGETGROUP:'+tg['TargetGroupName'])
                clientlb.delete_target_group(TargetGroupArn=tg['TargetGroupArn'])
                break
            except Exception:
                print('try again (10s sleep)')
                time.sleep(10)
    
    ####  INSTANCES
    clientec2 = my_session.client('ec2')
    response = clientec2.describe_instances()
    liste = []
    for r in response['Reservations']:
        for i in r['Instances']:
            liste.append(i['InstanceId'])
            print('INSTANCE:'+i['InstanceId'])
    try:
        if liste:
            clientec2.terminate_instances(InstanceIds=liste)
    except Exception as e:
        print("pb with terminate_instances")
        print(e)

    #### IMAGES
    response = clientec2.describe_images(Owners=['self'])
    for img in response['Images']:
        try:
            print('IMAGE:'+img['ImageId'])
            clientec2.deregister_image(ImageId=img['ImageId'])
        except Exception as e:
            print("pb with deregister_image")
            print(e)

    #### SNAPSHOTS
    response = clientec2.describe_snapshots(OwnerIds=['self'])
    for sn in response['Snapshots']:
        try:
            print('IMAGE:'+sn['SnapshotId'])
            clientec2.delete_snapshot(SnapshotId=sn['SnapshotId'])
        except Exception as e:
            print("pb with delete_snapshot")
            print(e)

    #### KEY PAIRS
    response = clientec2.describe_key_pairs()
    for kp in response['KeyPairs']:
        try:
            print('KEYPAIR:'+kp['KeyPairId'])
            clientec2.delete_key_pair(KeyPairId=kp['KeyPairId'])
        except Exception as e:
            print("pb with delete_key_pair")
            print(e)

    ####  SECURITY GROUPS
    response = clientec2.describe_security_groups()
    for sg in response['SecurityGroups']:
        if (sg['GroupName'] != 'default'):
            while True:
                try:
                    print('SECURITYGROUP:'+sg['GroupId'])
                    clientec2.delete_security_group(GroupId=sg['GroupId'])
                    break
                except ClientError:
                    print('try again (10s sleep)')
                    time.sleep(10)

    print
    print


cleanDC('eu-west-1')
cleanDC('eu-west-2')
cleanDC('eu-west-3')
cleanDC('eu-north-1')
#cleanDC('eu-south-1')
cleanDC('eu-central-1')


