#!/bin/bash

region="eu-central-1"
profile="sme-aoma-delivery-prod"

add_dependency_files() {

echo "Enter the Role ARN which terraform will assume: "
read assume_role
echo "Enter VPC Name which you want to import. ALL LOWER CASE"
read vpc_name

echo '''## Provider Section ##

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}
''' > provider.tf

echo ""
echo "provider \"aws\" {" >> provider.tf
echo "region = \"${region}\"" >> provider.tf
echo "profile = \"${profile}\"" >> provider.tf
echo "#assume_role {" >> provider.tf
echo "#  role_arn = \"${assume_role}\"" >> provider.tf
echo "  #}" >> provider.tf
echo "}" >> provider.tf

echo "## Backend Section ##" > main.tf

echo "#terraform {" >> main.tf
echo "#  cloud {" >> main.tf
echo "#    organization = \"SMECLOUDOPS\"" >> main.tf

echo "#    workspaces {" >> main.tf
echo "#      name = \"${profile}-${vpc_name}\"" >> main.tf
echo '''#    }
#  }
#}
''' >> main.tf
terraform fmt
}

###VPC imports
vpc_imports() {
  terraform init
  read -p "Enter VPC ID: " vpc_id
  echo resource \"aws_vpc\" \"${vpc_id}\" {} >> tmp-vpc.tf
  terraform import aws_vpc.${vpc_id} ${vpc_id} >/dev/null
  >tmp-vpc.tf
  rm tmp-vpc.tf
  terraformer import aws --resources=vpc --filter=vpc=${vpc_id} --regions ${region} --profile ${profile}
  mv generated/aws/vpc/vpc.tf .
  sed -i 's/tfer--//g' vpc.tf
  rm -rf generated
  sed  -i '/^  enable_classiclink/d' vpc.tf
  sed  -i '/^  ipv6_netmask_length/d' vpc.tf
  echo "Import Successful. Please run terraform plan to verify the changes."

  aws ec2 describe-vpcs --vpc-ids ${vpc_id} --profile ${profile} --region ${region} | jq -r '.Vpcs[] | .CidrBlockAssociationSet[1:][] | select(.AssociationId != null) | .AssociationId' > scondary_cidr.txt
  output_file="tmp-vpc-secondary-cidrs.tf"

  while IFS= read -r association; do
    cat <<EOF >> "$output_file"
import {
  to = aws_vpc_ipv4_cidr_block_association.${association}
  id = "${association}"
}

EOF
  done < scondary_cidr.txt
  rm -f scondary_cidr.txt
  terraform init
  terraform plan -generate-config-out=vpc-secondary-cidrs.tf
}

### VPC Flow logs
vpc_flow_logs() {
  read -p "Enter VPC ID: " vpc_id
  aws ec2 describe-flow-logs --filter Name=resource-id,Values=${vpc_id} --region ${region} --profile ${profile} | jq -r '.FlowLogs[] | .FlowLogId' > flowlogids.txt
  for id in `cat flowlogids.txt`; do
    echo "resource \"aws_flow_log\" \"${id}-flowlogs\" {}" > tmp-logs.tf
    terraform import aws_flow_log.${id}-flowlogs ${id} > /dev/null
    terraform state show -no-color aws_flow_log.${id}-flowlogs | egrep -v '# aws_flow_log.| arn | id | log_format | log_group_name ' >> vpc-flowlogs.txt
    echo -e "" >> vpc-flowlogs.txt
    >tmp-logs.tf
  done
  mv vpc-flowlogs.txt vpc-flowlogs.tf
  terraform fmt > /dev/null
  rm flowlogids.txt tmp-logs.tf
}

###Subnet imports
subnet_imports() {
  read -p "Enter VPC ID: " vpc_id
  aws ec2 describe-subnets --filters "Name=vpc-id,Values=${vpc_id}" --query "Subnets[*].SubnetId" --region ${region} --profile ${profile} | jq .[]| tr -d '"' > subnet-list.txt
  for subnet in `cat subnet-list.txt`; do
    echo resource \"aws_subnet\" \"${subnet}\" {} >> tmp-subnet.tf
    terraform import aws_subnet.${subnet} ${subnet} >/dev/null
    >tmp-subnet.tf
  done
  rm tmp-subnet.tf
  subnets_list=`sed -e :a -e '/$/N; s/\n/\:/; ta' subnet-list.txt`
  terraformer import aws --resources=subnet --filter=subnet=${subnets_list} --regions=${region} --profile=${profile}
  mv generated/aws/subnet/subnet.tf .
  sed -i 's/tfer--//g' subnet.tf 
  sed  -i '/^  map_customer_owned_ip_on_launch/d' subnet.tf
  rm -rf generated subnet-list.txt
  sed -i s/\"${vpc_id}\"/aws_vpc\.${vpc_id}\.id/g subnet.tf
  sed -i '/enable_lni_at_device_index/d' subnet.tf
}

## New Method doesn't work
# subnet_imports() {
#   read -p "Enter VPC ID: " vpc_id
#   aws ec2 describe-subnets --filters "Name=vpc-id,Values=${vpc_id}" --query "Subnets[*].SubnetId" --region ${region} --profile ${profile} | jq .[]| tr -d '"' > tmp-subnet-list.txt
#   output_file="tmp-subnet.tf"

#   while IFS= read -r subnet; do
#     cat <<EOF >> "$output_file"
# import {
#   to = aws_subnet.${subnet}
#   id = "${subnet}"
# }

# EOF
#   done < tmp-subnet-list.txt
#   rm -f tmp-subnet-list.txt
#   terraform init
#   terraform plan -generate-config-out=vpc-subnets.tf
# }


### Internet Gateway imports
igw_imports(){
  read -p "Enter VPC ID: " vpc_id
  aws ec2 describe-internet-gateways --filters "Name=attachment.vpc-id,Values=${vpc_id}" --query "InternetGateways[*].InternetGatewayId" --region=${region} --profile=${profile} | jq .[] | tr -d '"' > igw.txt
  output_file="tmp-internet-gateways.tf"

  while IFS= read -r igw; do
    cat <<EOF >> "$output_file"
import {
  to = aws_internet_gateway.${igw}
  id = "${igw}"
}

EOF
  done < igw.txt
  rm -f igw.txt
  terraform init
  terraform plan -generate-config-out=internet-gateway.tf
}

nat_imports(){
  read -p "Enter VPC ID: " vpc_id
  export vpc_id="${vpc_id}"
  aws ec2 describe-nat-gateways --region=${region} --profile=${profile} | jq -r '.NatGateways[]| select( .VpcId == env.vpc_id ) | .NatGatewayId' > nat.txt
  output_file="tmp-nat.tf"

  while IFS= read -r nat; do
    cat <<EOF >> "$output_file"
import {
  to = aws_nat_gateway.${nat}
  id = "${nat}"
}
EOF
  done < nat.txt
  rm -f nat.txt
  terraform init
  terraform plan -generate-config-out=nat-gateway.tf
  sed -i '/secondary_private_ip_address_count/d' nat-gateway.tf
  terraform apply  
  rm -f tmp-*
}

sg_imports(){
  read -p "Enter VPC ID: " vpc_id
  aws ec2 describe-security-groups --filters "Name=vpc-id,Values=${vpc_id}" --region=${region} --profile=${profile} | jq -r '.[] | .[].GroupId' > sg.txt
  for sg in `cat sg.txt`; do
    echo resource \"aws_security_group\" \"${sg}\" {} >> tmp-sg.tf
    terraform import aws_security_group.${sg} ${sg} >/dev/null
    terraform state show -no-color aws_security_group.${sg} >> tmp-sg.txt
    echo -e "" >> tmp-sg.txt
    >tmp-sg.tf
  done
  egrep -v 'owner_id|timeouts|arn|# aws_security_group| id |name_prefix' tmp-sg.txt  > security-groups.tf
  rm sg.txt tmp-sg.tf tmp-sg.txt
}

#####Manual work required after import####
route_table_imports() {
  read -p "Enter VPC ID: " vpc_id
  aws ec2 describe-route-tables --filters "Name=vpc-id,Values=${vpc_id}" --region=${region} --profile=${profile} | jq -r '.[]|.[].RouteTableId' > rt.txt
  table_list=`sed -e :a -e '/$/N; s/\n/\:/; ta' rt.txt`
  terraformer import aws --resources=route_table --filter=route_table=${table_list} --regions=${region} --profile=${profile}
  cd generated/aws/route_table/
  terraform state replace-provider registry.terraform.io/-/aws registry.terraform.io/hashicorp/aws
  sed -i 's/tfer--//g' *
  for i in $(terraform state list); do terraform state mv -state-out="../../../terraform.tfstate" "$i" "$i"; done
  cp route_table.tf route_table_association.tf main_route_table_association.tf ../../../
  cd ../../../
  echo "please fix the ids in route_table_association.tf main_route_table_association.tf files"
  rm -rf rt.txt generated

 # FIX MANUAL WORKS
  user_vpc_id="${vpc_id}"
  export user_vpc_id
  terraform state list | grep 'aws_main_route_table_association' | while read -r line; do
  vpc_id=$(terraform state show "$line" | awk '/vpc_id/ {print $3}')
  if [[ "$vpc_id" != "\"$user_vpc_id\"" ]]; then
    terraform state rm "$line"
  fi
  done
  file="main_route_table_association.tf"

  awk -v vpc_id="$user_vpc_id" '
BEGIN {print_mode=1}
/resource "aws_main_route_table_association"/ {
    block=$0; getline;
    while($0 !~ /^}/ && $0 != "") {
        block=block ORS $0; getline;
    }
    block=block ORS $0;
    if(block ~ vpc_id) {
        print block;
    } else {
        gsub(/\n/, "\n#", block);
        print "#" block;
    }
    next;
}
{print}
' "$file" > tmp_file.tf
  mv tmp_file.tf "$file"
  
  # 2nd Manual Fix
  terraform_file="route_table_association.tf"

  # Generate a list of valid subnet IDs within the specified VPC
  aws ec2 describe-subnets --filters "Name=vpc-id,Values=${vpc_id}" --query "Subnets[*].SubnetId" --region ${region} --profile ${profile} | jq -r .[] > valid-list.txt

  # Prepare a temporary file
  temp_file=$(mktemp)

  # Initialize variables
  inside_block=0
  comment_out=false
  resource_identifier=""

  # Process the Terraform configuration file
  while IFS= read -r line || [[ -n "$line" ]]; do
    # Detect the start of a aws_route_table_association resource block
    if echo "$line" | grep -qE '^resource "aws_route_table_association"'; then
      inside_block=1
      block_content=("$line")
      # Extract the resource identifier (e.g., "aws_route_table_association.subnet-XXXXX")
      resource_identifier=$(echo "$line" | awk -F\" '{print $2 "." $4}')
      continue
    fi

    # Accumulate lines and mark for commenting if invalid
    if [[ $inside_block -eq 1 ]]; then
      block_content+=("$line")

      if echo "$line" | grep -q 'subnet_id'; then
        subnet_id=$(echo "$line" | grep -oP 'subnet_id\s*=\s*"\K[^"]+')
        if ! grep -qw "$subnet_id" valid-list.txt; then
            comment_out=true
        fi
      fi

      # At the end of the block, decide to comment out and remove from state
      if [[ "$line" =~ ^}$ ]]; then
        inside_block=0
        if [[ $comment_out == true ]]; then
          for item in "${block_content[@]}"; do
            echo "#$item" >> "$temp_file"
          done
          # Remove the resource from the Terraform state
          terraform state rm "$resource_identifier"
          comment_out=false
        else
          printf "%s\n" "${block_content[@]}" >> "$temp_file"
        fi
        block_content=() # Reset block content
      fi
    else
      echo "$line" >> "$temp_file"
    fi
  done < "$terraform_file"

  # Replace the original Terraform file
  mv "$temp_file" "$terraform_file"
  rm valid-list.txt

  echo "Finished processing. Invalid resources removed from state."
  sed -i '/^#/d' route_table_association.tf && awk '/route_table_id/ {match($0, /rtb-[0-9a-zA-Z]+/); print "  route_table_id = \"" substr($0, RSTART, RLENGTH) "\""} !/route_table_id/ {print}' route_table_association.tf > route_table_association-tmp.tf && mv route_table_association-tmp.tf route_table_association.tf
  sed -i '/^#/d' main_route_table_association.tf && awk '/route_table_id/ {match($0, /rtb-[0-9a-zA-Z]+/); print "  route_table_id = \"" substr($0, RSTART, RLENGTH) "\""} !/route_table_id/ {print}' main_route_table_association.tf > main_route_table_association-tmp.tf && mv main_route_table_association-tmp.tf main_route_table_association.tf
}

nacl_imports() {
  read -p "Enter VPC ID: " vpc_id
  aws ec2 describe-network-acls --filters "Name=vpc-id,Values=${vpc_id}" --query "NetworkAcls[*].NetworkAclId" --region=${region} --profile=${profile} | jq .[] | tr -d '"' > nacl.txt
  nacl_list=`sed -e :a -e '/$/N; s/\n/\:/; ta' nacl.txt`
  terraformer import aws --resources=nacl --filter=nacl=${nacl_list} --regions=${region} --profile=${profile}
  cd generated/aws/nacl
  terraform state replace-provider registry.terraform.io/-/aws registry.terraform.io/hashicorp/aws
  sed -i 's/tfer--//g' *
  for i in $(terraform state list); do terraform state mv -state-out="../../../terraform.tfstate" "$i" "$i"; done
  cp network_acl.tf ../../../
  cd ../../../
  rm -rf nacl.txt generated
  for file in *_*; do mv "$file" "${file//_/-}"; done
} 

rds_imports() {
  read -p "Enter VPC ID: " vpc_id
  export vpc_id="${vpc_id}"
  aws rds describe-db-instances --region=${region} --profile=${profile} --filters "Name=engine,Values=mysql,postgres,oracle-se2,oracle-ee,sqlserver-ee,sqlserver-se,sqlserver-ex,sqlserver-web,mariadb" | jq --arg vpc_id "$vpc_id" -r '.DBInstances[] | select(.DBSubnetGroup.VpcId == $vpc_id) | .DBInstanceIdentifier' > rds-list.txt
  for rds in `cat rds-list.txt`; do
    echo resource \"aws_db_instance\" \"${rds}\" {} >> tmp-rds.tf
    terraform import aws_db_instance.${rds} ${rds} >/dev/null
    terraform state show -no-color aws_db_instance.${rds} >> tmp-rds.txt
    echo -e "" >> tmp-rds.txt
    >tmp-rds.tf
  done
  egrep -v '# aws_db_instance.| timeouts | status | resource_id | id | hosted_zone_id | engine_version_actual | arn | address | security_group_names | endpoint | latest_restorable_time | name | replicas ' tmp-rds.txt > rds-instances.tf
  rm *.txt tmp-rds.tf
}

aurora_imports() {
  if [ -e aurora-cluster-list.txt ] && [ -f aurora-cluster-list.txt ]; then
    echo "Found aurora-cluster-list.txt file"
    for cluster in `cat aurora-cluster-list.txt`; do
      echo resource \"aws_rds_cluster\" \"${cluster}\" {} >> tmp-cluster.tf
      terraform import aws_rds_cluster.${cluster} ${cluster} > /dev/null
      terraform state show -no-color aws_rds_cluster.${cluster} >> tmp-cluster.txt
      echo -e "" >> tmp-cluster.txt
      >tmp-cluster.tf
      
      # Importing the cluster members
      aws rds describe-db-instances --region=${region} --profile=${profile} --query "DBInstances[?DBClusterIdentifier=='${cluster}'].DBInstanceIdentifier" --output text > aurora_clusters_members.txt

      if [ -f aurora_clusters_members.txt ]; then
        echo "aurora_clusters_members.txt exists"
        for member in `cat aurora_clusters_members.txt`; do
          echo resource \"aws_rds_cluster_instance\" \"${member}\" {} >> tmp-member.tf
          terraform import aws_rds_cluster_instance.${member} ${member} > /dev/null
          terraform state show -no-color aws_rds_cluster_instance.${member} >> tmp-member.txt
          echo -e "" >> tmp-member.txt
          >tmp-member.tf
        done

      else
        echo "aurora_clusters_members.txt file does not exist"
        exit 1
      fi
    done
    egrep -v '# aws_rds_cluster.| arn | engine_version_actual | timeouts | id | hosted_zone_id | reader_endpoint | endpoint | cluster_resource_id ' tmp-cluster.txt >> aurora-clusters.tf
    egrep -v ' timeouts | id | engine_version_actual | endpoint | dbi_resource_id | arn | # aws_rds_cluster_instance.| port | storage_encrypted | writer | network_type | kms_key_id ' tmp-member.txt >> aurora-clusters-members.tf
  else
    echo "aurora-cluster-list.txt does not exist. Please add the list of aurora clusters in the file and run the command again."
    exit 1
  fi
  rm aurora*.txt tmp-*
}

documentdb_imports() {
  terraform init
  read -p "Enter VPC ID: " vpc_id
  export vpc_id="${vpc_id}"
  aws docdb describe-db-instances --region=${region} --profile=${profile} | jq --arg vpc_id "$vpc_id" -r '.DBInstances[] | select(.DBSubnetGroup.VpcId == $vpc_id) | select(.Engine == "docdb") | .DBClusterIdentifier' | uniq > documentdb.txt
  for cluster in `cat documentdb.txt`; do
    #terraform import aws_docdb_cluster.my_cluster my-cluster
    echo resource \"aws_docdb_cluster\" \"${cluster}\" {} >> tmp-cluster.tf
    terraform import aws_docdb_cluster.${cluster} ${cluster} > /dev/null
    terraform state show -no-color aws_docdb_cluster.${cluster} >> tmp-cluster.txt
    echo -e "" >> tmp-cluster.txt
    >tmp-cluster.tf
  done
  egrep -v ' reader_endpoint | endpoint | port | arn | id | hosted_zone_id | cluster_resource_id | timeouts |# aws_docdb_cluster.' tmp-cluster.txt > documentdb-clusters.tf
  rm tmp-cluster.tf tmp-cluster.txt

  for items in `cat documentdb.txt`; do
    aws docdb describe-db-instances --region=${region} --profile=${profile} | jq --arg vpc_id "$vpc_id" -r '.DBInstances[] | select(.DBSubnetGroup.VpcId == $vpc_id) | select(.Engine == "docdb") | .DBInstanceIdentifier' > dbinstances.txt
    for instance in `cat dbinstances.txt`; do
      #terraform import aws_docdb_cluster_instance.my_instance my-instance
      echo resource \"aws_docdb_cluster_instance\" \"${instance}\" {} >> tmp-instance.tf
      terraform import aws_docdb_cluster_instance.${instance} ${instance} > /dev/null
      terraform state show -no-color aws_docdb_cluster_instance.${instance} >> tmp-instance.txt
      echo -e "" >> tmp-instance.txt
      >tmp-instance.tf
    done 
  done
  egrep -v '# aws_docdb_cluster_instance.| arn | dbi_resource_id | endpoint | id | port | timeouts | writer | storage_encrypted | publicly_accessible | preferred_backup_window | kms_key_id | db_subnet_group_name | engine_version ' tmp-instance.txt > documentdb-cluster-instances.tf
  rm tmp-* dbinstances.txt documentdb.txt
}

ec2_imports(){
  read -p "Enter VPC ID: " vpc_id
  output_file="tmp-ec2-instances.tf"
  aws ec2 describe-instances \
    --region ${region} --profile ${profile} \
    --filters "Name=vpc-id,Values=${vpc_id}" \
    --query 'Reservations[].Instances[]' \
    --output json | jq -c '.[]' | while read -r instance; do

    # Extract Instance ID and Name tag (if exists)
    INSTANCE_ID=$(echo "$instance" | jq -r '.InstanceId')
    NAME_TAG=$(echo "$instance" | jq -r '.Tags[] | select(.Key=="Name") | .Value')
    
    NAME_TAG=${NAME_TAG//./-}
    # Check if the Name tag exists and is not empty
    if [[ -z "$NAME_TAG" ]] || [[ "$NAME_TAG" == "null" ]]; then
      # Fallback to Instance ID if Name is missing or null
      NAME_TAG="$INSTANCE_ID"
    fi

    # Filter out instances based on name criteria
    if echo "$NAME_TAG" | grep -ivE "batch|worker-nodes|worker-node|wip" > /dev/null; then
      # Your logic here, e.g., echo or further processing
      echo "VPC ID: $vpc_id, Instance ID: $INSTANCE_ID, Name: $NAME_TAG"
      cat <<EOF >> "$output_file"
import {
  to = aws_instance.${NAME_TAG}
  id = "${INSTANCE_ID}"
}

EOF
    fi
  done
  terraform init
  terraform plan -generate-config-out=ec2-instances.tf
  sed -i '/ipv6_address_count/d' ec2-instances.tf && sed -i '/ipv6_addresses/d' ec2-instances.tf
  sed -i '/^resource /a \ \ lifecycle {\n    ignore_changes = [\n      user_data,\n    ]\n  }' ec2-instances.tf
  terraform apply && rm -f tmp-*
  terraform fmt
}

loadbalancers() {
  read -p "Enter VPC ID: " vpc_id
  aws elbv2 describe-load-balancers --query "LoadBalancers[?VpcId=='${vpc_id}'].LoadBalancerArn" --region=${region} --profile=${profile} | jq -r '.[]' > tmp-lbs.txt
  output_file="tmp-elb.tf"

  while IFS= read -r elb; do
    name=`echo ${elb} | awk -F/ '{print $3}'`
    cat <<EOF >> "$output_file"
import {
  to = aws_lb.${name}
  id = "${elb}"
}
EOF
  done < tmp-lbs.txt
  rm -f tmp-lbs.txt
  terraform init
  terraform plan -generate-config-out=elb.tf
  sed -i '/subnets/d' elb.tf
  terraform apply
  rm -f tmp-*
}

asg() {
  OUTPUT_FILE="tmp-asg-list.txt"
  touch $OUTPUT_FILE
  SUBNETS=($(aws ec2 describe-subnets --region "$region" --profile "$profile" --filters "Name=vpc-id,Values=$vpc_id" --query 'Subnets[*].SubnetId' --output text))
  for SUBNET in "${SUBNETS[@]}"; do
    # List ASGs and filter those that include the current subnet
    ASGS=($(aws autoscaling describe-auto-scaling-groups --region "$region" --profile "$profile" --query "AutoScalingGroups[?contains(VPCZoneIdentifier, '$SUBNET')].AutoScalingGroupName" --output text))

    for ASG in "${ASGS[@]}"; do
      # Check if ASG is already listed in the file to avoid duplicates
      if ! grep -q "$ASG" "$OUTPUT_FILE"; then
        echo "$ASG" >> "$OUTPUT_FILE"
      fi
    done
  done

  generate_file="tmp-asg.tf"

  while IFS= read -r asg; do
    cat <<EOF >> "$generate_file"
import {
  to = aws_autoscaling_group.${asg}
  id = "${asg}"
}
EOF
  done < $OUTPUT_FILE
  terraform init
  terraform plan -generate-config-out=asg.tf
  sed -i '/availability_zones/d' asg.tf
  terraform apply
  rm -f tmp-*
}

launch_templates() {
  # Output file for matching launch templates
  OUTPUT_FILE="tmp-matching_launch_templates.txt"
  SG_IDS=$(aws ec2 describe-security-groups --region "$region" --profile "$profile" --filters Name=vpc-id,Values=$vpc_id --query 'SecurityGroups[*].GroupId' --output text)
  declare -a MATCHING_LT_IDS
  LAUNCH_TEMPLATES=$(aws ec2 describe-launch-templates --region "$region" --profile "$profile" --query 'LaunchTemplates[*].LaunchTemplateId' --output text)

  # Check each launch template for a matching security group
  for LT_ID in $LAUNCH_TEMPLATES; do
    # Extract security group IDs associated with the launch template
    LT_SG_IDS=$(aws ec2 describe-launch-template-versions --region "$region" --profile "$profile" --launch-template-id $LT_ID --query 'LaunchTemplateVersions[0].LaunchTemplateData.SecurityGroupIds' --output text)

    for SG_ID in $SG_IDS; do
      if [[ $LT_SG_IDS == *"$SG_ID"* ]]; then
        MATCHING_LT_IDS+=($LT_ID)
        break
      fi
    done
  done

  for LT_ID in "${MATCHING_LT_IDS[@]}"; do
    echo $LT_ID >> $OUTPUT_FILE
  done

  generate_file="tmp-lt.tf"
  while IFS= read -r lt; do
    cat <<EOF >> "$generate_file"
import {
  to = aws_launch_template.${lt}
  id = "${lt}"
}
EOF
  done < $OUTPUT_FILE
  terraform init
  terraform plan -generate-config-out=launch-templates.tf
  sed -i '/security_group_names/d' launch-templates.tf
  terraform apply
  rm -f tmp-*
}

# ebs_imports() {
#   for instance in $(terraform state list | grep aws_instance | awk -F. '{print $2}'); do aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=${instance} --query 'Volumes[*].{ID:VolumeId,Device:Attachments[0].Device}' --profile ${profile} --region ${region}; done | jq -r '.[] | .ID' > volume-ids.txt
#   for resource in $(terraform state list | grep aws_instance | awk -F. '{print $2}'); do aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=${resource} --query 'Volumes[*].{Instance:Attachments[0].InstanceId,ID:VolumeId,Device:Attachments[0].Device}' --profile ${profile} --region ${region}; done | jq -r '.[]' > volume-data.json

#   for volume in `cat volume-ids.txt`; do
#     echo "resource \"aws_ebs_volume\" \"${volume}\" {}" > tmp-volume.tf
#     terraform import aws_ebs_volume.${volume} ${volume} > /dev/null
#     terraform state show -no-color aws_ebs_volume.${volume} >> tmp-volume.txt
#     echo "" >> tmp-volume.txt
#     > tmp-volume.tf

#     ## Attachments
#     echo "resource \"aws_volume_attachment\" \"${volume}\" {}" >> tmp-ebs-volume-attachment.tf
#     deviceid=`cat volume-data.json| jq -r --arg volume "$volume" '. | select( .ID == $volume ) | .Device'`
#     instanceid=`cat volume-data.json| jq -r --arg volume "$volume" '. | select( .ID == $volume ) | .Instance'`
#     terraform import aws_volume_attachment.${volume} ${deviceid}:${volume}:${instanceid} > /dev/null
#     >tmp-ebs-volume-attachment.tf
#     echo "resource \"aws_volume_attachment\" \"${volume}\" {" >> ebs-volume-attachment.txt
#     echo "device_name = \"${deviceid}\"" >> ebs-volume-attachment.txt
#     echo "volume_id   = aws_ebs_volume.${volume}.id" >> ebs-volume-attachment.txt
#     echo "instance_id = aws_instance.${instanceid}.id" >> ebs-volume-attachment.txt
#     echo "}" >> ebs-volume-attachment.txt
#     echo "" >> ebs-volume-attachment.txt
#   done
#   egrep -v '# aws_ebs_volume.| arn | id | throughput | timeouts ' tmp-volume.txt > ebs-volumes.tf
#   cat ebs-volume-attachment.txt > ebs-volume-attachments.tf
#   terraform fmt
#   rm tmp-volume.txt volume-data.json ebs-volume-attachment.txt tmp-ebs-volume-attachment.tf tmp-volume.tf volume-ids.txt
# }

network_firewall() {
  read -p "Enter VPC ID: " vpc_id
  nfw_name=`aws network-firewall list-firewalls --vpc-ids $vpc_id --region ${region} --profile ${profile} | jq -r '.|.Firewalls[] | .FirewallName'`
  nfw_arn=`aws network-firewall list-firewalls --vpc-ids $vpc_id --region ${region} --profile ${profile} | jq -r '.|.Firewalls[] | .FirewallArn'`
  echo "resource \"aws_networkfirewall_firewall\" \"${nfw_name}\" {}" > nfw-tmp.tf
  terraform import aws_networkfirewall_firewall.${nfw_name} ${nfw_arn} > /dev/null
  rm nfw-tmp.tf
  echo "resource \"aws_networkfirewall_firewall\" \"${nfw_name}\" {" >> network-firewall.txt
  echo "delete_protection = true" >> network-firewall.txt
  echo "description = \"`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.description'`\"" >> network-firewall.txt
  echo "firewall_policy_arn = \"`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.firewall_policy_arn'`\"" >> network-firewall.txt
  echo "name = \"`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.name'`\"" >> network-firewall.txt
  echo "firewall_policy_change_protection = \"`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.firewall_policy_change_protection'`\"" >> network-firewall.txt
  echo "subnet_change_protection = \"`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.subnet_change_protection'`\"" >> network-firewall.txt
  echo "vpc_id = \"`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.vpc_id'`\"" >> network-firewall.txt
  echo "subnet_mapping `terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.subnet_mapping[]' | sed 's/:/=/g' | sed 's/,//g'`" >> network-firewall.txt
  echo "}" >> network-firewall.txt
  sed -i "s/\"ip_address_type\"/ip_address_type/" network-firewall.txt
  sed -i "s/\"subnet_id\"/subnet_id/" network-firewall.txt
  mv network-firewall.txt network-firewall.tf
  terraform fmt > /dev/null
  rm *.txt
  
  #Firewall Policy
  firewall_policy_name=`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.firewall_policy_arn' | awk -F/ '{print $2}'`
  firewall_policy_arn=`terraform show -json | jq -r --arg nfw "${nfw_name}" '.values.root_module | .resources[] | select(.type == "aws_networkfirewall_firewall")| select(.name == $nfw) | .values.firewall_policy_arn'`
  echo "resource \"aws_networkfirewall_firewall_policy\" \"${firewall_policy_name}\" {}" > network-firewall-policy.tf
  terraform import aws_networkfirewall_firewall_policy.${firewall_policy_name} ${firewall_policy_arn} > /dev/null
  terraform state show -no-color aws_networkfirewall_firewall_policy.${firewall_policy_name} > network-firewall-policy.txt
  egrep -v '# aws_networkfirewall_firewall_policy| arn | id | update_token | priority ' network-firewall-policy.txt > network-firewall-policy.tf
  terraform fmt > /dev/null
  rm network-firewall-policy.txt

  echo "resource \"aws_networkfirewall_logging_configuration\" \"${nfw_name}\" {}" > net-tmp.tf
  terraform import aws_networkfirewall_logging_configuration.${nfw_name} ${nfw_arn} > /dev/null
  echo -e "" >> network-firewall.tf
  rm net-tmp.tf
  terraform state show -no-color aws_networkfirewall_logging_configuration.${nfw_name} | egrep -v '# aws_networkfirewall_logging_configuration| id ' >> network-firewall.tf
  terraform fmt > /dev/null
}

nfw-rg() {
  echo "Enter the stateful rule group ARN. Please rerun the same if you have multiple rule groups. You can find the Rule group arns in network-firewall-policy.tf file"
  read rulegrouparn
  rulegroupname=`echo ${rulegrouparn} | awk -F/ '{print $2}'`
  echo "resource \"aws_networkfirewall_rule_group\" \"${rulegroupname}\" {}" > net-tmp.tf
  terraform import aws_networkfirewall_rule_group.${rulegroupname} ${rulegrouparn} > /dev/null
  rm net-tmp.tf
  terraform state show -no-color aws_networkfirewall_rule_group.${rulegroupname} | egrep -v '# aws_networkfirewall_rule_group| arn | id | update_token ' >> network-firewall-rulegroups.tf
  echo -e "" >> network-firewall-rulegroups.tf 
  terraform fmt > /dev/null
}

batch (){
  read -p "Enter VPC ID: " vpc_id
  aws batch describe-compute-environments --region ${region} --profile ${profile} | jq -r '.computeEnvironments[] | .computeEnvironmentName' > all-batch.txt

  while IFS= read -r compute; do
    subnet=$(aws batch describe-compute-environments --compute-environments ${compute} --region ${region} --profile ${profile} | jq -r '.computeEnvironments[] | .computeResources.subnets[0]')
    compute_vpc=$(aws ec2 describe-subnets --region ${region} --profile ${profile} --subnet-ids ${subnet} --query 'Subnets[0].VpcId' | tr -d \")
    if [ "${vpc_id}" == "${compute_vpc}" ]; then
      echo $compute >> tmp-batch.txt
    fi
  done < all-batch.txt
  rm all-batch.txt
  output_file="tmp-batch.tf"
  while IFS= read -r compute; do
    cat <<EOF >> "$output_file"
import {
  to = aws_batch_compute_environment.${compute}
  id = "${compute}"
}
EOF
  done < tmp-batch.txt
  terraform init
  terraform plan -generate-config-out=batch-compute-environments.tf
  awk '/^resource /{print;print "  lifecycle {\n    ignore_changes = [\n      compute_resources[0].desired_vcpus,\n    ]\n  }";next}1' batch-compute-environments.tf > modified_file.tf && mv modified_file.tf batch-compute-environments.tf
  terraform apply
  echo "Preparing to import Batch Job Queues..."
  # New: List all job queues and filter based on compute environments
  aws batch describe-job-queues --region ${region} --profile ${profile} | jq -r '.jobQueues[] | select(.state == "ENABLED") | .jobQueueName' > all-job-queues.txt

  while IFS= read -r queue; do
    # For each queue, check if its compute environment is in the list of filtered compute environments
    compute_envs_for_queue=$(aws batch describe-job-queues --job-queues ${queue} --region ${region} --profile ${profile} | jq -r '.jobQueues[].computeEnvironmentOrder[].computeEnvironment' | grep -f tmp-batch.txt)

    if [ ! -z "$compute_envs_for_queue" ]; then
      queuearn=`aws batch describe-job-queues --job-queues media-conversion-queue-priority0-stage2 --region ${region} --profile ${profile} --query 'jobQueues[0].jobQueueArn' --output text`
      cat <<EOF >> tmp-job-queue.tf
import {
  to = aws_batch_job_queue.${queue}
  id = "${queuearn}"
}
EOF
    fi
  done < all-job-queues.txt
  rm all-job-queues.txt
  terraform init
  terraform plan -generate-config-out=batch-job-queues.tf
  terraform apply
  rm -f tmp-*
}

delete_terraform_resource (){
  read -p "Enter resource type: " resource_type
  # Check if resource file exists
  if [ -f "resources.txt" ]; then
    for item in `cat resources.txt`; do
      terraform state rm ${resource_type}.${item}
    done
  else
    echo "resources.txt file does not exists"
  fi
}

workspaces (){
  read -p "Enter Directory ID: " directory_id
  workspaces=($(aws workspaces describe-workspaces --directory-id "$directory_id" --region "$region" --profile "$profile" --query 'Workspaces[*].[WorkspaceId, UserName, State.Name]' --output text))

  output_file="tmp-workspaces.tf"
  d_output_file="tmp-directory.tf"

  cat <<EOF >> "$d_output_file"
import {
  to = aws_workspaces_directory.${directory_id}
  id = "${directory_id}"  
}
EOF

  # Check if there are any workspaces
  if [ "${#workspaces[@]}" -eq 0 ]; then
    echo "No workspaces found for the provided Directory ID."
  else
    echo "Workspaces for Directory ID $directory_id:"

    # Loop through the array to display each workspace
    for ((i = 0; i < ${#workspaces[@]}; i+=3)); do
      workspace_id="${workspaces[$i]}"
      username="${workspaces[$i + 1]}"
      echo "Workspace ID: $workspace_id, Username: $username"
    # Append content to the output file
      cat <<EOF >> "$output_file"
import {
  to = aws_workspaces_workspace.${username}
  id = "${workspace_id}"  
}

EOF
    done
  fi
  terraform init
  terraform plan -generate-config-out=workspaces.tf
  echo "The workspace configs are generated in workspaces.tf file. Please Apply and then delete the remaining tmp-* files."
}

rdsproxy(){
  read -p "Enter VPC ID: " vpc_id
  aws rds describe-db-proxies --query "DBProxies[?VpcId=='$vpc_id'].DBProxyName" --region "$region" --profile "$profile" | jq -r .[] > db-proxies.txt
  output_file="tmp-proxies.tf"
  t_output_file="tmp-proxy-targets.tf"

  while IFS= read -r proxy; do
    echo "Processing DB Proxy: $proxy"
    cat <<EOF >> "$output_file"
import {
  to = aws_db_proxy.${proxy}
  id = "${proxy}"  
}

EOF
    cat <<EOF >> "$t_output_file"
import {
  to = aws_db_proxy_default_target_group.${proxy}
  id = "${proxy}"
}

EOF
  done < db-proxies.txt

  terraform init
  terraform plan -generate-config-out=rds-proxies.tf
  rm -f db-proxies.txt
  echo "The rds proxy and targets are generated in a single file rds-proxies.tf. Please make sure you separate them after applying (rds-proxy.tf and rds-proxy-target.tf)"
}

main() {
  local subcommand=${1}
  case ${subcommand} in
    add_dependency)
      add_dependency_files
    ;;
    vpc)
      vpc_imports
    ;;
    flow_logs)
      vpc_flow_logs
    ;;
    subnet)
      subnet_imports
    ;;
    igw)
      igw_imports
    ;;
    nat)
      nat_imports
    ;;
    sg)
      sg_imports
    ;;
    route-table)
      route_table_imports
    ;;
    nacl)
      nacl_imports
    ;;
    rds)
      rds_imports
    ;;
    aurora)
      aurora_imports
    ;;
    documentdb)
      documentdb_imports
    ;;
    ec2)
      ec2_imports
    ;;
    lb)
      loadbalancers
    ;;
    asg)
      asg
    ;;
    launch-templates)
      launch_templates
    ;;
    ebs)
      ebs_imports
    ;;
    nfw)
      network_firewall
    ;;
    nfw-rule-group)
      nfw-rg
    ;;
    batch)
      batch
    ;;
    workspaces)
      workspaces
    ;;
    rdsproxy)
      rdsproxy
    ;;
    delete_resources_from_state)
      delete_terraform_resource
    ;;
    -h|--help)
      echo "Usage: ./network-importer.sh <subcommand>"
      echo "Available subcommands:"
      echo "  add_dependency"
      echo "  vpc"
      echo "  flow_logs"
      echo "  subnet"
      echo "  igw"
      echo "  nat"
      echo "  sg"
      echo "  route-table"
      echo "  nacl"
      echo "  rds"
      echo "  aurora"
      echo "  documentdb"
      echo "  ec2"
      echo "  lb"
      echo "  asg"
      echo "  launch-templates"
      echo "  nfw"
      echo "  nfw-rule-group"
      echo "  batch"
      echo "  workspaces"
      echo "  rdsproxy"
      echo "  delete_resources_from_state"
    ;;
    *)
      >&2 echo "ERROR: missing or bad subcommand."
      echo "Usage: ./network-importer.sh -h|--help"
      exit 1
    ;;
  esac
}
main "$@"
