name: Build and Publish Snap

on:
  push:
    tags:
      - '*'
  workflow_dispatch:

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Fetch tags
        run: git fetch --force --tags

      - name: Install Snapcraft
        run: sudo snap install --classic snapcraft

      - name: Build snap
        id: build
        run: |
          sudo snapcraft pack --destructive-mode
          SNAP_FILE=$(ls *.snap)
          echo "snap=$SNAP_FILE" >> "$GITHUB_OUTPUT"

      - name: Upload snap artifact
        uses: actions/upload-artifact@v7
        with:
          name: snap
          path: ${{ steps.build.outputs.snap }}

      - name: Publish to Snapcraft Store
        if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch'
        uses: snapcore/action-publish@v1
        env:
          SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
        with:
          snap: ${{ steps.build.outputs.snap }}
          release: stable
