---
name: Build and push release
on:
  release:
    types:
      - published
  workflow_dispatch:
    inputs:
      tag:
        description: "Tag à utiliser (ex: v1.2.3)"
        required: true
        type: string

permissions:
  contents: write

env:
  TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.event.release.tag_name }}

jobs:
  release-crate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}

      - uses: cachix/install-nix-action@v31
        with:
          github_access_token: ${{ secrets.GITHUB_TOKEN }}

      - uses: cachix/cachix-action@v16
        with:
          name: nix-community

      - uses: Swatinem/rust-cache@v2
        with:
          shared-key: build

      - run: nix develop --command cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}

  build-raspbian:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}

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

      - uses: cachix/install-nix-action@v31
        with:
          github_access_token: ${{ secrets.GITHUB_TOKEN }}

      - uses: cachix/cachix-action@v16
        with:
          name: nix-community

      - uses: Swatinem/rust-cache@v2
        with:
          shared-key: build

      - run: nix develop --command just debian-armv6

      - name: Upload release assets
        env:
          TAG: ${{ env.TAG }}
          GH_TOKEN: ${{ github.token }}
        run: |
          VERSION=${TAG#v}
          gh release upload "${TAG}" \
            "target/arm-unknown-linux-gnueabihf/debian/memocadre_${VERSION}-1_armhf.deb#memocadre_raspbian.deb" \
            "target/arm-unknown-linux-gnueabihf/release/memocadre#memocadre_raspbian"
