name: "Draft new release"

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'The new version in X.Y.Z format.'
        required: true

jobs:
  draft-new-release:
    name: "Draft a new release"
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2.3.4
        with:
          token: ${{ secrets.BOTTY_GITHUB_TOKEN }}

      - name: Create release branch
        run: git checkout -b release/${{ github.event.inputs.version }}

      - name: Initialize mandatory git config
        run: |
          git config user.name "${{ secrets.BOTTY_NAME }}"
          git config user.email ${{ secrets.BOTTY_EMAIL }}

      - name: Bump version in Cargo.toml
        uses: thomaseizinger/set-crate-version@1.0.0
        with:
          version: ${{ github.event.inputs.version }}
          manifest: daemon/Cargo.toml

      - name: Update Cargo.lock
        run: cargo update --workspace

      - name: Commit changelog and manifest files
        id: make-commit
        run: |
          git add Cargo.lock daemon/Cargo.toml
          git commit --message "Prepare release ${{ github.event.inputs.version }}"

          echo "::set-output name=commit::$(git rev-parse HEAD)"

      - name: Create pull request
        run: |
          # Force push to allow for easier re-runs of the action
          git push origin ${{ env.RELEASE_BRANCH }} --force
          # Use heredoc to define multiline string: https://stackoverflow.com/a/23930212/2489334
          BODY=$(cat <<-EOF
          Hi @${{ github.actor }}!
          This PR was created in response to a manual trigger of the release workflow here: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}.
          I've bumped the versions in the manifest files in this commit: ${{ steps.make-commit.outputs.commit }}.
          Merging this PR will create a GitHub release and publish the library to crates.io!
          EOF
          )
          gh pr create \
            --reviewer ${{ github.actor }} \
            --title "Release version ${{ github.event.inputs.version }}" \
            --head ${{ env.RELEASE_BRANCH }} \
            --body "$BODY"
        env:
          # Using a bot account is important to trigger subsequent workflows.
          # See https://devopsdirective.com/posts/2020/07/stupid-github-actions/#2----recursive-action.
          GITHUB_TOKEN: ${{ secrets.BOTTY_GITHUB_TOKEN }}