#!/bin/bash

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
WARNING='\xE2\x9A\xA0'
CHECK_MARK="\xE2\x9C\x94"
CROSS_MARK="\xE2\x9C\x98"

# Function to log messages
log() {
  local type=$1
  local message=$2
  case $type in
    "SUCCESS")
      echo -e "${GREEN}${CHECK_MARK}: $message${NC}"
      ;;
    "ERROR")
      echo -e "${RED}${CROSS_MARK}: $message${NC}"
      ;;
    "INFO")
      echo -e "${BLUE}INFO: $message${NC}"
      ;;
    "WARNING")
      echo -e "${YELLOW}${WARNING} $message${NC}"
      ;;
  esac
}

# Function to check if a command exists
command_exists() {
  command -v "$1" >/dev/null 2>&1
}

# Check required commands
for cmd in aws kubectl jq; do
  if ! command_exists $cmd; then
    log "ERROR" "$cmd is not installed or not in PATH"
    
  fi
done

# Assuming VPC ID is passed as an argument
VPC_ID=$1
REGION=$2
REQUEST_ID=$3

if [ -z "$VPC_ID" ] || [ -z "$REGION" ] || [ -z "$REQUEST_ID" ]; then
  log "ERROR" "Some arguments are missing. Usage: $0 <VPC_ID> <REGION> <REQUEST_ID>"
  exit 1
fi

# Run every AWS CLI call against the data plane region.
export AWS_DEFAULT_REGION="$REGION" AWS_REGION="$REGION"

VPC_CIDR=$(aws ec2 describe-vpcs --vpc-ids "$VPC_ID" --query "Vpcs[0].CidrBlock" --output text)

echo -e "\n"

echo -e "Starting VPC and infrastructure checks for VPC: $VPC_ID $VPC_CIDR in the region: $REGION \n"

log "INFO" "Checking DNS Resolution and DNS Hostname Attributes in the VPC:  $VPC_ID ..."
# Get the DNS Resolution and DNS Hostname Attributes in the VPC
dns_resolution=$(aws ec2 describe-vpc-attribute --vpc-id "$VPC_ID" --attribute enableDnsSupport --query 'EnableDnsSupport.Value' --output text)
dns_hostnames=$(aws ec2 describe-vpc-attribute --vpc-id "$VPC_ID" --attribute enableDnsHostnames --query 'EnableDnsHostnames.Value' --output text)

# Check if the DNS Resolution and DNS hostname is enabled
if [ "$dns_resolution" == "True" ]; then
  message="DNS Resolution is enabled for VPC $VPC_ID"
  echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
else
  message="DNS Resolution is disabled for VPC $VPC_ID"
  echo -e "  ${YELLOW}${WARNING} $message${NC}"
fi

if [ "$dns_hostnames" == "True" ]; then
  message="DNS Hostnames is enabled for VPC $VPC_ID"
  echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
else
  message="DNS Hostnames is disabled for VPC $VPC_ID"
  echo -e "  ${YELLOW}${WARNING} $message${NC}"
fi
echo -e "\n"

# Get all subnets in the VPC, including their availability zone
subnets=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC_ID" --query 'Subnets[*].[SubnetId, AvailabilityZone, AvailableIpAddressCount, CidrBlock]' --output text)


if [ -z "$subnets" ]; then
  log "ERROR" "No subnets found in VPC $VPC_ID"
  
fi

# Get the s3 VPC endpoint
s3_vpc_endpoint=$(aws ec2 describe-vpc-endpoints --region $REGION \
  --filters "Name=vpc-id,Values=$VPC_ID" "Name=service-name,Values=com.amazonaws.$REGION.s3" "Name=vpc-endpoint-type,Values=Gateway" \
  --query 'VpcEndpoints[0].VpcEndpointId' \
  --output text)

# Check if the S3 VPC endpoint exists
if [ "$s3_vpc_endpoint" != "None" ] && [ -n "$s3_vpc_endpoint" ]; then
  log "SUCCESS" "S3 VPC Endpoint found -  $s3_vpc_endpoint"
  echo -e "\n"
else
  log "ERROR" "S3 VPC Endpoint not found"
  
fi

# Initialize arrays for public and private subnets
public_subnets=()
private_subnets=()
private_azs=()
public_nats=()

# Loop through each subnet to determine if it's public or private
while read -r subnet_id az available_ip_address_count cidr_block; do
  log "INFO" "Checking subnet: $subnet_id..."
  echo "  Availability zone: $az"
  echo "  CIDR Block: $cidr_block"

  # Validate available IP address count thresholds
  if [ "$available_ip_address_count" -lt 100 ]; then
    echo -e "  ${RED}${CROSS_MARK} Available IP Address Count $available_ip_address_count"
  elif [ "$available_ip_address_count" -lt 500 ]; then
    echo -e "  ${YELLOW}${WARNING} Available IP Address Count $available_ip_address_count"
  else
    echo -e "  ${GREEN}${CHECK_MARK} Available IP Address Count $available_ip_address_count"
  fi

  # Get the route table associated with the subnet
  route_table_id=$(aws ec2 describe-route-tables --filters "Name=association.subnet-id,Values=$subnet_id" --query 'RouteTables[0].RouteTableId' --output text)

  if [ -z "$route_table_id" ]; then
    log "ERROR" "No route table found for subnet $subnet_id"
  fi

  # Get the routes for the route table and check for 0.0.0.0/0 destination
  internet_gateway=$(aws ec2 describe-route-tables --route-table-ids "$route_table_id" --query 'RouteTables[0].Routes[?DestinationCidrBlock==`0.0.0.0/0`].GatewayId' --output text)

  # Check if the route table has an entry for the S3 VPC endpoint
  route_target=$(aws ec2 describe-route-tables --route-table-ids "$route_table_id" \
    --query "RouteTables[0].Routes[?GatewayId=='$s3_vpc_endpoint'].GatewayId" \
    --output text)
  
  if [ "$route_target" == "$s3_vpc_endpoint" ]; then
    message="Route table $route_table_id has target VPC endpoint $s3_vpc_endpoint."
    echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
  else
    message="Route table $route_table_id has no association with VPC endpoint $s3_vpc_endpoint."
    echo -e "  ${YELLOW}${WARNING} $message${NC}"
  fi

  # Get the NAT associated with the subnet  
  nat_gateway=$(aws ec2 describe-nat-gateways --filter "Name=subnet-id,Values=$subnet_id" --query 'NatGateways[0].NatGatewayId' --output text)

  # Check if the route table has an entry for the NAT
  nat_in_route_table=$(aws ec2 describe-route-tables --route-table-ids "$route_table_id" \
    --query 'RouteTables[].Routes[?NatGatewayId].NatGatewayId' \
    --output text)

  # Determine if it's public or private based on the target for 0.0.0.0/0
  if [[ "$internet_gateway" == igw-* ]]; then
    if [ -n "$nat_in_route_table" ]; then
      message="Route table $route_table_id has target NAT gateways - $nat_in_route_table"
      echo -e "  ${YELLOW}${WARNING} $message${NC}"
    else
      message="Route table $route_table_id has no target NAT gateways"
      echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
    fi
    echo "  Is a public subnet."
    public_subnets+=($subnet_id)

    if [ "$nat_gateway" != "None" ] && [ -n "$nat_gateway" ]; then
      message="NAT associated with the subnet - $nat_gateway"
      echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
      public_nats+=($nat_gateway)
    else
      message="No NAT associated with the subnet"
      echo -e "  ${YELLOW}${WARNING} $message${NC}"
    fi

  else
    if [ -n "$nat_in_route_table" ]; then
      message="Route table $route_table_id has target NAT gateways - $nat_in_route_table"
      echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
    else
      message="Route table $route_table_id has no target NAT gateways"
      echo -e "  ${YELLOW}${WARNING} $message${NC}"
    fi
    echo "  Is a private subnet"
    private_subnets+=($subnet_id)

    # Add AZ to the private_azs array if it's not already present
    if [[ ! " ${private_azs[@]} " =~ " $az " ]]; then
      private_azs+=("$az")
    fi

    if [ "$nat_gateway" != "None" ] && [ -n "$nat_gateway" ]; then
      message="NAT associated with the subnet - $nat_gateway"
      echo -e "  ${YELLOW}${WARNING} $message${NC}"
    else
      message="No NAT associated with the subnet"
      echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
    fi
  fi
  echo -e "\n"
done <<< "$subnets"

# Check if the private subnets span more than 1 Availability Zone
unique_private_az_count=${#private_azs[@]}
if [ "$unique_private_az_count" -ge 2 ]; then
  log "SUCCESS" "Private subnets exist across at least two AZs - ${private_azs[*]}"
else
  log "ERROR" "Private subnets do not exist across at least two AZs - ${private_azs[*]}"
  
fi

echo -e "\n"

# Check the NAT in the public subnets
unique_public_nat_count=${#public_nats[@]}
if [ "$unique_public_nat_count" -ge 1 ]; then
  log "SUCCESS" "NAT gateway exists in at least one public subnet - ${public_nats[*]}"
else
  log "ERROR" "No NAT gateway found in the public subnets."
  
fi

echo -e "\n"

# Check required onehouse roles
log "INFO" "Checking required onehouse roles"
truncated_request_id=${REQUEST_ID:0:8}
role_keys=(
  "CORE_ROLE"
  "CSI_DRIVER_ROLE"
  "EKS_NODE_ROLE"
  "EKS_ROLE"
  "CUSTOMER_SUPPORT_ROLE"
  "AUTOSCALING_SERVICE_ROLE"
  "EKS_SERVICE_ROLE"
  "EKS_NODEGROUP_SERVICE_ROLE"
)
get_role_value() {
  local key=$1
  case $key in
    "CORE_ROLE")
      echo "onehouse-customer-core-role-${truncated_request_id}"
      ;;
    "CSI_DRIVER_ROLE")
      echo "onehouse-customer-csi-driver-role-${truncated_request_id}"
      ;;
    "EKS_NODE_ROLE")
      echo "onehouse-customer-eks-node-role-${truncated_request_id}"
      ;;
    "EKS_ROLE")
      echo "onehouse-customer-eks-role-${truncated_request_id}"
      ;;
    "CUSTOMER_SUPPORT_ROLE")
      echo "onehouse-customer-support-role-${truncated_request_id}"
      ;;
    "AUTOSCALING_SERVICE_ROLE")
      echo "AWSServiceRoleForAutoScaling"
      ;;
    "EKS_SERVICE_ROLE")
      echo "AWSServiceRoleForAmazonEKS"
      ;;
    "EKS_NODEGROUP_SERVICE_ROLE")
      echo "AWSServiceRoleForAmazonEKSNodegroup"
      ;;
  esac
}

missing_roles=0
for role_key in "${role_keys[@]}"; do
  role_value=$(get_role_value "$role_key")
  
  if aws iam get-role --role-name "$role_value" &> /dev/null; then
    message="IAM role - ${role_value} exists."
    echo -e "  ${GREEN}${CHECK_MARK} $message${NC}"
  else
    message="IAM role - ${role_value} does not exist"
    echo -e "  ${RED}${CROSS_MARK} $message${NC}"
    missing_roles=$((missing_roles + 1))
  fi
done


if [ $missing_roles -gt 0 ]; then
  log "ERROR" "$missing_roles required IAM role(s) are missing"
  
fi
echo -e "\n"

# Function to check registry accessibility
log "INFO" "Checking image registries accessibility"
check_registry() {
  local registry_name=$1
  local registry_url=$2
  echo " Testing connectivity to - ${registry_name}"
  if output=$(curl -I -s --connect-timeout 10 --max-time 15 "$registry_url" 2>&1); then
    status_code=$(echo "$output" | grep -E "^HTTP/" | tail -1 | awk '{print $2}')
    if [ -n "$status_code" ]; then
      message="Registry - ${registry_name} is accessible (HTTP ${status_code})"
      echo -e " ${GREEN}${CHECK_MARK} $message${NC}"
      return 0
    else
      message="Registry - ${registry_name} responded but status unclear"
      echo -e " ${YELLOW}${WARNING} $message${NC}"
      return 0
    fi
  else
    message="Registry - ${registry_name} is not accessible"
    echo -e " ${RED}${CROSS_MARK} $message${NC}"
    echo -e " ${RED}Error: Connection failed or timed out${NC}"
    return 1
  fi
}

# Check registry accessibility (no sudo/password needed)
inaccessible_registries=0
check_registry "Docker Hub" "https://registry-1.docker.io/v2/" || ((inaccessible_registries++))
check_registry "Kubernetes" "https://registry.k8s.io/v2/" || ((inaccessible_registries++))
check_registry "Quay" "https://quay.io/v2/" || ((inaccessible_registries++))

if [ $inaccessible_registries -gt 0 ]; then
  log "WARNING" "$inaccessible_registries image registries are inaccessible"
  echo -e "${YELLOW}  This may affect the ability to pull container images${NC}"
else
  log "SUCCESS" "All checked image registries are accessible"
fi

# --- Egress allowlist check -------------------------------------------------
# Reads host[:port] entries from uris.txt (next to this script). {region} is
# replaced with the region argument. Each entry gets one TLS connection on its
# port (default 443). Any HTTP status, or a TLS Server Hello from an endpoint that
# wants a client certificate (the control plane connection on 7202), means the firewall let the
# connection through. -k: this checks reachability, not certificate trust, so a
# TLS-inspecting proxy still reports OPEN.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
URI_FILE="${URI_FILE:-$SCRIPT_DIR/uris.txt}"
TIMEOUT=8

probe() {
  local host="$1" port="$2" out rc code
  out=$(curl -k -v -o /dev/null --connect-timeout "$TIMEOUT" --max-time "$TIMEOUT" \
        -w 'HTTPCODE=%{http_code}' "https://${host}:${port}/" 2>&1)
  rc=$?
  code="${out##*HTTPCODE=}"
  if [ "$code" != "000" ] && [ -n "$code" ]; then echo "OPEN|HTTP=${code}"; return; fi
  if echo "$out" | grep -qi "server hello"; then
    echo "OPEN|TLS handshake reached the server (client certificate required)"; return
  fi
  case "$rc" in
    6) echo "NO_DNS|could not resolve host" ;;
    7) echo "REFUSED|connection refused" ;;
    28) echo "TIMEOUT|no response in ${TIMEOUT}s (likely dropped by a firewall)" ;;
    35|56) echo "RESET|connection reset during TLS (likely blocked by a firewall)" ;;
    *) echo "FAILED|curl exit ${rc}" ;;
  esac
}

log "INFO" "Checking egress to the Onehouse allowlist endpoints (from $URI_FILE)"
echo "  Run this from a host in the data plane private subnets for a meaningful result."
blocked_endpoints=()
if [[ ! -f "$URI_FILE" ]]; then
  log "ERROR" "URI file '$URI_FILE' not found. Place uris.txt next to this script."
else
  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line%%#*}"; line="$(echo "$line" | tr -d '[:space:]')"
    [[ -z "$line" ]] && continue
    line="${line//\{region\}/$REGION}"
    if [[ "$line" == *:* ]]; then host="${line%:*}"; port="${line##*:}"; else host="$line"; port=443; fi
    res=$(probe "$host" "$port")
    status="${res%%|*}"; detail="${res#*|}"
    if [ "$status" = "OPEN" ]; then
      echo -e "  ${GREEN}${CHECK_MARK} ${host}:${port} - ${detail}${NC}"
    else
      echo -e "  ${RED}${CROSS_MARK} ${host}:${port} - ${status}: ${detail}${NC}"
      blocked_endpoints+=("${host}:${port} (TCP)")
    fi
  done < "$URI_FILE"

  if [ ${#blocked_endpoints[@]} -gt 0 ]; then
    log "ERROR" "${#blocked_endpoints[@]} endpoint(s) are not reachable"
    echo "  Ask your network team to allow outbound TCP to these endpoints from the data plane subnets:"
    for e in "${blocked_endpoints[@]}"; do echo "    - $e"; done
  else
    log "SUCCESS" "All allowlist endpoints are reachable"
  fi
fi

echo -e "\n"
echo "---------------------------------------------------------"
log "INFO" "Checking for Service Control Policies (SCPs) that may block IAM roles"

# Check if the account is part of an AWS Organization and if SCPs exist
scp_check_output=$(aws organizations describe-organization 2>&1)
scp_check_exit_code=$?

if [ $scp_check_exit_code -eq 0 ]; then
  # Account is part of an organization, now check for SCPs
  log "SUCCESS" "Account is part of an AWS Organization"

  # Try to list SCPs
  scp_list_output=$(aws organizations list-policies --filter SERVICE_CONTROL_POLICY 2>&1)
  scp_list_exit_code=$?

  if [ $scp_list_exit_code -eq 0 ]; then
    # Successfully retrieved SCPs
    scp_count=$(echo "$scp_list_output" | jq -r '.Policies | length' 2>/dev/null)

    if [ -n "$scp_count" ] && [ "$scp_count" -gt 0 ]; then
      log "WARNING" "Found $scp_count Service Control Policy/Policies in the organization"
      echo -e "${YELLOW}  Please manually verify that these SCPs do not block the required IAM roles and permissions:${NC}"
      echo "$scp_list_output" | jq -r '.Policies[] | "    - \(.Name) (ID: \(.Id))"' 2>/dev/null || echo "    (Unable to parse SCP details)"
      echo -e "${YELLOW}  To check SCP details, run: aws organizations describe-policy --policy-id <POLICY_ID>${NC}"
    else
      log "SUCCESS" "No Service Control Policies found that could block IAM roles"
    fi
  else
    # Failed to list SCPs
    log "WARNING" "Unable to check for Service Control Policies"
    echo -e "${YELLOW}  Error: Insufficient permissions to list SCPs or AWS CLI error occurred${NC}"
    echo -e "${YELLOW}  Please manually verify that no SCPs are blocking the required IAM roles${NC}"
    echo -e "${YELLOW}  You can check this by running: aws organizations list-policies --filter SERVICE_CONTROL_POLICY${NC}"
  fi
else
  # Check if it's a permission error or the account is not in an organization
  if echo "$scp_check_output" | grep -qi "AccessDenied\|UnauthorizedOperation\|InvalidClientTokenId"; then
    log "WARNING" "Unable to check for Service Control Policies due to insufficient permissions"
    echo -e "${YELLOW}  Please manually verify that no SCPs are blocking the required IAM roles${NC}"
    echo -e "${YELLOW}  Contact your AWS Organization administrator to check for SCPs${NC}"
  elif echo "$scp_check_output" | grep -qi "AWSOrganizationsNotInUseException"; then
    log "INFO" "Account is not part of an AWS Organization (no SCPs to check)"
  else
    log "WARNING" "Unable to check for Service Control Policies"
    echo -e "${YELLOW}  Error: ${scp_check_output}${NC}"
    echo -e "${YELLOW}  Please manually verify that no SCPs are blocking the required IAM roles${NC}"
  fi
fi

echo -e "\n"
if [ ${#blocked_endpoints[@]} -gt 0 ]; then
  log "WARNING" "Checks completed with blocked endpoints. Review the errors above before you deploy."
  exit 1
fi
log "INFO" "Checks completed. Review any errors or warnings above before you deploy."
exit 0

