name: Deploy release

on:
  release:
    types: [ created ]

jobs:

  deploy-google-play:
    name: Google Play
    runs-on: ubuntu-latest
    timeout-minutes: 10
    environment: google-play
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-java@v3
        with:
          distribution: 'zulu'
          java-version: 17
      - uses: actions/cache@v3
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}
      - name: Decrypt keys
        env:
          ENCRYPT_KEY: ${{ secrets.ENCRYPT_KEY }}
          SERVICES_ENCRYPT_KEY: ${{ secrets.SERVICES_ENCRYPT_KEY }}
        run: |
          gpg --yes --batch --passphrase=$SERVICES_ENCRYPT_KEY ./app/src/release/google-services.json.gpg
          gpg --yes --batch --passphrase=$ENCRYPT_KEY ./app/upload-key.jks.gpg
      - name: Upload apk to google play
        env:
          PLAY_STORE_PASSWORD: ${{ secrets.PLAY_STORE_PASSWORD }}
          PLAY_KEY_ALIAS: ${{ secrets.PLAY_KEY_ALIAS }}
          PLAY_KEY_PASSWORD: ${{ secrets.PLAY_KEY_PASSWORD }}
          ANDROID_PUBLISHER_CREDENTIALS: ${{ secrets.ANDROID_PUBLISHER_CREDENTIALS }}
          ADMOB_PROJECT_ID: ${{ secrets.ADMOB_PROJECT_ID }}
          SINGLE_SUPPORT_AD_ID: ${{ secrets.SINGLE_SUPPORT_AD_ID }}
          DASHBOARD_TILE_AD_ID: ${{ secrets.DASHBOARD_TILE_AD_ID }}
          SET_BUILD_TIMESTAMP: ${{ secrets.SET_BUILD_TIMESTAMP }}
        run: ./gradlew publishPlayReleaseApps --stacktrace;

  deploy-app-gallery:
    name: AppGallery
    runs-on: ubuntu-latest
    timeout-minutes: 10
    environment: app-gallery
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-java@v3
        with:
          distribution: 'zulu'
          java-version: 17
      - uses: actions/cache@v3
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}
      - name: Decrypt keys
        env:
          ENCRYPT_KEY: ${{ secrets.ENCRYPT_KEY }}
          SERVICES_ENCRYPT_KEY: ${{ secrets.SERVICES_ENCRYPT_KEY }}
        run: |
          gpg --yes --batch --passphrase=$SERVICES_ENCRYPT_KEY ./app/src/release/agconnect-services.json.gpg
          gpg --yes --batch --passphrase=$ENCRYPT_KEY ./app/upload-key.jks.gpg
      - name: Prepare credentials
        env:
          AGC_CREDENTIALS: ${{ secrets.AGC_CREDENTIALS }}
        run: echo $AGC_CREDENTIALS > ./app/src/release/agconnect-credentials.json
      - name: Build and publish HMS version
        env:
          PLAY_STORE_PASSWORD: ${{ secrets.PLAY_STORE_PASSWORD }}
          PLAY_KEY_ALIAS: ${{ secrets.PLAY_KEY_ALIAS }}
          PLAY_KEY_PASSWORD: ${{ secrets.PLAY_KEY_PASSWORD }}
          SET_BUILD_TIMESTAMP: ${{ secrets.SET_BUILD_TIMESTAMP }}
        run: ./gradlew bundleHmsRelease --stacktrace && ./gradlew publishHuaweiAppGalleryHmsRelease --stacktrace
