#!/bin/bash

echo "Starting postCreateCommand"

if [ "$CODESPACE_NAME" ]; then
    BASE_NAME=`echo ${CODESPACE_NAME//-} | head -c 12`
else
    BASE_NAME=`echo ${HOSTNAME//-} | head -c 12`
fi

# create environment variables to support deployment
echo "
export SESSION=$PWD/.session
export CLUSTER_NAME=${BASE_NAME}
export STORAGE_ACCOUNT=${BASE_NAME}storage
export SCHEMA_REGISTRY=${BASE_NAME}schema
export SCHEMA_REGISTRY_NAMESPACE=${BASE_NAME}schemans
export PATH=$PATH:~/.dotnet/tools
" >> ~/.bashrc

# create a default resource group if not defined
if [ -z "$RESOURCE_GROUP" ]; then
    echo "export RESOURCE_GROUP=aio-${BASE_NAME}" >> ~/.bashrc
fi

# create a default location if not defined
if [ -z "$LOCATION" ]; then
    echo "export LOCATION=westus3" >> ~/.bashrc
fi

# Set the workspace as a safe directory
git config --global --add safe.directory /workspaces

echo "Environment variables:
    SUBSCRIPTION_ID:           $SUBSCRIPTION_ID
    RESOURCE_GROUP:            $RESOURCE_GROUP
    LOCATION:                  $LOCATION
    CLUSTER_NAME:              $CLUSTER_NAME
    STORAGE_ACCOUNT:           $STORAGE_ACCOUNT
    SCHEMA_REGISTRY:           $SCHEMA_REGISTRY
    SCHEMA_REGISTRY_NAMESPACE: $SCHEMA_REGISTRY_NAMESPACE"

# Add a convenience alias for the aio-broker
sudo sh -c 'echo 127.0.0.1 aio-broker >> /etc/hosts'

# Stop and start the cluster, so its in a fresh state
k3d cluster stop
k3d cluster start --wait

echo "Ending postCreateCommand"
