#!/bin/bash

# A script to create a basic AWS WAF Web ACL with a managed rule group using AWS CLI.

# --- Configuration ---
REGION="us-east-1"
WEB_ACL_NAME="MyCLIWafWebACL"
WEB_ACL_DESCRIPTION="Web ACL for CLI demo"
MANAGED_RULE_GROUP_NAME="AWSManagedRulesCommonRuleSet"

# --- 1. Create Web ACL ---
echo "--- Creating WAF Web ACL: $WEB_ACL_NAME ---"
WEB_ACL_ARN=$(aws wafv2 create-web-acl \
  --name $WEB_ACL_NAME \
  --scope REGIONAL \
  --default-action Allow={} \
  --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName="${WEB_ACL_NAME}Metric" \
  --description "$WEB_ACL_DESCRIPTION" \
  --region $REGION \
  --query 'Summary.ARN' --output text)

echo "Web ACL created with ARN: $WEB_ACL_ARN"

# Get Web ACL ID and LockToken for updates
WEB_ACL_ID=$(aws wafv2 list-web-acls \
  --scope REGIONAL \
  --region $REGION \
  --query "WebACLs[?Name=='$WEB_ACL_NAME'].Id" --output text)

LOCK_TOKEN=$(aws wafv2 get-web-acl \
  --name $WEB_ACL_NAME \
  --scope REGIONAL \
  --id $WEB_ACL_ID \
  --region $REGION \
  --query 'LockToken' --output text)

# --- 2. Add Managed Rule Group ---
echo -e "\n--- Adding Managed Rule Group: $MANAGED_RULE_GROUP_NAME to Web ACL ---"
aws wafv2 update-web-acl \
  --name $WEB_ACL_NAME \
  --scope REGIONAL \
  --id $WEB_ACL_ID \
  --lock-token $LOCK_TOKEN \
  --default-action Allow={} \
  --rules \
  $'[\n    {\n      "Name": "ManagedCommonRuleSet",\n      "Priority": 1,\n      "Statement": {\n        "ManagedRuleGroupStatement": {\n          "VendorName": "AWS",\n          "Name": "'"$MANAGED_RULE_GROUP_NAME"'"\n        }\n      },\n      "Action": { "Block": {} },\n      "VisibilityConfig": {\n        "SampledRequestsEnabled": true,\n        "CloudWatchMetricsEnabled": true,\n        "MetricName": "ManagedCommonRuleSetMetric"\n      }\n    }\n  ]' \
  --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName="${WEB_ACL_NAME}Metric" \
  --region $REGION

echo "Managed Rule Group added to Web ACL."

echo -e "\n--- WAF Web ACL Setup Complete! ---"
echo "Web ACL ARN: $WEB_ACL_ARN"
echo "You can now associate this Web ACL with an ALB, CloudFront distribution, or API Gateway."

read -p "Press Enter to delete the WAF Web ACL..."

# --- Clean Up ---
echo -e "\n--- Cleaning up resources ---"

# Get current LockToken before deleting
LOCK_TOKEN=$(aws wafv2 get-web-acl \
  --name $WEB_ACL_NAME \
  --scope REGIONAL \
  --id $WEB_ACL_ID \
  --region $REGION \
  --query 'LockToken' --output text)

# Delete Web ACL
echo "Deleting Web ACL '$WEB_ACL_NAME'வுகளை..."
aws wafv2 delete-web-acl \
  --name $WEB_ACL_NAME \
  --scope REGIONAL \
  --id $WEB_ACL_ID \
  --lock-token $LOCK_TOKEN \
  --region $REGION

echo "Web ACL deleted."

echo -e "\n--- WAF Web ACL demonstration and cleanup complete ---"
