name: Mac Build

on:
  push:
    branches: [ "main" ]
    paths:
      - ".github/workflows/mac_build.yml"
      - "src/main/csharp/net/eagle0/clients/unity/**"
      - "src/main/protobuf/net/eagle0/common/**"
      - "src/main/protobuf/net/eagle0/shardok/**"
      - "src/main/protobuf/net/eagle0/eagle/api/**"
      - "src/main/protobuf/net/eagle0/eagle/common/**"
      - "src/main/protobuf/net/eagle0/eagle/views/**"
      - "src/main/go/net/eagle0/build/mac_build_handler/**"
      - "scripts/build_protos.sh"
      - "scripts/build_mac_plugin.sh"
      - "scripts/inject_sparkle.sh"
      - "scripts/codesign_mac_app.sh"
      - "scripts/notarize_submit.sh"
      - "scripts/notarize_wait.sh"
      - "ci/github_actions/build_mac.sh"
      - "ci/github_actions/build_unity_mac.sh"
      - "ci/github_actions/upload_addressables.sh"
      - "ci/github_actions/ensure_unity_installed.sh"
      - "src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt"
      - "ci/mac/**"
  pull_request:
    # On PRs, only build Mac when Mac-specific files change. Shared C#/proto
    # changes are covered by the Windows build — if it passes, Mac will too.
    paths:
      - ".github/workflows/mac_build.yml"
      - "src/main/go/net/eagle0/build/mac_build_handler/**"
      - "scripts/build_mac_plugin.sh"
      - "scripts/build_sparkle_plugin.sh"
      - "src/main/objc/net/eagle0/clients/unity/sparkle/**"
      - "scripts/inject_sparkle.sh"
      - "scripts/codesign_mac_app.sh"
      - "scripts/notarize_submit.sh"
      - "scripts/notarize_wait.sh"
      - "ci/github_actions/build_mac.sh"
      - "ci/github_actions/build_unity_mac.sh"
      - "ci/mac/**"
  workflow_dispatch:
    inputs:
      skip_signing:
        description: 'Skip code signing, notarization, and deploy (build only)'
        required: false
        default: 'false'
        type: boolean

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
  contents: read
  actions: write  # Required to delete artifacts after deploy

env:
  # Runner-specific build directory to allow parallel builds on multiple runners
  EAGLE0_BUILD_DIR: /tmp/eagle0-${{ github.run_id }}
  # Runner-specific keychain to avoid conflicts when multiple runners sign simultaneously
  KEYCHAIN_NAME: build-${{ github.run_id }}.keychain

jobs:
  build-and-sign:
    runs-on: [self-hosted, macOS, unity-mac]
    outputs:
      submission_id: ${{ steps.notarize-submit.outputs.submission_id }}
      should_deploy: ${{ steps.check-deploy.outputs.should_deploy }}

    steps:
      - name: Prune stale PR refs
        run: |
          # Self-hosted runners persist .git between runs. When a PR is updated,
          # old local refs (refs/remotes/pull/*/merge) may point to commits whose
          # objects were never fetched or have been pruned. Remove these stale refs
          # before checkout to prevent "missing object" errors.
          if [ -d ".git" ]; then
            echo "Pruning stale PR refs..."
            git for-each-ref --format='%(refname)' refs/remotes/pull/ 2>/dev/null | \
              xargs -r git update-ref -d 2>/dev/null || true
          fi
      - uses: actions/checkout@v6
        with:
          lfs: false  # Fetch LFS after checkout to avoid stale ref issues
          clean: false  # Library/ persists between runs on self-hosted runners
          fetch-depth: 0  # For version numbering from git history

      - name: Clean stale files
        run: |
          git clean -ffd
          # Only clear Bee/ when C# files were added/deleted/renamed (structural
          # changes that stale the DAG). Content-only modifications are handled by
          # Bee's incremental compilation. See persist_library.sh for background.
          BEE_DIR="src/main/csharp/net/eagle0/clients/unity/eagle0/Library/Bee"
          SHA_FILE="src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_built_sha"
          if [ -f "$SHA_FILE" ] && [ -d "$BEE_DIR" ]; then
            LAST_SHA=$(cat "$SHA_FILE")
            if git diff --diff-filter=ADR --name-only "$LAST_SHA" HEAD -- '*.cs' '*.csproj' '*.asmdef' 2>/dev/null | grep -q .; then
              echo "C# files added/deleted/renamed since $LAST_SHA — clearing Bee/"
              rm -rf "$BEE_DIR"
            else
              echo "No structural C# changes since $LAST_SHA — keeping Bee/"
            fi
          else
            echo "No previous build SHA or no Bee/ — clearing Bee/ as safe default"
            rm -rf "$BEE_DIR"
          fi

      - name: Fetch LFS files
        run: ./ci/github_actions/fetch_lfs.sh

      - name: Ensure Unity version installed
        run: ./ci/github_actions/ensure_unity_installed.sh mac

      - name: Sync Bazel Xcode config
        run: ./scripts/sync_bazel_xcode.sh

      - name: Build Mac Unity
        run: ./ci/github_actions/build_unity_mac.sh "${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC"

      - name: Save build SHA for Bee/ cache invalidation
        if: success()
        run: git rev-parse HEAD > src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_built_sha

      - name: Upload Addressables to CDN
        if: success() && github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
        env:
          ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
          SECRET_KEY: ${{ secrets.SECRET_KEY }}
        run: ./ci/github_actions/upload_addressables.sh StandaloneOSX

      - name: Inject Sparkle Framework
        if: success()
        env:
          SPARKLE_EDDSA_PUBLIC_KEY: ${{ secrets.SPARKLE_EDDSA_PUBLIC_KEY }}
        run: |
          chmod +x ./scripts/inject_sparkle.sh
          ./scripts/inject_sparkle.sh "${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app"

      - name: Check if should deploy
        id: check-deploy
        run: |
          if [[ "${{ github.event_name }}" == "workflow_dispatch" && "${{ github.event.inputs.skip_signing }}" == "true" ]]; then
            echo "should_deploy=false" >> $GITHUB_OUTPUT
          elif [[ "${{ github.event_name }}" == "push" && "${{ github.ref }}" == "refs/heads/main" ]]; then
            echo "should_deploy=true" >> $GITHUB_OUTPUT
          elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
            echo "should_deploy=true" >> $GITHUB_OUTPUT
          else
            echo "should_deploy=false" >> $GITHUB_OUTPUT
          fi

      - name: Import Code Signing Certificate
        if: success() && steps.check-deploy.outputs.should_deploy == 'true'
        env:
          MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }}
          MACOS_CERTIFICATE_PWD: ${{ secrets.MACOS_CERTIFICATE_PWD }}
        run: |
          # Generate random keychain password (only used within this workflow run)
          KEYCHAIN_PASSWORD=$(openssl rand -base64 32)
          echo "KEYCHAIN_PASSWORD=$KEYCHAIN_PASSWORD" >> $GITHUB_ENV

          # Decode certificate
          echo "$MACOS_CERTIFICATE" | base64 --decode > certificate.p12

          # Delete any existing keychain from previous runs
          security delete-keychain "$KEYCHAIN_NAME" 2>/dev/null || true

          # Create temporary keychain
          security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_NAME"
          security default-keychain -s "$KEYCHAIN_NAME"
          security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_NAME"

          # Import certificate
          echo "=== Importing certificate ==="
          security import certificate.p12 -k "$KEYCHAIN_NAME" -P "$MACOS_CERTIFICATE_PWD" -T /usr/bin/codesign -T /usr/bin/security

          # Allow codesign to access keychain
          echo "=== Setting key partition list ==="
          security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_NAME"

          # Add keychain to search list (required for codesign to find certificates)
          echo "=== Adding keychain to search list ==="
          security list-keychains -d user -s "$KEYCHAIN_NAME" login.keychain

          # Debug: Check what's in the keychain after import
          echo "=== Debug: Identities in build keychain ==="
          KEYCHAIN_PATH="$HOME/Library/Keychains/$KEYCHAIN_NAME-db"
          security find-identity -v -p codesigning "$KEYCHAIN_PATH" || true
          echo "=== Debug: All available identities ==="
          security find-identity -v -p codesigning || true

          # Clean up
          rm certificate.p12

      - name: Code Sign App
        if: success() && steps.check-deploy.outputs.should_deploy == 'true'
        env:
          SIGNING_IDENTITY: ${{ secrets.SIGNING_IDENTITY }}
        run: |
          chmod +x ./scripts/codesign_mac_app.sh
          ./scripts/codesign_mac_app.sh "${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app" "ci/mac/eagle0.entitlements"

      - name: Submit for Notarization
        id: notarize-submit
        if: success() && steps.check-deploy.outputs.should_deploy == 'true'
        env:
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APP_SPECIFIC_PASSWORD: ${{ secrets.APP_SPECIFIC_PASSWORD }}
          TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
        run: |
          chmod +x ./scripts/notarize_submit.sh
          ./scripts/notarize_submit.sh "${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app" >> $GITHUB_OUTPUT

      - name: Cleanup Keychain
        if: always()
        run: |
          security delete-keychain "$KEYCHAIN_NAME" 2>/dev/null || true

      - name: Zip signed app for artifact
        if: success() && steps.check-deploy.outputs.should_deploy == 'true'
        run: |
          cd ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
          ditto -c -k --keepParent eagle0.app eagle0.app.zip

      - name: Upload signed app
        if: success() && steps.check-deploy.outputs.should_deploy == 'true'
        uses: actions/upload-artifact@v7
        with:
          name: signed-mac-app-${{ github.run_id }}
          path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app.zip
          retention-days: 1

      - name: Archive Build Log
        if: success() || failure()
        uses: actions/upload-artifact@v7
        with:
          name: editor_mac.log
          path: ${{ env.EAGLE0_BUILD_DIR }}/editor_mac.log
          retention-days: 3
      - name: Cleanup build directory
        if: always()
        run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"

  wait-notarization:
    needs: build-and-sign
    if: needs.build-and-sign.outputs.should_deploy == 'true'
    runs-on: [self-hosted, macOS, notarize]

    steps:
      - uses: actions/checkout@v6
        with:
          sparse-checkout: scripts

      - name: Clean download directory
        run: rm -rf ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC

      - name: Download signed app
        uses: actions/download-artifact@v8
        with:
          name: signed-mac-app-${{ github.run_id }}
          path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC

      - name: Unzip signed app
        run: |
          cd ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
          ditto -x -k eagle0.app.zip .
          rm eagle0.app.zip
          ls -la ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app/

      - name: Wait for Notarization and Staple
        env:
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APP_SPECIFIC_PASSWORD: ${{ secrets.APP_SPECIFIC_PASSWORD }}
          TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
        run: |
          chmod +x ./scripts/notarize_wait.sh
          ./scripts/notarize_wait.sh "${{ needs.build-and-sign.outputs.submission_id }}" "${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app"

      - name: Zip notarized app for artifact
        run: |
          cd ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
          rm -f eagle0.app.zip
          ditto -c -k --keepParent eagle0.app eagle0.app.zip

      - name: Upload notarized app
        uses: actions/upload-artifact@v7
        with:
          name: notarized-mac-app-${{ github.run_id }}
          path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app.zip
          retention-days: 1
      - name: Cleanup build directory
        if: always()
        run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"

  deploy:
    needs: [build-and-sign, wait-notarization]
    if: needs.build-and-sign.outputs.should_deploy == 'true'
    runs-on: [self-hosted, macOS, unity-mac]
    outputs:
      deployed_version: ${{ steps.deploy-mac.outputs.deployed_version }}

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0  # For version numbering

      - name: Clean download directory
        run: rm -rf ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC

      - name: Download notarized app
        uses: actions/download-artifact@v8
        with:
          name: notarized-mac-app-${{ github.run_id }}
          path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC

      - name: Unzip notarized app
        run: |
          cd ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
          ditto -x -k eagle0.app.zip .
          rm eagle0.app.zip

      - name: Sync Bazel Xcode config
        run: ./scripts/sync_bazel_xcode.sh

      - name: Deploy Mac Build
        id: deploy-mac
        env:
          ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
          SECRET_KEY: ${{ secrets.SECRET_KEY }}
          SPARKLE_EDDSA_PRIVATE_KEY: ${{ secrets.SPARKLE_EDDSA_PRIVATE_KEY }}
        run: |
          # Write private key to temp file for signing
          SPARKLE_PRIVATE_KEY_PATH="/tmp/sparkle_private_key"
          echo "$SPARKLE_EDDSA_PRIVATE_KEY" > "$SPARKLE_PRIVATE_KEY_PATH"
          chmod 600 "$SPARKLE_PRIVATE_KEY_PATH"

          # Install dmgbuild (creates .DS_Store programmatically, no AppleScript needed)
          pip3 install dmgbuild

          # Background image for styled DMG
          BACKGROUND_PATH="$(pwd)/ci/mac/dmg/background.png"

          # Read version from the built app's Info.plist to ensure appcast matches the actual app
          APP_PATH="${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app"
          BUILD_NUMBER=$(/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "$APP_PATH/Contents/Info.plist")
          VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$APP_PATH/Contents/Info.plist")

          bazel run //src/main/go/net/eagle0/build/mac_build_handler:mac_build_handler -- \
            "${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app" \
            "$VERSION" \
            "$BUILD_NUMBER" \
            "$BACKGROUND_PATH" \
            "$SPARKLE_PRIVATE_KEY_PATH"

          rm "$SPARKLE_PRIVATE_KEY_PATH"

          echo "deployed_version=$VERSION" >> $GITHUB_OUTPUT

      # Artifact cleanup is handled by the cleanup job on ubuntu-latest
      - name: Cleanup build directory
        if: always()
        run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"

  notify-mac:
    needs: deploy
    if: needs.deploy.outputs.deployed_version != ''
    runs-on: ubuntu-latest
    steps:
      - name: Purge CDN cache and notify clients
        env:
          NOTIFY_SECRET: ${{ secrets.EAGLE_NOTIFY_SECRET }}
          DO_CDN_PAT: ${{ secrets.DO_CDN_PAT }}
        run: |
          # Purge CDN cache so clients get the latest files immediately
          curl -s -X DELETE "https://api.digitalocean.com/v2/cdn/endpoints/8c98df29-6f0c-4704-8e82-ca40a2b81aa8/cache" \
            -H "Authorization: Bearer $DO_CDN_PAT" \
            -H "Content-Type: application/json" \
            -d '{"files": ["mac/*", "addressables/StandaloneOSX/*"]}' \
            --fail || echo "Warning: CDN purge failed (non-fatal)"

          curl -X POST "https://admin.eagle0.net/notify-update?platform=mac&version=${{ needs.deploy.outputs.deployed_version }}&required=false" \
            -H "X-Notify-Secret: $NOTIFY_SECRET" \
            --fail --silent --show-error || echo "Warning: Failed to notify clients (non-fatal)"

  # Cleanup job runs regardless of success/failure to prevent artifact accumulation
  cleanup:
    needs: [build-and-sign, wait-notarization, deploy, notify-mac]
    if: always()
    runs-on: ubuntu-latest

    steps:
      - name: Delete this run's Mac app artifacts
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          # Delete this run's artifacts (names include run ID to avoid conflicts)
          for artifact_name in signed-mac-app-${{ github.run_id }} notarized-mac-app-${{ github.run_id }}; do
            echo "Deleting artifact: $artifact_name"
            artifact_id=$(gh api "repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts" \
              -q ".artifacts[] | select(.name == \"$artifact_name\") | .id")
            if [ -n "$artifact_id" ]; then
              echo "Deleting artifact ID: $artifact_id"
              gh api -X DELETE "repos/${{ github.repository }}/actions/artifacts/$artifact_id" || true
            fi
          done
          echo "Cleanup complete"
