name: Release Builder
# Build a stable release on a tag v* newly pushed

on:
  push:
    tags:
      - v*

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

permissions:
  contents: write

jobs:
  prepare-build:
    runs-on: 'ubuntu-24.04'
    outputs:
      VERSION_TAG: ${{ steps.get_tag.outputs.VERSION_TAG }}
      CURRENT_SHA: ${{ steps.current_commit.outputs.CURRENT_SHA }}
      PREV_RELEASE_SHA: ${{ steps.previous_commit.outputs.PREV_RELEASE_SHA }}
      COMMIT_LOGS: ${{ steps.commit_logs.outputs.COMMIT_LOGS }}
      PREV_TAG_NAME: ${{ steps.previous_commit.outputs.PREV_TAG_NAME }}
    steps:
      - name: Get tag name (${{ github.ref }})
        id: get_tag
        run: |
          version_tag=$(echo ${GITHUB_REF/refs\/tags\//} | sed -r 's/^refs\/(heads|tags)\///' | sed -r 's/[-\/]+/_/g')
          echo "VERSION_TAG=$version_tag"
          echo "VERSION_TAG=$version_tag" >> $GITHUB_OUTPUT

      - name: Clone Repository (${{ steps.get_tag.outputs.VERSION_TAG }})
        uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
        with:
          fetch-depth: 0

      - name: Get previous release
        id: last_release
        uses: InsonusK/get-latest-release@7a9ff16c8c6b7ead5d71c0f1cc61f2703170eade # v1.1.0
        with:
          myToken: ${{ github.token }}
          exclude_types: "draft|prerelease"
          view_top: 1

      - name: Curren commit
        id: current_commit
        run: |
          commit_count=$(git rev-list --count HEAD)
          current_sha=$(git rev-parse --short HEAD)
          echo "COMMIT_COUNT=$commit_count"
          echo "COMMIT_COUNT=$commit_count" >> $GITHUB_OUTPUT
          echo "CURRENT_SHA=$current_sha"
          echo "CURRENT_SHA=$current_sha" >> $GITHUB_OUTPUT

      - name: Previous commit
        id: previous_commit
        run: |
          commit_count_diff=$(git rev-list --count "${{ steps.last_release.outputs.tag_name }}"..HEAD)

          # Fake at least 1 commits (to avoid no changes)
          if [ "${commit_count_diff}" -eq 0 ]; then
            commit_count_diff=1
          fi

          echo "commit_count_diff=$commit_count_diff"
          prev_release_sha=$(git rev-parse --short HEAD~$commit_count_diff)
          echo "PREV_RELEASE_SHA=$prev_release_sha"
          echo "PREV_RELEASE_SHA=$prev_release_sha" >> $GITHUB_OUTPUT
          echo "PREV_TAG_NAME=${{ steps.last_release.outputs.tag_name }}"
          echo "PREV_TAG_NAME=${{ steps.last_release.outputs.tag_name }}" >> $GITHUB_OUTPUT

      - name: Commit logs
        id: commit_logs
        run: |
          echo "COMMIT_LOGS<<{delimiter}
          $(curl -H "Accept: application/vnd.github.v3+json" \
            "https://api.github.com/repos/komikku-app/komikku/compare/${{ steps.previous_commit.outputs.PREV_RELEASE_SHA }}...${{ steps.current_commit.outputs.CURRENT_SHA }}" \
            | jq '[.commits[]|{message:(.commit.message | split("\n")), username:.author.login}]' \
            | jq -r '.[]|"- \(.message | first) (@\(.username))"')
          {delimiter}" >> $GITHUB_OUTPUT

  build-app:
    name: Build release app
    runs-on: 'ubuntu-24.04'
    needs: prepare-build
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - name: Clone Repository (${{ needs.prepare-build.outputs.VERSION_TAG }})
        uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
        with:
          fetch-depth: 0

      - name: Set up JDK
        uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
        with:
          java-version: 17
          distribution: temurin

      - name: Write google-services.json
        uses: DamianReeves/write-file-action@6929a9a6d1807689191dcc8bbe62b54d70a32b42 # v1.3
        with:
          path: app/google-services.json
          contents: ${{ secrets.GOOGLE_SERVICES_JSON }}
          write-mode: overwrite

      - name: Write client_secrets.json
        uses: DamianReeves/write-file-action@6929a9a6d1807689191dcc8bbe62b54d70a32b42 # v1.3
        with:
          path: app/src/main/assets/client_secrets.json
          contents: ${{ secrets.GOOGLE_CLIENT_SECRETS_JSON }}
          write-mode: overwrite

      - name: Set up gradle
        uses: gradle/actions/setup-gradle@0723195856401067f7a2779048b490ace7a47d7c # v5

      - name: Check code format
        run: ./gradlew spotlessCheck

      - name: Build app
        run: ./gradlew assembleRelease -Pinclude-telemetry -Penable-updater

      - name: Run unit tests
        run: ./gradlew testReleaseUnitTest

      - name: Upload artifacts
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
        with:
          path: "**/*.apk"
          retention-days: 1

      - name: Upload mapping
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
        with:
          name: mapping-${{ github.sha }}
          path: app/build/outputs/mapping/release

  release-app:
    runs-on: 'ubuntu-24.04'
    needs:
      - prepare-build
      - build-app
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
        with:
          merge-multiple: true

      - name: Sign APK
        uses: r0adkll/sign-android-release@f30bdd30588842ac76044ecdbd4b6d0e3e813478
        with:
          releaseDirectory: app/build/outputs/apk/release
          signingKeyBase64: ${{ secrets.SIGNING_KEY }}
          alias: ${{ secrets.ALIAS }}
          keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }}
          keyPassword: ${{ secrets.KEY_PASSWORD }}
        env:
          BUILD_TOOLS_VERSION: '35.0.1'

      - name: Get SHA & clean up build artifacts
        id: get_sha
        run: |
          set -e

          mv app/build/outputs/apk/release/app-universal-release-unsigned-signed.apk Komikku-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
          mv app/build/outputs/apk/release/app-arm64-v8a-release-unsigned-signed.apk Komikku-arm64-v8a-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
          mv app/build/outputs/apk/release/app-armeabi-v7a-release-unsigned-signed.apk Komikku-armeabi-v7a-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
          mv app/build/outputs/apk/release/app-x86-release-unsigned-signed.apk Komikku-x86-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
          mv app/build/outputs/apk/release/app-x86_64-release-unsigned-signed.apk Komikku-x86_64-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk

      - name: Create release
        uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2
        with:
          tag_name: ${{ needs.prepare-build.outputs.VERSION_TAG }}
          name: Komikku ${{ needs.prepare-build.outputs.VERSION_TAG }}
          body: |
            [![GitHub downloads](https://img.shields.io/github/downloads/komikku-app/komikku/${{ needs.prepare-build.outputs.VERSION_TAG }}/total?label=Downloaded&labelColor=27303D&color=0D1117&logo=github&logoColor=FFFFFF&style=flat)](https://github.com/komikku-app/komikku/releases/${{ needs.prepare-build.outputs.VERSION_TAG }})
            #### What's Changed
            ##### New

            ##### Improve

            ##### Fix

            ${{ needs.prepare-build.outputs.COMMIT_LOGS }}

            ##### Based on

            **Full Changelog**: [komikku-app/komikku@${{ needs.prepare-build.outputs.PREV_TAG_NAME }}...${{ needs.prepare-build.outputs.VERSION_TAG }}](https://github.com/komikku-app/komikku/compare/${{ needs.prepare-build.outputs.PREV_TAG_NAME }}...${{ needs.prepare-build.outputs.VERSION_TAG }})

            <!-->
            > [!TIP]
            >
            > ### If you are unsure which version to download then go with `Komikku-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk`
          files: |
            Komikku-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
            Komikku-arm64-v8a-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
            Komikku-armeabi-v7a-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
            Komikku-x86-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
            Komikku-x86_64-${{ needs.prepare-build.outputs.VERSION_TAG }}.apk
          draft: true
          prerelease: false
          token: ${{ secrets.GITHUB_TOKEN }}
