name: Cloudsmith

on:
  workflow_dispatch:
    inputs:
      build_number:
        description: "The build number."
        required: true
        type: string
      type:
        description: "Type: wip-20"
        required: true
        type: choice
        options:
          - wip-20

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        include:
          - distro: ubuntu
            codename: noble
          - distro: debian
            codename: trixie

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Deploy package
        run: |
          shopt -s nullglob
          if [[ "${{ inputs.build_number }}" == "auto" ]]; then
            BUILD_NUMBER="${{ github.run_number }}"
          else
            BUILD_NUMBER="${{ inputs.build_number }}"
          fi
          cd .github/ppa
          ./build.sh --type cloudsmith --build-number "${BUILD_NUMBER}" "${{ inputs.type }}" "${{ matrix.codename }}" create sync changes build
          rm -f *dbgsym*.deb

      - name: Upload built package artifact for ${{ matrix.codename }}
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.distro }}-${{ matrix.codename }}
          path: .github/ppa/*.deb

  publish:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: ./deb-packages
          merge-multiple: false

      - name: Install Cloudsmith CLI
        uses: cloudsmith-io/cloudsmith-cli-action@master
        with:
          api-key: ${{ secrets.CLOUDSMITH_API_KEY }}

      - name: Publish all .deb packages to Cloudsmith
        run: |
          find ./deb-packages -type f -name '*.deb' -print0 | while IFS= read -r -d '' debfile; do
            distro=$(basename "$(dirname "$debfile")")
            cloudsmith push deb "potassco/${{ inputs.type }}/${distro/-//}" "$debfile"
          done
