name: Linux packages

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

permissions:
  contents: read

jobs:
  package:
    name: ${{ matrix.arch }} AppImage and DEB
    strategy:
      fail-fast: false
      matrix:
        include:
          - arch: x64
            runner: ubuntu-24.04
            deb_arch: amd64
            elf_machine: x86-64
          - arch: arm64
            runner: ubuntu-24.04-arm
            deb_arch: arm64
            elf_machine: aarch64
    runs-on: ${{ matrix.runner }}
    timeout-minutes: 60

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 24
          cache: npm

      - name: Install packaging tools
        run: |
          sudo apt-get update
          sudo apt-get install --yes file ruby ruby-dev build-essential
          sudo gem install fpm --no-document

      - name: Install dependencies
        run: npm ci

      - name: Run validators
        run: |
          npm test
          npm run typecheck
          npm run lint

      - name: Build Linux packages
        run: npm run dist:linux:${{ matrix.arch }}

      - name: Verify package architecture and runtimes
        shell: bash
        run: |
          set -euo pipefail
          appimage="$(find dist -maxdepth 1 -type f -name '*.AppImage' -print -quit)"
          deb="$(find dist -maxdepth 1 -type f -name '*.deb' -print -quit)"
          unpacked="$(find dist -maxdepth 1 -type d -name 'linux*unpacked' -print -quit)"
          test -n "$appimage"
          test -n "$deb"
          test -n "$unpacked"
          file "$unpacked/goodbuddy" | grep -qi '${{ matrix.elf_machine }}'
          file "$unpacked/resources/runtimes/opencode/opencode" | grep -qi '${{ matrix.elf_machine }}'
          test -f "$unpacked/resources/runtimes/continue/dist/index.js"
          "$unpacked/resources/runtimes/opencode/opencode" --version
          dpkg-deb --field "$deb" Architecture | grep -qx '${{ matrix.deb_arch }}'
          dpkg-deb --contents "$deb" | grep -q 'runtimes/opencode/opencode'
          chmod +x "$appimage"
          "$appimage" --appimage-extract >/dev/null
          test -f squashfs-root/resources/runtimes/continue/dist/index.js

      - name: Upload packages
        uses: actions/upload-artifact@v4
        with:
          name: goodbuddy-linux-${{ matrix.arch }}
          path: |
            dist/*.AppImage
            dist/*.deb
            dist/*.blockmap
          if-no-files-found: error
