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

#Запускаем только кнопкой "Run workflow" в Actions -> Build MacOS
on:
  workflow_dispatch:
  push:
    branches:
      - main
    paths:
      - 'lib/**'  

jobs:
  build:
    runs-on: macos
    strategy:
      fail-fast: false
      matrix:
        arch: [x64, arm64]
    steps:
      - name: Checkout code
        uses: actions/checkout@v6
      
      - name: Install Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '22'

      # Кэш npm (тарифы грузятся из ~/.npm-cache на macOS)
      - name: Cache npm cache
        uses: actions/cache@v5
        with:
          path: ${{ env.HOME }}/.npm-cache
          key: ${{ runner.os }}-npm-${{ hashFiles('**/package.json') }}
          restore-keys: |
            ${{ runner.os }}-npm-
          if-no-files-found: ignore

      # Кэш для electron-builder
      - name: Cache electron-builder
        uses: actions/cache@v5
        with:
          path: |
            ${{ env.HOME }}/Library/Caches/electron-builder
            ${{ env.HOME }}/Library/Caches/electron
          key: ${{ runner.os }}-electron-builder-${{ hashFiles('**/electron-builder.yml') }}
          restore-keys: |
            ${{ runner.os }}-electron-builder-
          if-no-files-found: ignore

      - name: NPM offline setup
        shell: bash
        run: |
          mkdir -p dist/builds/darwin/arm64 dist/builds/darwin/x64 
          npm config set cache "$HOME/.npm-cache" --global
          npm config set prefer-offline true --global

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

      - name: Build the application
        run: |
          npx electron-vite build
          npx electron-builder --mac --${{ matrix.arch }}

      - name: Check if files exist
        run: |
          echo "=== Checking dist structure ==="
          find dist/builds/darwin/${{ matrix.arch }} -type f -name "*.pkg" 2>/dev/null || echo "No PKG files found"
          ls -la dist/builds/darwin/${{ matrix.arch }}/ 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/darwin/${{ matrix.arch }}/Rosetta-*.pkg"
          target: "${{ secrets.SDU_SSH_KERNEL }}/darwin/${{ matrix.arch }}"
          strip_components: 4
          rm: true