name: Release

on:
  push:
    tags:
      - "v*"

jobs:
  build:
    name: Create Release
    runs-on: ubuntu-latest
    steps:
      - name: Set up Go
        uses: actions/setup-go@v2
        with:
          go-version: 1.18
      - name: Checkout code
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Release Note
        run: |
          RELEASE_VERSION=${GITHUB_REF#refs/*/}
          PREVERSION=$(git for-each-ref --sort='-creatordate' --format='%(refname:lstrip=2)' --count=50 'refs/tags/*' | grep -v 'rc' | awk 'NR==2')
          echo ${PREVERSION}
          echo ${PREVERSION}
          echo "$(./.github/release-note.sh ${PREVERSION} ${RELEASE_VERSION})" > release_note.md
      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
        with:
          tag_name: ${{ github.ref }}
          release_name: Release ${{ github.ref }}
          draft: false
          prerelease: false
          body_path: release_note.md

      - name: Collect Release Info
        run: |
          echo "${{ steps.create_release.outputs.upload_url }}" >> UPLOAD_URL
          echo ${{ env.RELEASE_VERSION }} >> RELEASE_VERSION
          git reset --hard

      - name: Upload RELEASE_VERSION
        uses: actions/upload-artifact@v2
        with:
          name: RELEASE_VERSION
          path: RELEASE_VERSION

      - name: Upload UPLOAD_URL
        uses: actions/upload-artifact@v2
        with:
          name: UPLOAD_URL
          path: UPLOAD_URL

      - name: Push image to docker hub
        run: |
          echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USER }} --password-stdin
          make all-image

      - name: Repository Dispatch
        uses: peter-evans/repository-dispatch@v1
        with:
          token: ${{ secrets.REPOSITORYDISPATCH }}
          event-type: release-event
          client-payload: '{"url": "${{ steps.create_release.outputs.upload_url }}", "tag": "${{ github.ref }}"}'
