name: Release Candidate

# Cuts a v1 release-candidate pre-release (e.g. v1.0.0-rc3) from the
# release/v1 stabilization branch. The rc number is computed automatically
# from existing tags. Run manually from the Actions tab.

on:
  workflow_dispatch:
    inputs:
      base_version:
        description: "Base version the rc leads up to"
        type: string
        default: "1.0.0"
      dry_run:
        description: "Compute and print the next tag without tagging or releasing"
        type: boolean
        default: false

permissions:
  contents: write # to create tags and the GitHub pre-release
  id-token: write # to sign the release

jobs:
  tag:
    runs-on: ubuntu-latest
    outputs:
      tag: ${{ steps.compute.outputs.tag }}
      prev_stable: ${{ steps.compute.outputs.prev_stable }}
    steps:
      - name: Guard branch
        if: github.ref != 'refs/heads/release/v1'
        run: |
          echo "::error::Release candidates must be cut from release/v1 (got ${{ github.ref }})."
          exit 1

      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Compute next rc tag
        id: compute
        run: |
          set -euo pipefail
          BASE="${{ inputs.base_version }}"
          git fetch --tags --force
          # Highest existing rc number for this base version, 0 if none yet.
          LATEST=$(git tag -l "v${BASE}-rc*" \
            | sed -E "s/^v${BASE}-rc//" \
            | grep -E '^[0-9]+$' \
            | sort -n | tail -1 || true)
          NEXT=$(( ${LATEST:-0} + 1 ))
          TAG="v${BASE}-rc${NEXT}"
          echo "Next release candidate: $TAG"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"

          # Last STABLE release tag (no -rc / nightly / preview). Used as the
          # changelog base so every rc's notes are cumulative since the last
          # stable — covering all prior rc changes too, not just the last rc.
          PREV_STABLE=$(git tag -l 'v*' \
            | grep -vE '\-rc|nightly|preview' \
            | sort -V | tail -1 || true)
          echo "Changelog base (last stable): ${PREV_STABLE:-<none>}"
          echo "prev_stable=$PREV_STABLE" >> "$GITHUB_OUTPUT"

      - name: Create and push tag
        if: ${{ !inputs.dry_run }}
        run: |
          set -euo pipefail
          TAG="${{ steps.compute.outputs.tag }}"
          git config user.name "Floatpane Bot"
          git config user.email "us@floatpane.com"
          git tag -a "$TAG" -m "Release candidate $TAG"
          git push origin "$TAG"

  goreleaser:
    needs: tag
    if: ${{ !inputs.dry_run }}
    runs-on: macos-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          ref: ${{ needs.tag.outputs.tag }}

      - name: Set up Go
        uses: actions/setup-go@v6
        with:
          go-version: "1.26.4"

      - name: Set up Zig
        uses: goto-bus-stop/setup-zig@v2

      - name: Set up libpcsclite for Linux cross-compilation
        run: |
          PCSC_DIR="$RUNNER_TEMP/pcsclite"
          mkdir -p "$PCSC_DIR/include" "$PCSC_DIR/lib/pkgconfig"

          # Download pcsc-lite headers from upstream
          PCSC_URL="https://raw.githubusercontent.com/LudovicRousseau/PCSC/master/src/PCSC"
          for header in winscard.h wintypes.h; do
            curl -fsSL "$PCSC_URL/$header" -o "$PCSC_DIR/include/$header"
          done
          # pcsclite.h is generated from pcsclite.h.in — download and substitute the version placeholder
          curl -fsSL "$PCSC_URL/pcsclite.h.in" -o "$PCSC_DIR/include/pcsclite.h"
          sed -i '' 's/@VERSION@/1.9.0/' "$PCSC_DIR/include/pcsclite.h"

          # Build stub library — the real libpcsclite is loaded at runtime on the user's system,
          # but the linker needs symbols to resolve during cross-compilation.
          cat > "$RUNNER_TEMP/pcsclite_stub.c" << 'STUB'
          #include <stddef.h>
          typedef long LONG;
          typedef unsigned long DWORD;
          typedef void *LPCVOID;
          typedef char *LPSTR;
          typedef const char *LPCSTR;
          typedef unsigned char *LPBYTE;
          typedef unsigned char BYTE;
          typedef LONG SCARDCONTEXT;
          typedef LONG SCARDHANDLE;
          typedef struct { DWORD dwProtocol; DWORD cbPciLength; } SCARD_IO_REQUEST;
          typedef struct { LPCSTR szReader; DWORD dwCurrentState; DWORD dwEventState; DWORD cbAtr; unsigned char rgbAtr[36]; void *pvUserData; } SCARD_READERSTATE;
          LONG SCardEstablishContext(DWORD s, LPCVOID r1, LPCVOID r2, SCARDCONTEXT *c) { return 0; }
          LONG SCardReleaseContext(SCARDCONTEXT c) { return 0; }
          LONG SCardIsValidContext(SCARDCONTEXT c) { return 0; }
          LONG SCardCancel(SCARDCONTEXT c) { return 0; }
          LONG SCardConnect(SCARDCONTEXT c, LPCSTR r, DWORD s, DWORD p, SCARDHANDLE *h, DWORD *ap) { return 0; }
          LONG SCardReconnect(SCARDHANDLE h, DWORD s, DWORD p, DWORD d, DWORD *ap) { return 0; }
          LONG SCardDisconnect(SCARDHANDLE h, DWORD d) { return 0; }
          LONG SCardBeginTransaction(SCARDHANDLE h) { return 0; }
          LONG SCardEndTransaction(SCARDHANDLE h, DWORD d) { return 0; }
          LONG SCardStatus(SCARDHANDLE h, LPSTR r, DWORD *rl, DWORD *s, DWORD *p, LPBYTE a, DWORD *al) { return 0; }
          LONG SCardTransmit(SCARDHANDLE h, const SCARD_IO_REQUEST *si, const BYTE *s, DWORD sl, SCARD_IO_REQUEST *ri, BYTE *r, DWORD *rl) { return 0; }
          LONG SCardControl(SCARDHANDLE h, DWORD c, LPCVOID i, DWORD il, void *o, DWORD ol, DWORD *br) { return 0; }
          LONG SCardGetAttrib(SCARDHANDLE h, DWORD a, LPBYTE b, DWORD *bl) { return 0; }
          LONG SCardSetAttrib(SCARDHANDLE h, DWORD a, const BYTE *b, DWORD bl) { return 0; }
          LONG SCardListReaders(SCARDCONTEXT c, LPCSTR g, LPSTR r, DWORD *rl) { return 0; }
          LONG SCardListReaderGroups(SCARDCONTEXT c, LPSTR g, DWORD *gl) { return 0; }
          LONG SCardGetStatusChange(SCARDCONTEXT c, DWORD t, SCARD_READERSTATE *s, DWORD n) { return 0; }
          LONG SCardFreeMemory(SCARDCONTEXT c, LPCVOID m) { return 0; }
          const char *pcsc_stringify_error(LONG e) { return "stub"; }
          STUB

          zig cc -c -target x86_64-linux-musl -o "$RUNNER_TEMP/pcsclite_stub_amd64.o" "$RUNNER_TEMP/pcsclite_stub.c"
          zig cc -c -target aarch64-linux-musl -o "$RUNNER_TEMP/pcsclite_stub_arm64.o" "$RUNNER_TEMP/pcsclite_stub.c"

          mkdir -p "$PCSC_DIR/lib/amd64" "$PCSC_DIR/lib/arm64"
          ar rcs "$PCSC_DIR/lib/amd64/libpcsclite.a" "$RUNNER_TEMP/pcsclite_stub_amd64.o"
          ar rcs "$PCSC_DIR/lib/arm64/libpcsclite.a" "$RUNNER_TEMP/pcsclite_stub_arm64.o"

          # Create pkg-config file — Libs will be overridden per-arch via CGO_LDFLAGS in goreleaser
          cat > "$PCSC_DIR/lib/pkgconfig/libpcsclite.pc" << EOF
          Name: libpcsclite
          Description: PC/SC Lite
          Version: 1.9.0
          Cflags: -I$PCSC_DIR/include
          Libs: -L$PCSC_DIR/lib/amd64 -lpcsclite
          EOF

          echo "PKG_CONFIG_PATH=$PCSC_DIR/lib/pkgconfig" >> $GITHUB_ENV
          echo "PCSC_DIR=$PCSC_DIR" >> $GITHUB_ENV

      - name: Get macOS SDK path
        id: macos_sdk
        run: echo "path=$(xcrun --show-sdk-path)" >> $GITHUB_OUTPUT

      - name: Run GoReleaser
        uses: goreleaser/goreleaser-action@v7
        with:
          version: latest
          args: release --clean --config .goreleaser.rc.yml
        env:
          SDK_PATH: ${{ steps.macos_sdk.outputs.path }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          # Force the changelog base to the last stable tag so rc notes are
          # cumulative across every rc since that release.
          GORELEASER_PREVIOUS_TAG: ${{ needs.tag.outputs.prev_stable }}

  snapcraft:
    needs: [tag, goreleaser]
    if: ${{ !inputs.dry_run }}
    runs-on: ${{ matrix.runner }}
    strategy:
      matrix:
        include:
          - arch: amd64
            runner: ubuntu-latest
          - arch: arm64
            runner: ubuntu-24.04-arm
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          ref: ${{ needs.tag.outputs.tag }}

      - name: Install Snapcraft and LXD
        run: |
          sudo snap install snapcraft --classic
          sudo snap install lxd
          sudo lxd init --auto
          sudo iptables -P FORWARD ACCEPT
          sudo usermod -aG lxd $USER

      - name: Build snap
        run: sg lxd -c 'snapcraft pack --use-lxd --build-for=${{ matrix.arch }}'

      - name: Upload snap to candidate channel
        env:
          SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
        run: snapcraft upload --release=candidate *.snap
