name: Publish Snap

on:
  workflow_dispatch: ~
  push:
    branches: [master, beta, nightly]
    tags: [v*]

jobs:
  build-snap:
    name: Build Snap Package (${{ matrix.architecture }})
    runs-on: ubuntu-latest
    if: ${{ !contains(github.event.head_commit.message, '[skip ci]') }}
    strategy:
      fail-fast: false
      matrix:
        architecture:
          - amd64
          - arm64
          - armhf
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      - name: Prepare
        id: prepare
        run: |
          git fetch --prune --unshallow --tags
          if [[ $GITHUB_REF == refs/tags/*-beta || $GITHUB_REF == refs/heads/beta ]]; then
            echo "RELEASE=beta" >> $GITHUB_OUTPUT
          elif [[ $GITHUB_REF == refs/tags/* || $GITHUB_REF == refs/heads/master ]]; then
            echo "RELEASE=stable" >> $GITHUB_OUTPUT
          else
            echo "RELEASE=edge" >> $GITHUB_OUTPUT
          fi

      - name: Set Up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Build Snap Package
        uses: diddlesnaps/snapcraft-multiarch-action@master
        id: build
        with:
          architecture: ${{ matrix.architecture }}

      - name: Upload Snap Package
        uses: actions/upload-artifact@v4
        with:
          name: Tautulli-snap-package-${{ matrix.architecture }}
          path: ${{ steps.build.outputs.snap }}

      - name: Review Snap Package
        uses: diddlesnaps/snapcraft-review-tools-action@master
        with:
          snap: ${{ steps.build.outputs.snap }}

      - name: Publish Snap Package
        uses: snapcore/action-publish@v1
        if: startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/nightly'
        env:
          SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAP_LOGIN }}
        with:
          snap: ${{ steps.build.outputs.snap }}
          release: ${{ steps.prepare.outputs.RELEASE }}

  discord:
    name: Discord Notification
    needs: build-snap
    if: always() && !contains(github.event.head_commit.message, '[skip ci]')
    runs-on: ubuntu-latest
    steps:
      - name: Post Status to Discord
        uses: sarisia/actions-status-discord@v1
        with:
          webhook: ${{ secrets.DISCORD_WEBHOOK }}
          status: ${{ needs.build-snap.result == 'success' && 'success' || contains(needs.*.result, 'failure') && 'failure' || 'cancelled' }}
          title: ${{ github.workflow }}
          nofail: true
