# .github/workflows/build.yml
name: Build and Package Desktop App

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [macos-latest, windows-latest]
        arch: [x64, arm64]

    steps:
      - uses: actions/checkout@v3

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.12'

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'

      - name: Install Python dependencies
        run: |
          python -m pip install --upgrade pip
          cd server
          pip install -r requirements.txt

      - name: Install Node.js dependencies
        run: |
          npm install --force
          cd react
          npm install --force

      - name: Build Python app
        run: |
          cd server
          pyinstaller main.spec

      - name: Build React app
        env:
          VITE_UMAMI_WEBSITE_ID: ${{ secrets.UMAMI_WEBSITE_ID }}
          VITE_PUBLIC_POSTHOG_KEY: ${{ secrets.VITE_PUBLIC_POSTHOG_KEY }}
          VITE_PUBLIC_POSTHOG_HOST: ${{ secrets.VITE_PUBLIC_POSTHOG_HOST }}
        run: |
          cd react
          npx vite build

      - name: Install Apple certificate
        if: matrix.os == 'macos-latest'
        run: |
          echo "$CERTIFICATE_P12" | base64 --decode > certificate.p12
          security create-keychain -p "" build.keychain
          security default-keychain -s build.keychain
          security unlock-keychain -p "" build.keychain
          security import certificate.p12 -k build.keychain -P "$CERTIFICATE_PASSWORD" -T /usr/bin/codesign
          security set-key-partition-list -S apple-tool:,apple: -s -k "" build.keychain
        env:
          CERTIFICATE_P12: ${{ secrets.CERTIFICATE_P12 }}
          CERTIFICATE_PASSWORD: ${{ secrets.CERTIFICATE_PASSWORD }}

      - name: Set env for mac signing
        if: matrix.os == 'macos-latest'
        run: echo "CSC_LINK=certificate.p12" >> $GITHUB_ENV && echo "CSC_KEY_PASSWORD=${{ secrets.CERTIFICATE_PASSWORD }}" >> $GITHUB_ENV

      - name: Build and Package Electron app
        run: |
          npx electron-builder --${{ matrix.os == 'macos-latest' && 'mac' || 'win' }} --publish always
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_APP_PASSWORD: ${{ secrets.APPLE_APP_PASSWORD }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_PASSWORD }} # Map the existing password
          TEAM_ID: ${{ secrets.TEAM_ID }}

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: desktop-app-${{ matrix.os }}-${{ matrix.arch }}-${{ github.run_id }}
          path: dist/
          overwrite: true
