#!/bin/bash

# Prompt for VCD details
read -p "Enter VMware Cloud Director URL (e.g., https://vcd.example.com): " VCD_URL
read -p "Enter your VCD username (e.g., user@org or user@system for Provider Access): " USERNAME
read -rs -p "Enter your VCD password: " PASSWORD
echo ""

# Headers
API_VERSION="38.1"
AUTH_HEADER="application/json;version=$API_VERSION"

# Authenticate and get bearer token
echo "Authenticating to VCD..."

RESPONSE=$(curl -ksSL -D - -X POST "$VCD_URL/cloudapi/1.0.0/sessions/provider" -H "Accept: ${AUTH_HEADER}" -u "${USERNAME}:${PASSWORD}")

TOKEN=$(echo "$RESPONSE" | grep -Fi x-vmware-vcloud-access-token | awk -F': ' '{print $2}' | tr -d '\r')

if [ -z "$TOKEN" ]; then
  echo "Failed to authenticate. Check your credentials."
  exit 1
fi

echo "Authentication successful. Token acquired."
echo ""
read -p "Enter the Edge Gateway ID: " EDGEGW_ID

echo "Fetching NAT rules for Edge Gateway '$EDGEGW_ID'..."

# Get all NAT rules for the Edge Gateway
NAT_RULES_JSON=$(curl -ksSL "$VCD_URL/cloudapi/1.0.0/edgeGateways/$EDGEGW_ID/nat/rules?pageSize=500" -H "Accept: $AUTH_HEADER" -H "Authorization: Bearer $TOKEN")

# Extract all rule IDs
RULE_IDS=$(echo "$NAT_RULES_JSON" | jq -r '.values[] | .id')

if [ -z "$RULE_IDS" ]; then
  echo "No NAT rules found."
  exit 1
fi

# Loop over each NAT rule and enable it
for RULE_ID in $RULE_IDS; do
  echo "Enabling NAT rule: $RULE_ID"

  # Get full rule JSON
  RULE_JSON=$(curl -ksSL "$VCD_URL/cloudapi/1.0.0/edgeGateways/$EDGEGW_ID/nat/rules/$RULE_ID" \
    -H "Accept: $AUTH_HEADER" \
    -H "Authorization: Bearer $TOKEN")

  # Modify 'enabled' to true using jq
  UPDATED_RULE_JSON=$(echo "$RULE_JSON" | jq '.enabled = true')

  # PUT the updated rule
  curl -ksS -X PUT "$VCD_URL/cloudapi/1.0.0/edgeGateways/$EDGEGW_ID/nat/rules/$RULE_ID" \
    -H "Accept: $AUTH_HEADER" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$UPDATED_RULE_JSON"

  echo "Rule $RULE_ID enabled."
  sleep 3

done

echo "All NAT rules Enabled."
