name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Set Tag as Filename
        id: tag_name
        run: echo "TAG_NAME=${GITHUB_REF##*/}" >> $GITHUB_ENV

      - name: Create ZIP file
        run: zip -r "${{ env.TAG_NAME }}.zip" .

      - name: Generate Changelog
        id: generate_changelog
        run: |
          # Find the most recent tag before the current one
          PREV_TAG=$(git describe --tags --abbrev=0 HEAD^)

          # Create a new CHANGELOG.md file with headers
          echo -e "# Changelog\n" > CHANGELOG.md

          # List commit messages between the previous tag and current HEAD
          git log ${PREV_TAG}..HEAD --pretty=format:"* %s" >> CHANGELOG.md

          # List unique contributors for these commits
          echo -e "\n\n# Contributors\n" >> CHANGELOG.md
          git log ${PREV_TAG}..HEAD --format='%aN' | sort -u | awk '{print "* " $0}' >> CHANGELOG.md

      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT }}
        with:
          tag_name: ${{ github.ref }}
          release_name: Release ${{ github.ref }}
          draft: false
          prerelease: false
          body_path: ./CHANGELOG.md

      - name: Upload Asset
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GH_PAT }}
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: ./${{ env.TAG_NAME }}.zip
          asset_name: source.zip
          asset_content_type: application/zip
