#!/bin/bash

# WARNING: This script is meant for Docker Compose execution in docker/schema-gen, do not run it directly

# if INJECT_CODEGENENV is not present, stop the script and warn the user
if [ -z "$INJECT_CODEGENENV" ]; then
  echo "Codegen: INJECT_CODEGENENV is not set, please run the script using docker-compose project located in `docker/schema-gen`"
  exit 1
fi

# schemas folder must be present
if [ ! -d "./schemas" ]; then
  echo "Codegen: `schemas` folder not found"
  exit 1
fi

# gql folder must be present
if [ ! -d "../gql" ]; then
  echo "Codegen: `gql` folder not found"
  exit 1
fi

mkdir -p ./gql-cache
# copy all files from gql folder to gql-cache folder, prevent gql being prefixed
cp -r ../gql/* ./gql-cache
find ./gql-cache -type f -name "*.graphql"

# list out graphql schema files in schemas dir
SCHEMA_FILES=$(find ./schemas -type f -name "*.graphql")
# echo them out
echo "Codegen: Found schema files: $SCHEMA_FILES"

# generate typescript types from graphql schema
yarn exec graphql-codegen --config codegen.ts

FILES=$(find ./gql-cache -type f -name "*.ts")
echo $FILES

# move all .ts files from gql folder to generated folder recursively while keeping their paths and removing gql-cache/gql prefix
for FILE in $FILES; do
  DEST_FILE=$(echo $FILE | sed 's/gql-cache/generated/g')
  mkdir -p $(dirname $DEST_FILE)
  mv $FILE $DEST_FILE
done

rm -rf ./gql-cache

echo "Codegen: Done"
 
#The script is pretty straightforward. It checks if the  schemas  and  gql  folders are present. If they are, it runs the codegen script. After the codegen script is done, it moves all the generated files from the  gql  folder to the  generated  folder. 
# The codegen script is a simple script that uses the  graphql-codegen  package to generate typescript types from the graphql schema. 
# Path: codegen/codegen.ts