# Automatically pull down the required versions of windows plugins
# and bundle them up for releases. This makes staging on non-internet
# connected systems easier.
name: publish
on:
  push:
    tags:
      - 'v*.*.*'

jobs:
  release:
    name: Release
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/')
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Setup Python 3.9
        uses: actions/setup-python@v2
        with:
          python-version: "3.9"
      - name: Installing Python Poetry
        run: pip install poetry
      - name: Install and Build pwncat-cs Package
        run: |
          poetry install
          poetry build
      - name: Publish Package to TestPyPi
        run: |
          # Test that package publishing is going to work with the testpypi
          # instance first before trying to package plugins.
          poetry config pypi-token.testpypi ${{ secrets.TEST_PYPI_TOKEN }}
          poetry config repositories.testpypi https://test.pypi.org/legacy/
          poetry publish --repository testpypi
      - name: Download and Archive Plugins
        run: |
          # Have pwncat download all plugins needed
          poetry run pwncat-cs --download-plugins

          # They are stored in ~/.local/share/pwncat by default
          tar czvf pwncat-plugins.tar.gz --transform='s|.*pwncat/||' ~/.local/share/pwncat/*
      - name: Publish Package to PyPi
        run: |
          # Everything looks good, publish to pypi
          poetry config pypi-token.pypi ${{ secrets.PYPI_TOKEN }}
          poetry publish
      - name: Extract Release Body
        run: |
          # Grab tag name without the `v`
          version=$(git describe --tags --abbrev=0 | sed 's/v//')

          # build a changelog with just logs from this release
          echo "## Changelog" >> this_version_changelog.md
          cat CHANGELOG.md | sed -n '/^## \['"$version"'\]/,/^## /p' | head -n -1 | tail -n +2 >> this_version_changelog.md
          echo "[Full Changelog](https://github.com/calebstewart/pwncat/blob/v$version/CHANGELOG.md)" >> this_version_changelog.md
      - name: Publish Plugins
        uses: softprops/action-gh-release@v1
        with:
          files: "pwncat-plugins.tar.gz"
          body_path: this_version_changelog.md
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
