name: Linux Kernel Build
run-name: Build and Upload Linux Kernel

on:
  workflow_dispatch:
  push:
    branches:
      - main
    paths:
      - 'lib/**'

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - arch: x64
            out_dir: x86_64
          - arch: arm64
            out_dir: arm64

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Install Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '22'

      - name: Install npm dependencies
        run: npm install --no-audit --no-fund

      - name: Debug ARCH
        run: |
          echo "arch=${{ matrix.arch }}"
          echo "out_dir=${{ matrix.out_dir }}"

      - name: Build the application
        run: |
          mkdir -p dist/builds/linux/x64
          mkdir -p dist/builds/linux/${{ matrix.out_dir }}
          npx electron-vite build
          npx electron-builder --linux --$ARCH

      - name: Check if files exist
        run: |
          echo "=== Checking dist structure ==="
          find dist/builds/linux/${{ matrix.out_dir }} -type f -name "*.AppImage" 2>/dev/null || echo "No AppImage files found"
          ls -la dist/builds/linux/${{ matrix.out_dir }}/ 2>/dev/null || echo "arch folder not found"

      - name: Upload to SSH using SCP
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.SDU_SSH_HOST }}
          username: ${{ secrets.SDU_SSH_USERNAME }}
          password: ${{ secrets.SDU_SSH_PASSWORD }}
          port: 22
          source: dist/builds/linux/${{ matrix.out_dir }}/Rosetta-*.AppImage
          target: ${{ secrets.SDU_SSH_KERNEL }}/linux/${{ matrix.arch }}
          strip_components: 4
          rm: true