#!/bin/bash

# Change the values of these variables
ACCESS_TOKEN=YOUR_ACCESS_TOKEN
ADMIN_PORTAL_URL="YOUR_ADMIN_PORTAL_URL" # e.g. "https://my-domain-admin.example.com"

# Create 5 new products (named "product_1", "product_2" etc.)

for i in `seq 1 5`; do curl -k -X 'POST' \
  "$ADMIN_PORTAL_URL/admin/api/services.json" \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d "access_token=$ACCESS_TOKEN&name=product_$i";
done

# Extract service IDs

SERVICE_IDS=$(curl -k -s -X 'GET' \
  "$ADMIN_PORTAL_URL/admin/api/services.json?access_token=$ACCESS_TOKEN&page=1&per_page=500" \
  |  jq -r '[.services[].service.id] | join(",")')

echo "\nSERVICE_IDS: $SERVICE_IDS \n"
# SERVICE_IDS: 3,4,5,6,7,8

# Set a default backend for each new product (ignore errors for the products that are already configured)

BACKEND_ID=$(curl -k -s -X 'GET' \
  "$ADMIN_PORTAL_URL/admin/api/backend_apis.json?access_token=$ACCESS_TOKEN&page=1&per_page=500" \
  | jq '.backend_apis[0].backend_api.id')

echo $BACKEND_ID

for i in $(echo "$SERVICE_IDS" | tr ',' ' '); do
  curl -k -s -X 'POST' \
  "$ADMIN_PORTAL_URL/admin/api/services/$i/backend_usages.json" \
  -d "access_token=$ACCESS_TOKEN&backend_api_id=$BACKEND_ID&path=%2F"
done

# Promote each configuration to "staging"

for i in $(echo "$SERVICE_IDS" | tr ',' ' '); do
  curl -k -s -o /dev/null -w '%{http_code}\n'  -X 'POST' \
  "$ADMIN_PORTAL_URL/admin/api/services/$i/proxy/deploy.xml" \
  -d "access_token=$ACCESS_TOKEN"
done

# Promote each configuration to "production"

for i in $(echo "$SERVICE_IDS" | tr ',' ' '); do
  curl -k -s -o /dev/null -w '%{http_code}\n'  -X 'POST' \
  "$ADMIN_PORTAL_URL/admin/api/services/$i/proxy/configs/sandbox/1/promote.json" \
  -d "access_token=$ACCESS_TOKEN&to=production"
done
