name: Create Release Notes

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'SemVer format release tag, i.e. 0.24.5'
        required: true
  repository_dispatch:
    types: [ release-notes ]

jobs:
  create-release-notes:
    runs-on: ubuntu-18.04
    steps:
      - name: Get Vars
        id: get_vars
        run: |
          if [ "$EVENT_NAME" == "workflow_dispatch" ]
          then
            release_id=$(curl -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/dolthub/dolt/releases/tags/v${{ github.event.inputs.version }} | jq '.id')
            echo "::set-output name=version::${{ github.event.inputs.version }}"
            echo "::set-output name=release_id::$release_id"
          else
            echo "::set-output name=version::${{ github.event.client_payload.version }}"
            echo "::set-output name=release_id::${{ github.event.client_payload.release_id }}"
          fi
        env:
          EVENT_NAME: ${{ github.event_name }}
      - name: Checkout Release Notes Generator
        uses: actions/checkout@v2
        with:
          repository: dolthub/release-notes-generator
          token: ${{ secrets.REPO_ACCESS_TOKEN }}
      - name: Install Dependencies
        run: sudo ./install-deps.sh
        env:
          PERL_MM_USE_DEFAULT: 1
      - name: Create Notes
        run: |
          git clone https://github.com/dolthub/dolt.git
          ./gen_release_notes.pl \
          --token "$TOKEN" \
          -d dolthub/go-mysql-server \
          -d dolthub/vitess dolthub/dolt v${{ steps.get_vars.outputs.version }} > changelog.txt
        env:
          TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
      - name: Post Changelog to Release
        uses: actions/github-script@v4
        with:
          debug: true
          github-token: ${{ secrets.REPO_ACCESS_TOKEN }}
          script: |
            const fs = require('fs');
            const path = require('path')
            try {
              const body = fs.readFileSync(path.join(process.env.WORKSPACE, "changelog.txt"),  { encoding: "utf8" })
              const res = await github.repos.updateRelease({
                owner: "dolthub",
                repo: "dolt",
                release_id: parseInt(process.env.RELEASE_ID, 10),
                body,
              });
              console.log("Successfully updated release notes", res)
            } catch (err) {
              console.log("Error", err);
              process.exit(1);
            }
        env:
          WORKSPACE: ${{ github.workspace }}
          RELEASE_ID: ${{ steps.get_vars.outputs.release_id }}
