#!/bin/bash -e

ssh git@gitlab.nexdev.uk

echo "Cloning 'git@gitlab.nexdev.uk:$CI_PROJECT_PATH.git'"
git clone "git@gitlab.nexdev.uk:$CI_PROJECT_PATH.git"  -q > /dev/null

echo "Running standard version"
cd "$CI_PROJECT_NAME"
NODE_PATH=$(npm root -g) standard-version \
    --commitUrlFormat "https://gitlab.nexdev.uk/$CI_PROJECT_PATH/-/commit/{{hash}}" \
    --compareUrlFormat "https://gitlab.nexdev.uk/$CI_PROJECT_PATH/-/compare/{{previousTag}}...{{currentTag}}" \
    --issueUrlFormat "https://gitlab.nexdev.uk/$CI_PROJECT_PATH/-/issues/{{id}}"

echo "Pushing new commit"

# Check arguments for --run-tag-pipeline
while :; do
  case $1 in
    -t|--run-tag-pipeline)
      # Push the commit separately from the tag
      git push -o ci.skip
      # Grab the tag at this commit
      TAG=$(git tag --points-at HEAD)
      # Push the tag to origin
      git push origin "$TAG"
      exit
      ;;
    -a|--run-all-pipelines)
      # Push both together without skipping the CI job
      git push --follow-tags
      exit
      ;;
    --)
      # End of options
      shift
      break
      ;;
    -?*)
      # Unrecognised option - ignore and continue
      printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
      ;;
    *)
      # Default case, flag not found, break out and continue with the default command
      break
  esac

  shift
done

# No flag passed, follow-tags instead
git push --follow-tags -o ci.skip