name: Nightly

on:
  schedule:
    # every night at midnight
    - cron:  '0 0 * * *'

jobs:

  instrumentation_tests:
    strategy:
      matrix:
        api-level: [21, 22, 23, 24, 25, 27, 28, 30]
        target: [default]
      fail-fast: false
    runs-on: macos-11
    steps:

      - name: checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 1

      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: 11

      - name: Restore Cache
        uses: actions/cache@v2
        with:
            path: |
              ~/.gradle/caches
              ~/.gradle/wrapper
            key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*') }}
            restore-keys: |
              ${{ runner.os }}-gradle-

      - name: run instrumentation tests
        uses: ReactiveCircus/android-emulator-runner@v2.23.0
        with:
          api-level: ${{ matrix.api-level }}
          target: ${{ matrix.target }}
          arch: x86_64
          profile: pixel_2
          ndk: 21.4.7075529
          sdcard-path-or-size: '1000M'
          disable-animations: false
          script: bash contrib/instrumentation_nightly.sh

      - name: Upload screenshot result
        uses: actions/upload-artifact@v1
        if: failure()
        with:
          name: ${{ matrix.api-level }}
          path: screencap.png

  unit_test_and_release:
    runs-on: ubuntu-22.04
    steps:

      - name: checkout
        uses: actions/checkout@v1
        with:
          fetch-depth: 1

      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: 11

      - name: Install NDK
        run: echo "y" | sudo ${ANDROID_HOME}/tools/bin/sdkmanager --install "ndk;22.0.7026061" --sdk_root=${ANDROID_SDK_ROOT}

      - name: run unit tests
        run: ./gradlew testDebugUnitTest testCustomExampleDebugUnitTest

      - name: build debug
        run: ./gradlew assembleDebug

      - name: Decrypt files
        env:
          ssh_key: ${{ secrets.ssh_key }}
        run: |
          echo "$ssh_key" | base64 -d > ssh_key
          chmod 600 ssh_key

      - name: Set date variable
        run: echo "DATE=$(echo $(date +%Y-%m-%d))" >> $GITHUB_ENV

      - name: release debug to kiwix.download.org
        env:
          UNIVERSAL_DEBUG_APK: app/build/outputs/apk/debug/*universal*.apk
        run: |
          mkdir $DATE
          cp $UNIVERSAL_DEBUG_APK $DATE
          scp -P 30022 -vrp -i ssh_key -o StrictHostKeyChecking=no $DATE ci@master.download.kiwix.org:/data/download/nightly/
