name: SP Builds
run-name: Build and Upload SP Packages

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

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Install Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '22'    
      - name: Checkout code
        uses: actions/checkout@v6

      - name: NPM offline setup
        shell: bash
        run: |
          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

      #Собираем Kernel чтобы свежие файлы попали в папку out
      - name: Build the application
        run: npm run kernel:linux

      - name: Install ZIP in Docker container
        run: |
          apt-get update
          apt-get install -y zip

      #Собираем сервисные пакеты для всех платформ  
      - name: Build SP
        shell: bash
        run: |
          chmod +x "$GITHUB_WORKSPACE/build-packs.sh"
          sh "$GITHUB_WORKSPACE/build-packs.sh"
      #Загружаем на удаленный сервер по SSH используя scp и пароль из секретов
      #Загружаем из двух папок dist/builds/darwin/x64 и dist/builds/darwin/arm64, так как electron-builder может создавать разные файлы для разных архитектур
      # - name: Upload to SSH
      #   shell: bash
      #   run: |
      #     chmod +x "$GITHUB_WORKSPACE/.gitea/workflows/sshupload.sh"
      #     sh "$GITHUB_WORKSPACE/.gitea/workflows/sshupload.sh" \
      #       -l "$GITHUB_WORKSPACE/packs/*" \
      #       -r "${{ secrets.SDU_SSH_PACKS }}" \
      #       -s "${{ secrets.SDU_SSH_HOST }}" \
      #       -u "${{ secrets.SDU_SSH_USERNAME }}" \
      #       -p '${{ secrets.SDU_SSH_PASSWORD }}'

      - name: Check SP
        shell: bash
        run: |
          echo "=== Workspace ==="
          pwd
          ls -la
          echo "=== Packs ==="
          find packs -maxdepth 3 -type f 2>/dev/null || true
          test -n "$(find packs -type f -print -quit 2>/dev/null)" || { echo "packs is empty"; exit 1; }

      - name: Clean files before upload
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.SDU_SSH_HOST }}
          username: ${{ secrets.SDU_SSH_USERNAME }}
          password: ${{ secrets.SDU_SSH_PASSWORD }}
          port: 22
          script: |
            mkdir -p "${{ secrets.SDU_SSH_PACKS }}"
            find "${{ secrets.SDU_SSH_PACKS }}" -mindepth 1 -type f -delete

      - 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: "packs/*"
          target: "${{ secrets.SDU_SSH_PACKS }}"
          strip_components: 1
          rm: false