name: rnx-build
on:
  workflow_dispatch:
    inputs:
      architecture:
        description: "Supported architectures are `arm64`, `x64`"
        required: true
        default: "x64"
      deviceType:
        description: "Supported device types are `device`, `emulator`, `simulator`"
        required: true
        default: "simulator"
      distribution:
        description: "Distribution config string, e.g. `local` or `firebase:<appId>`"
        required: true
        default: "local"
      packageManager:
        description: "Binary name of the package manager used in the current repo"
        required: true
        default: "yarn"
      platform:
        description: "Supported platforms are `android`, `ios`, `macos`, `windows`"
        required: true
      projectRoot:
        description: "Root of the project"
        required: true
      scheme:
        description: "The workspace scheme to build (iOS and macOS only)"
        default: "ReactTestApp"
jobs:
  build-android:
    name: "Build Android"
    if: ${{ github.event.inputs.platform == 'android' }}
    runs-on: ubuntu-20.04
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Set up JDK
        uses: actions/setup-java@v3.6.0
        with:
          distribution: temurin
          java-version: 11
      - name: Set up Node 16
        uses: actions/setup-node@v3.5.1
        with:
          node-version: 16
      - name: Install npm dependencies
        run: ${{ github.event.inputs.packageManager }} install
      - name: Build Android app
        uses: gradle/gradle-build-action@v2.3.3
        with:
          gradle-version: wrapper
          arguments: --no-daemon clean assembleDebug
          build-root-directory: ${{ github.event.inputs.projectRoot }}/android
      - name: Upload build artifact
        uses: actions/upload-artifact@v3
        with:
          name: android-artifact
          path: ${{ github.event.inputs.projectRoot }}/android/app/build/outputs/apk/debug/app-debug.apk
          if-no-files-found: error
          retention-days: 14
  build-ios:
    name: "Build iOS"
    if: ${{ github.event.inputs.platform == 'ios' }}
    runs-on: macos-12
    env:
      CERTIFICATE_FILE: build-certificate.p12
      KEYCHAIN_FILE: app-signing.keychain-db
      PROVISION_PATH: "Library/MobileDevice/Provisioning Profiles/Provisioning_Profile.mobileprovision"
      XCARCHIVE_FILE: app.xcarchive
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Set up Node 16
        uses: actions/setup-node@v3.5.1
        with:
          node-version: 16
      - name: Install npm dependencies
        run: ${{ github.event.inputs.packageManager }} install
      - name: Install Pods
        run: pod install --project-directory=ios --verbose
        working-directory: ${{ github.event.inputs.projectRoot }}
      - name: Install Apple signing certificate and provisioning profile
        if: ${{ github.event.inputs.deviceType == 'device' }}
        env:
          BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
          BUILD_PROVISION_PROFILE_BASE64: ${{ secrets.BUILD_PROVISION_PROFILE_BASE64 }}
          KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
          P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
        run: npx --prefix . rnx-build-apple install-certificate
      - name: Build iOS app
        run: npx --prefix . rnx-build-apple build-ios --scheme ${{ github.event.inputs.scheme }} --device-type ${{ github.event.inputs.deviceType }} --archs ${{ github.event.inputs.architecture }}
        working-directory: ${{ github.event.inputs.projectRoot }}/ios
      - name: Remove Apple signing certificate and provisioning profile
        # Always run this job step, even if previous ones fail. See also
        # https://docs.github.com/en/actions/deployment/deploying-xcode-applications/installing-an-apple-certificate-on-macos-runners-for-xcode-development#required-clean-up-on-self-hosted-runners
        if: ${{ always() && github.event.inputs.deviceType == 'device' }}
        run: npx --prefix . rnx-build-apple uninstall-certificate
      - name: Prepare build artifact
        id: prepare-build-artifact
        run: |
          if [[ ${{ github.event.inputs.distribution }} == 'local' ]]; then
            app=$(find ${XCARCHIVE_FILE}/Products/Applications -maxdepth 1 -name '*.app' -type d | head -1)
            npx --prefix . rnx-build-apple archive ios-artifact.tar "${app}"
            echo 'filename=ios-artifact.tar' >> $GITHUB_OUTPUT
          else
            xcodebuild -exportArchive -archivePath ${XCARCHIVE_FILE} -exportPath export -exportOptionsPlist ExportOptions.plist 2>&1
            ipa=$(find export -maxdepth 1 -name '*.ipa' -type d | head -1)
            echo "filename=${ipa}" >> $GITHUB_OUTPUT
          fi
        working-directory: ${{ github.event.inputs.projectRoot }}/ios
      - name: Upload build artifact
        uses: actions/upload-artifact@v3
        with:
          name: ios-artifact
          path: ${{ github.event.inputs.projectRoot }}/ios/${{ steps.prepare-build-artifact.outputs.filename }}
          if-no-files-found: error
          retention-days: 14
  build-macos:
    name: "Build macOS"
    if: ${{ github.event.inputs.platform == 'macos' }}
    runs-on: macos-12
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Set up Node 16
        uses: actions/setup-node@v3.5.1
        with:
          node-version: 16
      - name: Install npm dependencies
        run: ${{ github.event.inputs.packageManager }} install
      - name: Install Pods
        run: pod install --project-directory=macos --verbose
        working-directory: ${{ github.event.inputs.projectRoot }}
      - name: Build macOS app
        run: npx --prefix . rnx-build-apple build-macos --scheme ${{ github.event.inputs.scheme }}
        working-directory: ${{ github.event.inputs.projectRoot }}/macos
      - name: Prepare build artifact
        run: |
          output_path=DerivedData/Build/Products
          app=$(find ${output_path} -maxdepth 2 -name '*.app' -type d | head -1)
          npx --prefix . rnx-build-apple archive macos-artifact.tar "${app}"
        working-directory: ${{ github.event.inputs.projectRoot }}/macos
      - name: Upload build artifact
        uses: actions/upload-artifact@v3
        with:
          name: macos-artifact
          path: ${{ github.event.inputs.projectRoot }}/macos/macos-artifact.tar
          if-no-files-found: error
          retention-days: 14
  build-windows:
    name: "Build Windows"
    if: ${{ github.event.inputs.platform == 'windows' }}
    runs-on: windows-2022
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Set up MSBuild
        uses: microsoft/setup-msbuild@v1.1
      - name: Set up Node 16
        uses: actions/setup-node@v3.5.1
        with:
          node-version: 16
      - name: Install npm dependencies
        run: ${{ github.event.inputs.packageManager }} install
      - name: Install Windows test app
        run: |
          npx --package react-native-test-app -- install-windows-test-app --use-nuget
        working-directory: ${{ github.event.inputs.projectRoot }}
      - name: Install NuGet packages
        run: |
          nuget restore
        working-directory: ${{ github.event.inputs.projectRoot }}/windows
      - name: Build Windows app
        run: |
          MSBuild -maxCpuCount -property:Configuration=Debug -property:Platform=${{ github.event.inputs.architecture }} -property:AppxBundlePlatforms=${{ github.event.inputs.architecture }} -property:AppxBundle=Always -property:UapAppxPackageBuildMode=SideloadOnly -property:UseBundle=false -target:Build
        working-directory: ${{ github.event.inputs.projectRoot }}/windows
      - name: Prepare build artifact
        id: prepare-build-artifact
        run: |
          appx_manifest=$(find ${{ github.event.inputs.architecture }}/Debug -name AppxManifest.xml -type f | head -1)
          app_name=$(basename $(dirname ${appx_manifest}))
          cp ${appx_manifest} AppPackages/${app_name}/*
          echo "app-name=${app_name}" >> $GITHUB_OUTPUT
        shell: bash
        working-directory: ${{ github.event.inputs.projectRoot }}/windows
      - name: Upload build artifact
        uses: actions/upload-artifact@v3
        with:
          name: windows-artifact
          path: ${{ github.event.inputs.projectRoot }}/windows/AppPackages/${{ steps.prepare-build-artifact.outputs.app-name }}
          if-no-files-found: error
          retention-days: 14
  distribute:
    name: "Distribute build"
    needs: [build-android, build-ios]
    runs-on: ubuntu-20.04
    if: ${{ github.event.inputs.distribution != 'local' && !cancelled() && !failure() }} # `success()` excludes skipped jobs
    steps:
      - name: Download build artifact
        uses: actions/download-artifact@v3
        with:
          name: ${{ github.event.inputs.platform }}-artifact
      - name: Display structure of build artifact
        run: ls -R
      - name: Upload to Firebase
        if: ${{ startsWith(github.event.inputs.distribution, 'firebase:') }}
        env:
          FIREBASE_APP_ID: ${{ github.event.inputs.distribution }}
          GOOGLE_APPLICATION_CREDENTIALS: credentials.json
        run: |
          artifact=$(find . -maxdepth 1 -type f | head -1)
          echo -n "${{ secrets.GOOGLE_APPLICATION_CREDENTIALS_BASE64 }}" | base64 --decode > ${GOOGLE_APPLICATION_CREDENTIALS}
          npx --package firebase-tools@11 firebase appdistribution:distribute "${artifact}" --app ${FIREBASE_APP_ID:9} --release-notes "${{ github.ref_name }}"
