name: pypi-release

on:
  release:
    types: [published]

env:
  RELEASE_TAG: ${{ github.event.release.tag_name }}
  GITHUB_BRANCH: master

jobs:
  release-prowler-job:
    runs-on: ubuntu-latest
    env:
      POETRY_VIRTUALENVS_CREATE: "false"
    name: Release Prowler to PyPI
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v3
        with:
          ref: ${{ env.GITHUB_BRANCH }}
      - name: Install dependencies
        run: |
          pipx install poetry
          pipx inject poetry poetry-bumpversion
      - name: setup python
        uses: actions/setup-python@v4
        with:
          python-version: 3.9
          cache: 'poetry'
      - name: Change version and Build package
        run: |
          poetry version ${{ env.RELEASE_TAG }}
          git config user.name "github-actions"
          git config user.email "<noreply@github.com>"
          git add prowler/config/config.py pyproject.toml
          git commit -m "chore(release): ${{ env.RELEASE_TAG }}" --no-verify
          git tag -fa ${{ env.RELEASE_TAG }} -m "chore(release): ${{ env.RELEASE_TAG }}"
          git push -f origin ${{ env.RELEASE_TAG }}
          poetry build
      - name: Publish prowler package to PyPI
        run: |
          poetry config pypi-token.pypi ${{ secrets.PYPI_API_TOKEN }}
          poetry publish
      # Create pull request with new version
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v4
        with:
          token: ${{ secrets.PROWLER_ACCESS_TOKEN }}
          commit-message: "chore(release): update Prowler Version to ${{ env.RELEASE_TAG }}."
          branch: release-${{ env.RELEASE_TAG }}
          labels: "status/waiting-for-revision, severity/low"
          title: "chore(release): update Prowler Version to ${{ env.RELEASE_TAG }}"
          body: |
            ### Description

            This PR updates Prowler Version to ${{ env.RELEASE_TAG }}.

            ### License

            By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
      - name: Replicate PyPi Package
        run: |
          rm -rf ./dist && rm -rf ./build && rm -rf prowler.egg-info
          pip install toml
          python util/replicate_pypi_package.py
          poetry build
      - name: Publish prowler-cloud package to PyPI
        run: |
          poetry config pypi-token.pypi ${{ secrets.PYPI_API_TOKEN }}
          poetry publish
      # Create pull request to github.com/Homebrew/homebrew-core to update prowler formula
      - name: Bump Homebrew formula
        uses: mislav/bump-homebrew-formula-action@v2
        with:
          formula-name: prowler
          base-branch: release-${{ env.RELEASE_TAG }}
        env:
          COMMITTER_TOKEN: ${{ secrets.PROWLER_ACCESS_TOKEN }}
