#!/usr/bin/env bash

VERSION=""

while [[ "$#" -gt 0 ]]; do
  case $1 in
    -v|--version)
      VERSION=$2
      shift 2;;
    *)
      shift;;
  esac
done

# Initialize and update git submodules
git submodule init
git submodule update --remote

if [ -n "$VERSION" ]; then
    echo "Required version: $VERSION"
    echo "Pulling files for version: $VERSION"

    for repo in "backend" "definition-registry" "docker-deployment"; do
        if [ -d "./$repo" ]; then
            cd "./$repo"

            git fetch --tags &>/dev/null
            git checkout main &>/dev/null # Ensure we are on a valid branch before switching
            git checkout tags/$VERSION &>/dev/null

            if [ $? -ne 0 ]; then
                echo "⚠️  Warning: The tag '$VERSION' was not found in the '$repo' repository."
                echo "⚠️  Using the main branch instead."
            fi

            cd ../  # Return to the main directory
        fi
    done
else
    echo "No version provided, using the NEWEST files."
fi
