name: Build and Release

on:
  push:
    tags:
      - 'v*' # 当推送 v 开头的标签时触发，如 v1.0.0

jobs:
  build:
    name: Build on ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [windows-latest, macos-latest, ubuntu-latest]
        include:
          - os: windows-latest
            artifact_name: EasyShell-Windows
            build_cmd: npm run build && npx electron-builder --win
          - os: macos-latest
            artifact_name: EasyShell-Mac
            build_cmd: npm run build && npx electron-builder --mac
          - os: ubuntu-latest
            artifact_name: EasyShell-Linux
            build_cmd: npm run build && npx electron-builder --linux

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Generate icons
        run: npm run icons
        continue-on-error: true

      - name: Build application
        run: ${{ matrix.build_cmd }}
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.artifact_name }}
          path: |
            dist/*.exe
            dist/*.dmg
            dist/*.AppImage
            dist/*.deb
          if-no-files-found: ignore

  release:
    name: Create Release
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write

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

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Display structure of downloaded files
        run: ls -R artifacts

      - name: Get version from tag
        id: get_version
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT

      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          name: EasyShell ${{ steps.get_version.outputs.VERSION }}
          tag_name: ${{ steps.get_version.outputs.VERSION }}
          draft: false
          prerelease: false
          generate_release_notes: true
          files: |
            artifacts/**/*.exe
            artifacts/**/*.dmg
            artifacts/**/*.AppImage
            artifacts/**/*.deb
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
