#!/bin/bash

# Set git config
git config --global user.email "$GITLAB_USER_EMAIL"
git config --global user.name "$GITLAB_USER_NAME"

git remote update
git fetch
git checkout --track origin/"$CI_COMMIT_REF_NAME"

# Conditionally remove the old manifest files
if [ -f test/manifest-schema.json ]; then
  rm -f test/manifest-schema.json
  git add test/manifest-schema.json
fi
if [ -f test/manifestTester.js ]; then
  rm -f test/manifestTester.js
  git add test/manifestTester.js
fi
if [ -f test/manifestLinkTester.js ]; then
  rm -f test/manifestLinkTester.js
  git add test/manifestLinkTester.js
fi

# Add files to be commited
git add test/cypress/integration
git add test/cypress/plugins/index.js
git add test/cypress/support
git add test/cypress.json
git add package.json
git add package-lock.json
git add artifact.json
git add CHANGELOG.md
git add README.md

# Check existence of documentation_mapping file whether to commit
# generated metadata and markdown files
if [ -e "documentation/documentation_mapping.json" ]; then
  git add documentation
  git add metadata.json
  git add TAB1.md
  git add TAB2.md
else
  echo "Skipping git add of documentation"
fi

# Commit files
git commit -m "Committing auto-generated package.json, markdown files, metadata.json, and artifact.json, [skip ci]"

# Update git tag
NEW_VERSION=$(node -p "require('./artifact.json').metadata.version")
git tag -a v"$NEW_VERSION" -m "Bumping versions for package and artifact"

# Push to git
git remote set-url origin "https://$AUTHORIZED_USERNAME_WITH_UNDERSCORES:$GROUP_ACCESS_TOKEN@gitlab.com/$CI_PROJECT_PATH.git"
if git push --follow-tags --no-verify; then
  echo "Changes and tag pushed successfully to release branch"
else
  echo "Changes and tag failed to push to release branch"
  exit 1
fi

# Publish to NPM
if [ "${CI_PROJECT_NAMESPACE}" == "itentialopensource/pre-built-automations" ]; then
  if npm publish --registry=https://registry.npmjs.org --access=public; then
    echo "Project published to npmjs.com successfully."
  else
    echo "Project failed to publish to npmjs.com."
    exit 1
  fi
else
  echo "Skipping NPM publish step."
fi
