#!/bin/bash

# ==========================================================================
# SCRIPT: privatelink_setup.sh
# DESCRIPTION: Sets up VPC Gateway Endpoints for Amazon S3 and Amazon DynamoDB
#              using AWS CLI. These endpoints allow instances in your VPC to
#              access these AWS services privately, without traversing the
#              public internet. This enhances security and can reduce data
#              transfer costs.
#
# USE CASE SCENARIO:
# An application running in a private subnet within a VPC needs to securely
# access Amazon S3 and DynamoDB without exposing traffic to the public internet.
# This script automates the creation of the necessary Gateway Endpoints and
# associates them with specified route tables.
#
# PREREQUISITES:
# 1.  **AWS CLI:** The AWS Command Line Interface must be installed and configured
#     with credentials that have the necessary permissions.
# 2.  **IAM Permissions:** The principal executing this script must have:
#     - `ec2:DescribeVpcEndpoints`
#     - `ec2:CreateVpcEndpoint`
#     - `ec2:DescribeRouteTables` (implicitly needed if you need to find route tables)
# 3.  **Existing Resources:**
#     - A VPC where the endpoints will be created.
#     - One or more Route Tables within that VPC that need to be updated to use the endpoint.
#
# HOW TO USE:
# 1.  **Save the script:** Save this content as `privatelink_setup.sh`.
# 2.  **Make it executable:** `chmod +x privatelink_setup.sh`
# 3.  **Configure variables:** Open the script and update the `--- Configuration Variables ---`
#     section with your specific environment details.
# 4.  **Run from your terminal:** `./privatelink_setup.sh`
#
# IMPORTANT CONSIDERATIONS:
# - This script creates Gateway Endpoints, which are free. Interface Endpoints (for other services)
#   incur charges.
# - Ensure your security groups and NACLs allow traffic to/from the endpoint.
# - The script checks for existing endpoints to prevent recreation errors.
# - The `ROUTE_TABLE_IDS` variable should contain space-separated IDs.
# ==========================================================================

# --- Configuration Variables (REPLACE with your actual values) ---
VPC_ID="vpc-0abcdef1234567890"          # The ID of your VPC (e.g., "vpc-xxxxxxxxxxxxxxxxx")
ROUTE_TABLE_IDS="rtb-0abcdef1234567890 rtb-0fedcba9876543210" # Space-separated list of Route Table IDs
                                     # Traffic destined for S3/DynamoDB from subnets associated with these
                                     # route tables will be routed through the endpoint.
AWS_REGION="us-east-1"                    # AWS region
CREATE_S3_ENDPOINT="true"                 # Set to "true" (string) to create S3 Gateway Endpoint, "false" otherwise
CREATE_DYNAMODB_ENDPOINT="true"           # Set to "true" (string) to create DynamoDB Gateway Endpoint, "false" otherwise
# ----------------------------------------------------------------

echo "Starting PrivateLink (VPC Gateway Endpoints) setup script in region ${AWS_REGION}...\n"

# Function to check if a VPC endpoint already exists for a given service and VPC.
# This prevents attempting to create an endpoint that already exists.
check_endpoint_exists() {
    local service_name="$1" # e.g., "s3" or "dynamodb"
    local vpc_id="$2"
    local region="$3"
    aws ec2 describe-vpc-endpoints \
        --filters "Name=vpc-id,Values=${vpc_id}" "Name=service-name,Values=com.amazonaws.${region}.${service_name}" \
        --query "VpcEndpoints[0].VpcEndpointId" \
        --region "${region}" \
        --output text 2>/dev/null # Redirect stderr to /dev/null to suppress "No such file or directory" errors if endpoint doesn't exist
}

# ==========================================================================
# STEP 1: Setup S3 Gateway Endpoint (if enabled in configuration).
# This creates a route in the specified route tables to S3 via the endpoint.
# ==========================================================================
if [ "${CREATE_S3_ENDPOINT}" = "true" ]; then
    echo ">>> Step 1: Setting up S3 Gateway Endpoint for VPC '${VPC_ID}'..."
    EXISTING_S3_ENDPOINT=$(check_endpoint_exists "s3" "${VPC_ID}" "${AWS_REGION}")

    if [ -n "${EXISTING_S3_ENDPOINT}" ]; then
        echo "   S3 Gateway Endpoint already exists in VPC '${VPC_ID}'. Endpoint ID: ${EXISTING_S3_ENDPOINT}"
    else
        # Create the VPC endpoint. `VpcEndpointType="Gateway"` is specific to S3 and DynamoDB.
        # `service-name` follows the pattern `com.amazonaws.<region>.<service>`.
        # `route-table-ids` specifies which route tables will have a route added for S3.
        S3_ENDPOINT_ID=$(aws ec2 create-vpc-endpoint \
            --vpc-endpoint-type "Gateway" \
            --vpc-id "${VPC_ID}" \
            --service-name "com.amazonaws.${AWS_REGION}.s3" \
            --route-table-ids ${ROUTE_TABLE_IDS} \
            --tag-specifications "ResourceType=vpc-endpoint,Tags=[{Key=Name,Value=${VPC_ID}-s3-gateway-endpoint}]" \
            --query "VpcEndpoint.VpcEndpointId" \
            --region "${AWS_REGION}" \
            --output text)
        if [ $? -eq 0 ]; then
            echo "   S3 Gateway Endpoint '${S3_ENDPOINT_ID}' created successfully."
        else
            echo "Error creating S3 Gateway Endpoint. Exiting.\n"
            exit 1
        fi
    fi
else
    echo "Skipping S3 Gateway Endpoint creation as CREATE_S3_ENDPOINT is 'false'.\n"
fi

# ==========================================================================
# STEP 2: Setup DynamoDB Gateway Endpoint (if enabled in configuration).
# This creates a route in the specified route tables to DynamoDB via the endpoint.
# ==========================================================================
if [ "${CREATE_DYNAMODB_ENDPOINT}" = "true" ]; then
    echo "\n>>> Step 2: Setting up DynamoDB Gateway Endpoint for VPC '${VPC_ID}'..."
    EXISTING_DYNAMODB_ENDPOINT=$(check_endpoint_exists "dynamodb" "${VPC_ID}" "${AWS_REGION}")

    if [ -n "${EXISTING_DYNAMODB_ENDPOINT}" ]; then
        echo "   DynamoDB Gateway Endpoint already exists in VPC '${VPC_ID}'. Endpoint ID: ${EXISTING_DYNAMODB_ENDPOINT}"
    else
        # Create the VPC endpoint for DynamoDB.
        DYNAMODB_ENDPOINT_ID=$(aws ec2 create-vpc-endpoint \
            --vpc-endpoint-type "Gateway" \
            --vpc-id "${VPC_ID}" \
            --service-name "com.amazonaws.${AWS_REGION}.dynamodb" \
            --route-table-ids ${ROUTE_TABLE_IDS} \
            --tag-specifications "ResourceType=vpc-endpoint,Tags=[{Key=Name,Value=${VPC_ID}-dynamodb-gateway-endpoint}]" \
            --query "VpcEndpoint.VpcEndpointId" \
            --region "${AWS_REGION}" \
            --output text)
        if [ $? -eq 0 ]; then
            echo "   DynamoDB Gateway Endpoint '${DYNAMODB_ENDPOINT_ID}' created successfully."
        else
            echo "Error creating DynamoDB Gateway Endpoint. Exiting.\n"
            exit 1
        fi
    fi
else
    echo "Skipping DynamoDB Gateway Endpoint creation as CREATE_DYNAMODB_ENDPOINT is 'false'.\n"
fi

echo "\n=== PrivateLink (VPC Gateway Endpoints) setup script completed. ===\n"
