"""
SYNOPSIS
--------
    Get the details of unused resources present across regions in the AWS account

DESCRIPTION
-----------
    This script provides a detailed overview of the number of unused resources present in the AWS account. 
	It provides service-wise details of unused resources lying around in all the regions of the AWS account. 

PREREQUISITES
-------------
        -   Workstation with Python version 3 and above
        -   AWS python-based SDK: boto3
            Installation command: pip3 install boto3
        -   pandas framework and openpyxl for reporting operations (xlsx file). 
            Installation command(s): 
            - pip3 install pandas
            - pip3 install openpyxl
        -   User credentials (Access Key Id and Secret Accces Key) of a user having atleast the Security Audit permission and above on the AWS account

EXAMPLE
-------
    This script can be executed on a python compiler (AWS Cloudshell, Powershell, bash, any command line tool with python installed)
    Command: python ./unused_aws_resources.py --accessKey <AWS Access Key Id> --secretKey <AWS Secret Access Key>

OUTPUT
------
    - The script will provide a summarized count of all unused resources in the account.
    - For a detailed view, the user can refer to the .xlsx file that will be generated by the script.

"""

import json
import boto3
import argparse
import multiprocessing
import csv
import os
import pandas as pd
import sys
import glob

from urllib.request import urlopen

def ebs_volume(function, credentials, unused_resource_count, region_list):
    print('Scanning EBS Volumes')

    volume_count = 0
    unused_volume_detail = []

    for region in region_list:
        try:
            ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            volumes = list(ec2.volumes.all())
            
            unused_volumes = set([volume.volume_id for volume in volumes if volume.state == 'available'])
            for volume_id in unused_volumes:
                unused_volume_detail.append({'ResourceType':'AWS::EC2::Volume','ResourceId':volume_id,'Region':region})
            volume_count+=len(unused_volumes)
        except:
            pass
    
    if volume_count:
        unused_volume_detail = json.loads(json.dumps(unused_volume_detail))
        f = csv.writer(open("./aws_logs/ebs_volume.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_volume_detail in unused_volume_detail:
            f.writerow([unused_volume_detail["ResourceType"],
                        unused_volume_detail["ResourceId"],
                        unused_volume_detail["Region"]])

    unused_resource_count[function] = volume_count

def elastic_ip(function, credentials, unused_resource_count, region_list):
    print('Scanning Elastic IPs')

    eip_count = 0
    unused_eip_detail = []
    
    for region in region_list:
        try:
            ec2_client = boto3.client('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            
            eip_data = ec2_client.describe_addresses()['Addresses']
            for eip in eip_data:
                try:
                    AssociationId = eip['AssociationId']
                except:
                    AssociationId = ''
                
                if not AssociationId:
                    unused_eip_detail.append({'ResourceType':'AWS::EC2::EIP','ResourceId':eip['AllocationId'],'Region':region})
                    eip_count += 1
        except:
            pass

    if eip_count:
        unused_eip_detail = json.loads(json.dumps(unused_eip_detail))
        f = csv.writer(open("./aws_logs/elastic_ip.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_eip_detail in unused_eip_detail:
            f.writerow([unused_eip_detail["ResourceType"],
                        unused_eip_detail["ResourceId"],
                        unused_eip_detail["Region"]])

    unused_resource_count[function] = eip_count

def network_interface(function, credentials, unused_resource_count, region_list):
    print('Scanning Network Interfaces')

    ni_count = 0
    unused_ni_detail = []

    for region in region_list:
        try:
            ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            network_interfaces = list(ec2.network_interfaces.all())
            
            unused_nis = set([ni.network_interface_id for ni in network_interfaces if ni.status == 'available'])
            for network_interface_id in unused_nis:
                unused_ni_detail.append({'ResourceType':'AWS::EC2::NetworkInterface','ResourceId':network_interface_id,'Region':region})
            ni_count+=len(unused_nis)
        except:
            pass

    if ni_count:
        unused_ni_detail = json.loads(json.dumps(unused_ni_detail))
        f = csv.writer(open("./aws_logs/network_interface.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_ni_detail in unused_ni_detail:
            f.writerow([unused_ni_detail["ResourceType"],
                        unused_ni_detail["ResourceId"],
                        unused_ni_detail["Region"]])

    unused_resource_count[function] = ni_count

def vpc(function, credentials, unused_resource_count, region_list):
    print('Scanning VPCs')

    vpc_count = 0
    unused_vpc_detail = []

    for region in region_list:
        try:
            ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            vpcs = list(ec2.vpcs.all())
            network_interfaces = list(ec2.network_interfaces.all())
            
            all_vpcs = set([vpc.vpc_id for vpc in vpcs])
            all_active_vpcs = set([vpc['VpcId'] for ni in network_interfaces for vpc in ni.vpc])
            unused_vpcs = all_vpcs - all_active_vpcs
            for vpcid in unused_vpcs:
                unused_vpc_detail.append({'ResourceType':'AWS::EC2::VPC','ResourceId':vpcid,'Region':region})
            vpc_count+=len(unused_vpcs)
        except:
            pass

    if vpc_count:
        unused_vpc_detail = json.loads(json.dumps(unused_vpc_detail))
        f = csv.writer(open("./aws_logs/vpc.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_vpc_detail in unused_vpc_detail:
            f.writerow([unused_vpc_detail["ResourceType"],
                        unused_vpc_detail["ResourceId"],
                        unused_vpc_detail["Region"]])

    unused_resource_count[function] = vpc_count

def subnet(function, credentials, unused_resource_count, region_list):
    print('Scanning Subnets')

    subnet_count = 0
    unused_subnet_detail = []

    for region in region_list:
        try:
            ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            subnets = list(ec2.subnets.all())
            network_interfaces = list(ec2.network_interfaces.all())
            
            all_subnets = set([subnet.subnet_id for subnet in subnets])
            all_active_subnets = set([subnet['SubnetId'] for ni in network_interfaces for subnet in ni.subnet])
            unused_subnets = all_subnets - all_active_subnets
            for subnetid in unused_subnets:
                unused_subnet_detail.append({'ResourceType':'AWS::EC2::Subnet','ResourceId':subnetid,'Region':region})
            subnet_count+=len(unused_subnets)
        except:
            pass

    if subnet_count:
        unused_subnet_detail = json.loads(json.dumps(unused_subnet_detail))
        f = csv.writer(open("./aws_logs/subnet.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_subnet_detail in unused_subnet_detail:
            f.writerow([unused_subnet_detail["ResourceType"],
                        unused_subnet_detail["ResourceId"],
                        unused_subnet_detail["Region"]])

    unused_resource_count[function] = subnet_count

def security_group(function, credentials, unused_resource_count, region_list):
    print('Scanning Security Groups')

    sg_count = 0
    unused_sg_detail = []
    
    for region in region_list:
        try:
            ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            sgs = list(ec2.security_groups.all())
            network_interfaces = list(ec2.network_interfaces.all())
            
            all_sgs = set([sg.group_id for sg in sgs])
            all_inst_sgs = set([sg['GroupId'] for ni in network_interfaces for sg in ni.groups])
            unused_sgs = all_sgs - all_inst_sgs
            for sgid in unused_sgs:
                unused_sg_detail.append({'ResourceType':'AWS::EC2::SecurityGroup','ResourceId':sgid,'Region':region})
            sg_count+=len(unused_sgs)
        except:
            pass
    
    if sg_count:
        unused_sg_detail = json.loads(json.dumps(unused_sg_detail))
        f = csv.writer(open("./aws_logs/security_group.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_sg_detail in unused_sg_detail:
            f.writerow([unused_sg_detail["ResourceType"],
                        unused_sg_detail["ResourceId"],
                        unused_sg_detail["Region"]])

    unused_resource_count[function] = sg_count

def classic_loadbalancer(function, credentials, unused_resource_count, region_list):
    print('Scanning Classic Load balancers')

    elb_count = 0
    unused_elb_detail = []
    
    for region in region_list:
        try:
            classic_lb = boto3.client('elb', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            
            paginated_data=[]
            elb_paginator = classic_lb.get_paginator('describe_load_balancers')
            for load_balancers in elb_paginator.paginate():
                paginated_data.extend(load_balancers['LoadBalancerDescriptions'])
        
            for elb_detail in paginated_data:
                instance_health_status = []
                instance_data = classic_lb.describe_instance_health(LoadBalancerName=elb_detail['LoadBalancerName'])['InstanceStates']
                for instance in instance_data:
                    instance_health_status.append(instance['State'])
                if 'InService' not in instance_health_status:
                    unused_elb_detail.append({'ResourceType':'AWS::ElasticLoadBalancing::LoadBalancer','ResourceId':elb_detail['LoadBalancerName'],'Region':region})
                    elb_count+=1
        except:
            pass

    if elb_count:
        unused_elb_detail = json.loads(json.dumps(unused_elb_detail))
        f = csv.writer(open("./aws_logs/classic_loadbalancer.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_elb_detail in unused_elb_detail:
            f.writerow([unused_elb_detail["ResourceType"],
                        unused_elb_detail["ResourceId"],
                        unused_elb_detail["Region"]])

    unused_resource_count[function] = elb_count

def app_nw_gateway_loadbalancer(function, credentials, unused_resource_count, region_list):
    print('Scanning Application/Network/Gateway Load balancers')

    elbv2_count = 0
    unused_elbv2_detail = []
    
    for region in region_list:
        try:
            elbv2 = boto3.client('elbv2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            
            paginated_data=[]
            elbv2_paginator = elbv2.get_paginator('describe_load_balancers')
            for load_balancers in elbv2_paginator.paginate():
                paginated_data.extend(load_balancers['LoadBalancers'])
        
            for elbv2_detail in paginated_data:
                target_health_status = []
                try:  
                    target_group_detail = elbv2.describe_target_groups(LoadBalancerArn=elbv2_detail['LoadBalancerArn'])['TargetGroups']
                    for target_group in target_group_detail:
                        target_group_health = elbv2.describe_target_health(TargetGroupArn=target_group['TargetGroupArn'])['TargetHealthDescriptions']
                        for target in target_group_health:
                            target_health_status.append(target['TargetHealth']['State'])
                except:
                    pass

                if 'healthy' not in target_health_status:
                    unused_elbv2_detail.append({'ResourceType':'AWS::ElasticLoadBalancingV2::LoadBalancer', 'LoadBalancer_Type':elbv2_detail['Type'], 'ResourceId':elbv2_detail['LoadBalancerName'],'Region':region})
                    elbv2_count+=1
        except:
            pass

    if elbv2_count:
        unused_elbv2_detail = json.loads(json.dumps(unused_elbv2_detail))
        f = csv.writer(open("./aws_logs/app_nw_gateway_loadbalancer.csv", "w", newline=''))

        f.writerow(["ResourceType", "LoadBalancer_Type", "ResourceId", "Region"])

        for unused_elbv2_detail in unused_elbv2_detail:
            f.writerow([unused_elbv2_detail["ResourceType"],
                        unused_elbv2_detail["LoadBalancer_Type"],
                        unused_elbv2_detail["ResourceId"],
                        unused_elbv2_detail["Region"]])

    unused_resource_count[function] = elbv2_count

def iam_user(function, credentials, unused_resource_count, region_list):
    print('Scanning IAM Users')

    iamuser_count = 0
    unused_iamuser_detail = []

    try:
        iam = boto3.resource('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
        iam_client = boto3.client('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
        
        iamuser_data = list(iam.users.all())
        for user in iamuser_data:
            if not user.password_last_used and not iam_client.list_access_keys(UserName=user.name)['AccessKeyMetadata']:
                unused_iamuser_detail.append({'ResourceType':'AWS::IAM::User', 'ResourceId': user.name, 'Region':'Global'})
                iamuser_count += 1
    except:
        pass

    if iamuser_count:
        unused_iamuser_detail = json.loads(json.dumps(unused_iamuser_detail))
        f = csv.writer(open("./aws_logs/iam_user.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_iamuser_detail in unused_iamuser_detail:
            f.writerow([unused_iamuser_detail["ResourceType"],
                        unused_iamuser_detail["ResourceId"],
                        unused_iamuser_detail["Region"]])

    unused_resource_count[function] = iamuser_count

def iam_group(function, credentials, unused_resource_count, region_list):
    print('Scanning IAM Groups')

    iamgroup_count = 0
    unused_iamgroup_detail = []

    try:
        iam = boto3.resource('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
        iam_client = boto3.client('iam', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'])
        
        iamgroup_data = list(iam.groups.all())
        for group in iamgroup_data:
            if not iam_client.get_group(GroupName=group.name)['Users']:
                unused_iamgroup_detail.append({'ResourceType':'AWS::IAM::Group', 'ResourceId': group.name, 'Region':'Global'})
                iamgroup_count += 1
    except:
        pass

    if iamgroup_count:
        unused_iamgroup_detail = json.loads(json.dumps(unused_iamgroup_detail))
        f = csv.writer(open("./aws_logs/iam_group.csv", "w", newline=''))

        f.writerow(["ResourceType", "ResourceId", "Region"])

        for unused_iamgroup_detail in unused_iamgroup_detail:
            f.writerow([unused_iamgroup_detail["ResourceType"],
                        unused_iamgroup_detail["ResourceId"],
                        unused_iamgroup_detail["Region"]])

    unused_resource_count[function] = iamgroup_count

def main(arg):
    access_key = arg.accessKey
    secret_key = arg.secretKey
    region_list = []
    unused_resource_details = {}

    try:
        print("Connecting to AWS account ")
        session = boto3.session.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
    except:
        print("\033[1;31;40m ""Please do Check for Credentials provided or Internet Connection and Try Again\n")
        quit()

    iam = session.client('sts')
    account_id = iam.get_caller_identity()["Account"]
    print("Successfully connected to AWS account", account_id)

    print("Scanning for unused resources across all available regions.")
    print("Wait for few minutes...\n")

    function_list= [ ebs_volume, elastic_ip, network_interface, vpc, subnet, security_group, classic_loadbalancer, app_nw_gateway_loadbalancer,
                     iam_user, iam_group ]

    print("Collecting list of enabled region")
    available_regions = session.client('ec2',region_name="us-east-1")
    enabled_regions = available_regions.describe_regions()['Regions']
    for region in enabled_regions:
        region_list.append(region['RegionName'])
    
    manager = multiprocessing.Manager()
    unused_resource_count = manager.dict()
    credentials = manager.dict()
    credentials['access_key'] = access_key
    credentials['secret_key'] = secret_key
    credentials['account_id'] = account_id
    jobs = []

    try:
        os.mkdir("./aws_logs")
    except:
        pass

    for function in function_list:
        try:
            p = multiprocessing.Process(target=function, args=(function, credentials, unused_resource_count, region_list))
            jobs.append(p)
            p.start()
        except:
            print("Exception occurred while creating processes. Please try again later!")
            quit()
    
    if jobs:
        for process in jobs:
            try:
                process.join()
            except:
                print("Exception occurred while joining processes. Please try again later!")
                quit()

    os.chdir('./aws_logs')
    writer = pd.ExcelWriter('unused_resources.xlsx')
    all_files = glob.glob("*.csv")

    for f in all_files:
        df = pd.read_csv(f)
        df.to_excel(writer,sheet_name=f.split('.')[0], index=False)
    writer.save()

    for f in all_files:
        os.remove(f)

    print("Completed account scan")
    # Updating Resource Count Object
    unused_resource_details.update({ 'AWS::EC2::Volume': unused_resource_count[ebs_volume],
                                     'AWS::EC2::EIP': unused_resource_count[elastic_ip],
                                     'AWS::EC2::NetworkInterface': unused_resource_count[network_interface],
                                     'AWS::EC2::VPC': unused_resource_count[vpc],
                                     'AWS::EC2::Subnet': unused_resource_count[subnet],
                                     'AWS::EC2::SecurityGroup': unused_resource_count[security_group],
                                     'AWS::ElasticLoadBalancing::LoadBalancer': unused_resource_count[classic_loadbalancer],
                                     'AWS::ElasticLoadBalancingV2::LoadBalancer': unused_resource_count[app_nw_gateway_loadbalancer],
                                     'AWS::IAM::User': unused_resource_count[iam_user],
                                     'AWS::IAM::Group': unused_resource_count[iam_group]
                                    })

    # Showing Resource Distribution
    print("\nUnused Resources in the Account:")
    unused_resource_count = 0
    for key, value in sorted(unused_resource_details.items(), key=lambda x: x[1], reverse=True):
        if value != 0:
            print("\t{} : {}".format(key, value))
            unused_resource_count+=value

    print("\n\nSummary:")
    print("\tTotal Unused Resources:", unused_resource_count)
    print("\n\nDetailed unused resource information can be found at: aws_logs/unused_resources.xlsx")

if(__name__ == '__main__'):
    arg_parser = argparse.ArgumentParser(prog='unused_aws_resources',
                                        usage='%(prog)s [options]',
                                        description='Count AWS resources')

    # Add the arguments
    arg_parser.add_argument('--accessKey',
                        type=str,
                        required=True,
                        help='AWS Access Key')
    arg_parser.add_argument('--secretKey',
                        type=str,
                        required=True,
                        help='AWS Secret Key')

    # Execute the parse_args() method
    args = arg_parser.parse_args()
    main(args)
