name: Prepare release
on:
  workflow_dispatch:

jobs:
  update-for-release:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v6
      with:
        fetch-depth: 0
        fetch-tags: true
    - name: Setup git
      run: |
        git config user.name 'lballabio[bot]'
        git config user.email '224797326+lballabio-bot@users.noreply.github.com'
    - name: Calculate versions
      env:
        GH_TOKEN: ${{ github.token }}
      run: |
        export LATEST_RELEASE=`gh release list --json name,isLatest --jq '.[] | select(.isLatest)|.name'`
        echo ${LATEST_RELEASE} | awk -F '.' '{ print "LATEST_MINOR=" $2 }' | tee -a $GITHUB_ENV
        echo ${LATEST_RELEASE} | awk -F '.' '{ print "NEXT_MINOR=" $2 + 1 }' | tee -a $GITHUB_ENV
    - name: Update version numbers
      run: |
        sed -i -e "s/^AC_INIT(\[QuantLib\].*$/AC_INIT([QuantLib], [1.${NEXT_MINOR}],/g" configure.ac
        sed -i -e "s/^#define QL_VERSION.*$/#define QL_VERSION \"1.${NEXT_MINOR}\"/g" ql/version.hpp
        sed -i -e "s/^#define QL_HEX_VERSION.*$/#define QL_HEX_VERSION 0x01${NEXT_MINOR}00f0/g" ql/version.hpp
        sed -i -e "s/^set(PACKAGE_VERSION  .*$/set(PACKAGE_VERSION       \"1.${NEXT_MINOR}\"\)/g" CMakeLists.txt
        sed -i -e "s/^set(PACKAGE_VERSION_HEX.*$/set(PACKAGE_VERSION_HEX   \"0x01${NEXT_MINOR}00f0\"\)/g" CMakeLists.txt
        git commit -a -m "Set version to 1.${NEXT_MINOR}"
    - name: Update ChangeLog
      run: |
        git log --pretty=medium --date=rfc --stat --grep='Merge [^p]' --grep='[Mm]erged' --grep='[Pp]ull from' --invert-grep v1.${LATEST_MINOR}... > ChangeLog.txt
        git commit -a -m "Update changelog"
    - uses: peter-evans/create-pull-request@v8
      with:
        token: ${{ secrets.MACHINE_ACCOUNT_PAT }}
        push-to-fork: ${{ vars.MACHINE_ACCOUNT }}/QuantLib
        branch: update-version-for-release-${{ github.ref_name }}
        delete-branch: true
        title: 'Set version to 1.${{ env.NEXT_MINOR }} final'
        author: lballabio[bot] <224797326+lballabio-bot@users.noreply.github.com>
