version: 0.2

phases:
  build:
    commands:
      - echo "Building and pushing Docker image"
      - |
        # Determine branch name or use fallback
        if [ -n "$CODEBUILD_WEBHOOK_HEAD_REF" ]; then
          BRANCH_NAME=$(echo $CODEBUILD_WEBHOOK_HEAD_REF | sed 's/refs\/heads\///')
        elif [ -n "$CODEBUILD_SOURCE_VERSION" ]; then
          BRANCH_NAME=$CODEBUILD_SOURCE_VERSION
        else
          BRANCH_NAME="unknown"
        fi

        # Replace '/' with '-' and remove any invalid characters for Docker tag
        SAFE_BRANCH_NAME=$(echo $BRANCH_NAME | sed 's/[^a-zA-Z0-9._-]/-/g')

        # Use "latest" if branch name is empty or only contains invalid characters
        if [ -z "$SAFE_BRANCH_NAME" ]; then
          SAFE_BRANCH_NAME="latest"
        fi

        # Get the git repository short name
        REPO_SHORT_NAME=$(basename -s .git `git config --get remote.origin.url`)
        if [ -z "$REPO_SHORT_NAME" ]; then
          REPO_SHORT_NAME="verification"
        fi

        # Parse the env variable string into an array
        mapfile -d ' ' -t IMAGE_BASE_VERSIONS <<< "$ISAACSIM_BASE_VERSIONS_STRING"
        for IMAGE_BASE_VERSION in "${IMAGE_BASE_VERSIONS[@]}"; do
          IMAGE_BASE_VERSION=$(echo "$IMAGE_BASE_VERSION" | tr -d '[:space:]')
          # Combine repo short name and branch name for the tag
          COMBINED_TAG="${REPO_SHORT_NAME}-${SAFE_BRANCH_NAME}-${IMAGE_BASE_VERSION}"

          docker login -u \$oauthtoken -p $NGC_TOKEN nvcr.io
          docker build -t $IMAGE_NAME:$COMBINED_TAG \
            --build-arg ISAACSIM_BASE_IMAGE_ARG=$ISAACSIM_BASE_IMAGE \
            --build-arg ISAACSIM_VERSION_ARG=$IMAGE_BASE_VERSION \
            --build-arg ISAACSIM_ROOT_PATH_ARG=/isaac-sim \
            --build-arg ISAACLAB_PATH_ARG=/workspace/isaaclab \
            --build-arg DOCKER_USER_HOME_ARG=/root \
            -f docker/Dockerfile.base .
          docker push $IMAGE_NAME:$COMBINED_TAG
          docker tag $IMAGE_NAME:$COMBINED_TAG $IMAGE_NAME:$COMBINED_TAG-b$CODEBUILD_BUILD_NUMBER
          docker push $IMAGE_NAME:$COMBINED_TAG-b$CODEBUILD_BUILD_NUMBER
        done
