name: update-actions

on:
  schedule:
    - cron: "0 4 * * *"
  workflow_dispatch:

concurrency: update-actions-${{ github.ref }}

jobs:
  update-actions:
    env:
      GITHUB_CONTEXT: ${{ toJson(github) }}
      GITHUB_TOKEN: ${{ secrets.HURL_BOT_TOKEN }}
      REPO: ${{ github.repository }}
      BOT_UPDATE_BRANCH_NAME: "bot/update-actions"
    name: update-actions
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4.1.7
        with:
          ref: master
          token: ${{ secrets.HURL_BOT_TOKEN }}

      - name: Actions update
        run: |
          UPDATE_ACTIONS_OUTPUT="/tmp/update.output"
          echo "UPDATE_ACTIONS_OUTPUT=${UPDATE_ACTIONS_OUTPUT}" | tee -a "${GITHUB_ENV}"
          .github/workflows/bin/update_workflow_actions.sh --github-token $GITHUB_TOKEN 2>&1 | tee -a "${UPDATE_ACTIONS_OUTPUT}" && actions_update_exit_code=0 || actions_update_exit_code=$?
          cat "${UPDATE_ACTIONS_OUTPUT}"
          if [ ${actions_update_exit_code} -eq 0 ] ; then
            UPDATED_ACTIONS_COUNT=$(grep -cE "updated to" "${UPDATE_ACTIONS_OUTPUT}" || true)
            echo "UPDATED_ACTIONS_COUNT=${UPDATED_ACTIONS_COUNT}" | tee -a "${GITHUB_ENV}"
            echo "  - ✅ Update actions succeeds with ${UPDATED_ACTIONS_COUNT} actions updated."
          else
            echo "  - ❌ A problem occurs updating actions. Please refer to ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID} logs."
            exit 1
          fi

      - name: Get actual pull request id
        run: |
          ACTUAL_PR_NUMBER=$(gh pr list --repo "${REPO}" --head "${BOT_UPDATE_BRANCH_NAME}" --state "open" --json number --jq .[].number)
          ACTUAL_PR_NUMBER=${ACTUAL_PR_NUMBER:-0}
          echo "ACTUAL_PR_NUMBER=${ACTUAL_PR_NUMBER}" | tee -a "${GITHUB_ENV}"
          if [ ${ACTUAL_PR_NUMBER} -eq 0 ] ; then
            echo "  - ✅ There is no pull request for actions update."
          else
            echo "  - ✅ Actual pull request number is ${ACTUAL_PR_NUMBER}."
          fi

      - name: Close actual pull request
        if: env.ACTUAL_PR_NUMBER != 0
        run: |
          if [ ${UPDATED_ACTIONS_COUNT} -eq 0 ] ; then
            comment="✅ Pull request n°${ACTUAL_PR_NUMBER} closed because actions are up to date on master branch."
          else
            comment="✅ Pull request n°${ACTUAL_PR_NUMBER} closed before opening new one with new updated actions list."
          fi
          gh pr close "${ACTUAL_PR_NUMBER}" --comment "${comment}" --delete-branch && gh_exit_code=0 || gh_exit_code=$?
          if [ ${gh_exit_code} -eq 0 ] ; then
            echo "  - ${comment}"
          else
            comment="❌ A problem occurs when bot attempts to close PR n°${ACTUAL_PR_NUMBER}."
            gh pr comment "${ACTUAL_PR_NUMBER}" --body "${comment} Please refer to ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID} logs."
            echo "  - ${comment}"
            exit 1
          fi

      - name: Init git bot context
        uses: crazy-max/ghaction-import-gpg@v6.1.0
        with:
          gpg_private_key: ${{ secrets.HURL_BOT_GPG_PRIVATE_KEY }}
          passphrase: ${{ secrets.HURL_BOT_GPG_PRIVATE_KEY_PASSPHRASE }}
          git_committer_name: "hurl-bot"
          git_committer_email: "bot@hurl.dev"
          git_user_signingkey: true
          git_commit_gpgsign: true

      - name: Push updates to branch
        if: env.UPDATED_ACTIONS_COUNT != 0
        run: |
          git checkout -b "${BOT_UPDATE_BRANCH_NAME}"
          git commit -am "Update actions"
          git push --set-upstream origin "${BOT_UPDATE_BRANCH_NAME}" && git_exit_code=0 || git_exit_code=$?
          if [ ${git_exit_code} -eq 0 ] ; then
            echo "  - ✅ push actions update to ${BOT_UPDATE_BRANCH_NAME} succeeds."
          else
            echo "  - ❌ A problem occurs when attempting to push actions update to origin/${BOT_UPDATE_BRANCH_NAME}."
            exit 1
          fi
          branch_exists=$(git ls-remote | (grep -c "${BOT_UPDATE_BRANCH_NAME}" || true))
          if [ ${branch_exists} -eq 1 ] ; then
            echo "  - ✅ The origin/${BOT_UPDATE_BRANCH_NAME} now branch exists on remote."
          else
            echo "  - ❌ Git push command succeeds but origin/${BOT_UPDATE_BRANCH_NAME} still does not exist on remote."
            exit 1
          fi

      - name: Create new pull request
        if: env.UPDATED_ACTIONS_COUNT != 0
        run: |
          GITHUB_TOKEN=${{ secrets.HURL_BOT_TOKEN }}
          gh pr create --fill --base master --head "${BOT_UPDATE_BRANCH_NAME}" && gh_exit_code=0 || gh_exit_code=$?
          if [ ${gh_exit_code} -eq 0 ] ; then
            NEW_PR_NUMBER=$(gh pr list --repo "${REPO}" --head "${BOT_UPDATE_BRANCH_NAME}" --state "open" --json number --jq .[].number)
            echo "  - ✅ Creation of pull request n°${NEW_PR_NUMBER} succeeds."
          else
            echo "  - ❌ A problem occurs when attempting to create new pull request."
            exit 1
          fi
          sed -i -r "s/\x1B\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g" "${UPDATE_ACTIONS_OUTPUT}"
          pr_comment=$(grep -v "newest" "${UPDATE_ACTIONS_OUTPUT}" || true)
          gh pr comment "${NEW_PR_NUMBER}" --body "${pr_comment}" && gh_exit_code=0 || gh_exit_code=$?
          if [ ${gh_exit_code} -eq 0 ] ; then
            echo "  - ✅ Comment updates list to pull request n° ${NEW_PR_NUMBER} succeeds."
          else
            echo "  - ❌ A problem occurs when attempting to create updates list comment into new pull request n°${NEW_PR_NUMBER}."
            exit 1
          fi
          gh pr edit "${NEW_PR_NUMBER}" --add-label "bot,dependencies"  && gh_exit_code=0 || gh_exit_code=$?
          if [ ${gh_exit_code} -eq 0 ] ; then
            echo "  - ✅ Adding Label to pull request n° ${NEW_PR_NUMBER} succeeds."
          else
            echo "  - ❌ A problem occurs when attempting to add labels into new pull request n°${NEW_PR_NUMBER}."
            exit 1
          fi
