---
name: Deploy workflow
on:
  workflow_dispatch:
    inputs:
      comments:
        description: "Comments"
      branch:
        description: The branch from which to make the release
        required: true
        default: master

jobs:
  release_changelog:
    runs-on: ubuntu-latest

    steps:
      - name: Print author
        run: |
          echo "Author: ${{ github.triggering_actor }}"
          echo "Comments: ${{ github.event.inputs.comments }}"

      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.branch }}

      - name: Draft change log
        uses: release-drafter/release-drafter@v5
        id: release-drafter
        with:
          commitish: ${{ github.event.inputs.branch }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      # Can replace the below with (until pipeline description) with
      # khanlab/actions/.github/workflows/workflow-version_task-publishGithub.yml
      # after adding PAT token
      - name: Set new release version
        env:
          RD_RELEASE: ${{ steps.release-drafter.outputs.name }}
        run: |
          if [ ! -z "$RD_RELEASE" ]; then
            echo "NEW_RELEASE=$RD_RELEASE" >> $GITHUB_ENV
          else
            echo "NEW_RELEASE=0.1.0" >> $GITHUB_ENV
          fi

      - name: Update version in pyproject.toml
        uses: jacobtomlinson/gha-find-replace@v3
        with:
          include: "pyproject.toml"
          find: 'version = "(?:([0-9]+\.[0-9]+\.[0-9]+.+)|([0-9]+\.[0-9]+\.[0-9]+))"'
          replace: 'version = "${{ env.NEW_RELEASE }}"'

      - name: Update version in pipeline_description (not actually used)
        uses: jacobtomlinson/gha-find-replace@v3
        with:
          include: "hippunfold/pipeline_description.json"
          find: '"Version": "(?:([0-9]+\.[0-9]+\.[0-9]+.+)|([0-9]+\.[0-9]+\.[0-9]+))"'
          replace: '"Version": "${{ env.NEW_RELEASE }}"'

      - name: Update version in config/snakebids.yml
        uses: jacobtomlinson/gha-find-replace@v3
        with:
          include: "hippunfold/config/snakebids.yml"
          find: 'version: "(?:([0-9]+\.[0-9]+\.[0-9]+.+)|([0-9]+\.[0-9]+\.[0-9]+))"'
          replace: 'version: "${{ env.NEW_RELEASE }}"'

      - name: Commit updates
        env:
          LATEST_VERSION: ${{ env.NEW_RELEASE }}
        run: |
          git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git diff-index --quiet HEAD || git commit -m "Bump version to $LATEST_VERSION" -a

      - name: Push changes
        uses: ad-m/github-push-action@v0.8.0
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}

      - name: Publish change log
        uses: release-drafter/release-drafter@v5
        with:
          publish: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
