# Copyright (C) 2019 Intel Corporation.  All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: create a tag

on:
  workflow_call:
    outputs:
      minor_version:
        description: "the new version is a minor version or a major version"
        value: ${{ jobs.create_tag.outputs.minor_version}}
      new_ver:
        description: "the new version"
        value: ${{ jobs.create_tag.outputs.new_ver}}
      new_tag:
        description: "the new tag just created"
        value: ${{ jobs.create_tag.outputs.new_tag}}

jobs:
  create_tag:
    runs-on: ubuntu-latest
    outputs:
      minor_version: ${{ steps.preparation.outputs.minor_version }}
      new_ver: ${{ steps.preparation.outputs.new_ver }}
      new_tag: ${{ steps.preparation.outputs.new_tag }}

    steps:
      - uses: actions/checkout@v3
        # Full git history is needed to get a proper list of commits and tags
        with:
          fetch-depth: 0

      - name: prepare
        id: preparation
        run: |
          # show latest 3 versions
          git tag --list WAMR-*.*.* --sort=committerdate --format="%(refname:short)" | tail -n 3
          # compare latest git tag and semantic version definition
          result=$(python3 ./.github/scripts/fetch_and_compare_version.py)
          echo "script result is ${result}"
          #
          # return in a form like "WAMR-X.Y.Z,major_minor_change" or ",patch_change"
          new_ver=$(echo "${result}" | awk -F',' '{print $1}')
          diff_versioning=$(echo "${result}" | awk -F',' '{print $2}')
          echo "next version is ${new_ver}, it ${diff_versioning}"
          #
          # set output
          if [[ ${diff_versioning} == 'major_minor_change' ]];then
            echo "minor_version=true" >> "$GITHUB_OUTPUT"
          else
            echo "minor_version=false" >> "$GITHUB_OUTPUT"
          fi
          #
          #
          if [[ -z ${new_ver} ]]; then
            echo "::error::please indicate the right semantic version in core/version.h"
            echo "new_ver=''" >> "$GITHUB_OUTPUT"
            echo "new_tag=''" >> "$GITHUB_OUTPUT"
            exit 1
          else
            echo "new_ver=${new_ver}" >> "$GITHUB_OUTPUT"
            echo "new_tag=WAMR-${new_ver}" >> "$GITHUB_OUTPUT"
          fi

      - name: push tag
        if: steps.preparation.outputs.new_tag != ''
        run: |
          git tag ${{ steps.preparation.outputs.new_tag }}
          git push origin --force --tags
