#!/bin/bash -ex
ENVIRONMENT="$1"

echo "GITHUB_REF: $GITHUB_REF"
if [[ "$GITHUB_REF" == refs/tags/* ]]; then
  # Tag
  GIT_TAG=$(echo $GITHUB_REF | sed -E 's,refs/tags/,,')
elif [[ "$GITHUB_REF" == refs/heads/* ]]; then
  # Branch
  GIT_TAG=$(echo $GITHUB_REF | sed -E 's,refs/heads/,,')
elif [[ "$GITHUB_REF" == refs/pull/* ]]; then
  # Pull Request
  GIT_TAG=$GITHUB_HEAD_REF
fi

GIT_TAG=$(echo $GIT_TAG | sed -E 's,/,-,g')
echo "GIT_TAG: $GIT_TAG"

shift

schema_files=$(for file in "$@"; do basename "$file"; done | tr '\n' ' ')
echo "Building environment '$ENVIRONMENT' with schemas: $schema_files"

# Generate SQL files from Felis yaml files
# Place the SQL files in the sql directory, which gets
# copied into the docker image.
schema_index=0
unique_flag=""
if [ "$FELIS_UNIQUE_KEYS" == "1" ]; then
    echo "Generating unique keys"
    unique_flag="-u"
fi
for file in $@
do
    felis load-tap-schema \
        --tap-schema-index $schema_index \
        --dry-run \
        --engine-url=mysql:// \
        --tap-schema-name=tap_schema \
        --tap-tables-postfix=11 \
        --force-unbounded-arraysize \
        --output-file sql/`basename $file`.sql \
        $unique_flag \
        $file
    schema_index=$((schema_index+1))
done

# Build and push docker images
docker buildx create  --name tap-schema --driver docker-container \
       --platform linux/amd64 --platform linux/arm64
docker buildx build --push --builder tap-schema --progress plain \
       --platform linux/amd64 --platform linux/arm64 \
       --tag lsstsqre/tap-schema-$ENVIRONMENT:$GIT_TAG .
docker buildx rm tap-schema

echo "Pushed Docker image: lsstsqre/tap-schema-$ENVIRONMENT:$GIT_TAG"

# Clean up any untracked files in the sql directory
# between the different runs of this script.
git clean -n
git clean -f sql
