name: Publish App

on:
  release:
    types: [published]

jobs:
  publish:

    runs-on: ubuntu-22.04

    steps:
      - uses: actions/checkout@v3

      - name: Set up JDK 11
        uses: actions/setup-java@v3
        with:
          java-version: 11
          distribution: temurin

      - name: Retrieve secrets to files
        env:
          KEYSTORE: ${{ secrets.keystore }}
          SSH_KEY: ${{ secrets.ssh_key }}
        run: |
          echo "$KEYSTORE" | base64 -d > kiwix-android.keystore
          echo "$SSH_KEY" | base64 -d > ssh_key
          chmod 600 ssh_key

      - name: Publish APK to download.kiwix.org
        env:
          KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
          KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
          KEY_STORE_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }}
          UNIVERSAL_RELEASE_APK: app/build/outputs/apk/release/*universal*.apk
          ARCHIVE_NAME: kiwix-${{ github.event.release.tag_name }}.apk
        run: |
          ./gradlew assembleRelease
          cp ${UNIVERSAL_RELEASE_APK} ${ARCHIVE_NAME}
          scp -P 30022 -vrp -i ssh_key -o StrictHostKeyChecking=no "$ARCHIVE_NAME" ci@master.download.kiwix.org:/data/download/release/kiwix-android/

#      This is temporary, once we will publish 3.7.0 then we will uncommented this code.
#      # This is necessary for F-Droid
#      - name: Publish "versionInfo" to download.kiwix.org
#        run: |
#          ./gradlew generateVersionCodeAndName
#          scp -P 30022 -vrp -i ssh_key -o StrictHostKeyChecking=no VERSION_INFO ci@master.download.kiwix.org:/data/download/release/kiwix-android/

      - name: Publish to GitHub
        uses: ncipollo/release-action@v1
        with:
          artifacts: "app/build/outputs/apk/release/**"
          token: ${{ secrets.GITHUB_TOKEN }}
          draft: true
          prerelease: true

      - name: Publish bundle to Google Play
        env:
          KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
          KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
          KEY_STORE_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }}
          PLAYSTORE_JSON: ${{ secrets.PLAYSTORE_JSON }}
        run: |
          echo "$PLAYSTORE_JSON" > playstore.json
          ./gradlew publishPlayStoreBundle --scan
