utopia-remix/fga-create-store.sh
#!/usr/bin/env bash

# Create a new store based on the fga/model.fga file against the local FGA server,
# then parse the generated Store ID and save it into the .env file.

set -e

HOST_ENV_KEY="FGA_API_HOST"
STORE_ENV_KEY="FGA_STORE_ID"

# Only run this if the .env file uses the local FGA store
if ! grep -qE "^[^#]*\b${HOST_ENV_KEY}\b=['\"]?localhost" .env; then
	echo "The FGA_API_HOST is either not defined or not set to localhost, so I won't do anything."
	exit
fi

if type docker &> /dev/null; then
	RUNTIME=docker
elif type podman &> /dev/null; then
	RUNTIME=podman
else
	echo "The docker or podman commands are not found."
	exit
fi

SERVICE_NAME="utopia-fga-model-${RUNTIME}"

echo "* Creating store…"
${RUNTIME} compose -f docker-compose.fga.yml up ${SERVICE_NAME}

# Note: it would be awesome to just use jq here, but there's no guarantee it
# will be available on the host machine, so this is just doing a simple regex
# match since the JSON output of the FGA CLI is simple enough.
echo "* Parsing logs…"
STORE_ID=$( ${RUNTIME} logs -f ${SERVICE_NAME} | tail -n1 | grep -o '"id":"[^"]*"' | awk -F':' '{print $2}' | tr -d '"' )

echo "=> Obtained store id ${STORE_ID}"

STORE_ENV_LINE="${STORE_ENV_KEY}=\"${STORE_ID}\" # ** GENERATED BY fga-create-store.sh **"

grep -vE "\b${STORE_ENV_KEY}\b=" .env > .env.temp
mv .env.temp .env
echo "${STORE_ENV_LINE}" >> .env

echo "=> Updated .env file"
