#!/bin/bash

PRIVATE_IP_ENABLED=$(gcloud compute networks subnets describe $GCP_SUBNETWORK_NAME --region=$GCP_REGION --format="get(privateIpGoogleAccess)")

if [[ $PRIVATE_IP_ENABLED == "True" ]]; then
  echo 'PRIVATE_IP_ENABLED'
else
  gcloud compute networks subnets update $GCP_SUBNETWORK_NAME --region=$GCP_REGION --enable-private-ip-google-access
fi


ADDRESS_CREATED=$(gcloud compute addresses describe $GCP_INTERNAL_IP_NAME --region=$GCP_REGION --format="get(status)")

if [[ $ADDRESS_CREATED == "IN_USE" ]]; then
  echo 'ADDRESS_CREATED'
else
  gcloud compute addresses create $GCP_INTERNAL_IP_NAME --region=$GCP_REGION --subnet=$GCP_SUBNETWORK_NAME
fi


FORWARDING_RULE_ACCEPTED=$(gcloud compute forwarding-rules describe $GCP_PSC_NAME --region=$GCP_REGION --format="get(pscConnectionStatus)")

if [[ $FORWARDING_RULE_ACCEPTED == "ACCEPTED" ]]; then
  echo 'FORWARDING_RULE_ACCEPTED'
else
  gcloud compute forwarding-rules create $GCP_PSC_NAME --region=$GCP_REGION --network=$GCP_NETWORK_NAME --address=$GCP_INTERNAL_IP_NAME --target-service-attachment=$ELASTIC_SERVICE_ATTACHMENT_URI
fi


gcloud dns managed-zones describe $GCP_DNS_ZONE_MAGENTO_ELASTIC > /dev/null 2>&1
DNS_ZONE_CREATED=$?

if [[ $DNS_ZONE_CREATED == 0 ]]; then
  echo 'DNS_ZONE_CREATED'
else
  gcloud dns managed-zones create $GCP_DNS_ZONE_MAGENTO_ELASTIC --description="Managed by GitLab CI" --dns-name=$ELASTIC_DNS_ZONE. --visibility=private --networks=$GCP_NETWORK_NAME
  gcloud dns record-sets transaction start --zone="$GCP_DNS_ZONE_MAGENTO_ELASTIC"
  gcloud dns record-sets transaction add $(gcloud compute addresses describe $GCP_INTERNAL_IP_NAME --region=$GCP_REGION --format="get(address)") --name="*.$ELASTIC_DNS_ZONE." --ttl="30" --type="A" --zone="$GCP_DNS_ZONE_MAGENTO_ELASTIC"
  gcloud dns record-sets transaction execute --zone="$GCP_DNS_ZONE_MAGENTO_ELASTIC"
fi


echo "GCP_PSC_CONNECTION_ID=$(gcloud compute forwarding-rules describe $GCP_PSC_NAME --region=$GCP_REGION --format="get(pscConnectionId)")" > pscConnectionId.env