name: CI

on:
  push:
    branches:
      - master
    paths-ignore:
      - '**.md'
      - '.github/workflows/issue_moderator.yml'
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}
  cancel-in-progress: true

env:
  CI_CHUNK_SIZE: 65

jobs:
  prepare:
    name: Prepare job
    runs-on: arch
    env:
      CI_MODULE_GEN: true
    steps:
      - name: Clone repo
        uses: actions/checkout@v4

  build_individual:
    name: Build individual modules
    needs: prepare
    runs-on: arch
    steps:
      - name: Checkout master branch
        uses: actions/checkout@v4

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

      - name: Prepare signing key
        run: |
          echo ${{ secrets.SIGNING_KEY }} | base64 -d > signingkey.jks

      - name: Set up Gradle
        uses: gradle/actions/setup-gradle@417ae3ccd767c252f5661f1ace9f835f9654f2b5 # v3.1.0

      - name: Build extensions
        env:
          ALIAS: ${{ secrets.ALIAS }}
          KEY_STORE_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }}
          KEY_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }}
        run: ./gradlew -p src assembleRelease
        

      - name: Upload APKs
        uses: actions/upload-artifact@v3
        with:
          name: "individual-apks"
          path: "**/*.apk"
          retention-days: 1

      - name: Clean up CI files
        run: rm signingkey.jks

  publish_repo:
    name: Publish repo
    needs:
      - build_individual
    runs-on: arch
    steps:
      - name: Download APK artifacts
        uses: actions/download-artifact@v3
        with:
          path: ~/apk-artifacts

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

      - name: Checkout master branch
        uses: actions/checkout@v4
        with:
          ref: master
          path: master

      - name: Create repo artifacts
        run: |
          cd master
          python ./.github/scripts/move-apks.py
          INSPECTOR_LINK="$(curl -s "https://api.github.com/repos/keiyoushi/extensions-inspector/releases/latest" | jq -r '.assets[0].browser_download_url')"
          curl -L "$INSPECTOR_LINK" -o ./Inspector.jar
          java -jar ./Inspector.jar "repo/apk" "output.json" "tmp"
          python ./.github/scripts/create-repo.py

      - name: Checkout repo branch
        uses: actions/checkout@v4
        with:
          ref: repo
          path: repo

      - name: Deploy repo
        run: |
          cd repo
          ../master/.github/scripts/commit-repo.sh
          rm -r ~/apk-artifacts
