name: Build app

run-name: ${{ github.event_name == 'workflow_dispatch' && format('Build and Release v{0}', github.event.inputs.version) || github.event.commits[0].message }}

on:
  push:
    branches:
      - master
  workflow_dispatch:
    inputs:
      version:
        description: 'Version (without "v" prefix)'
        required: true
        type: string
      beta:
        description: 'Beta release'
        default: false
        required: false
        type: boolean
      message:
        description: 'Message for releases (the text at the top of changelog)'
        default: ''
        required: false
        type: string

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name == 'workflow_dispatch' }}
  cancel-in-progress: true

jobs:
  build:
    name: Build app
    runs-on: ubuntu-latest

    steps:
      - name: Clone repo
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Android SDK
        run: |
          ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager "build-tools;35.0.0"

      - name: Setup Gradle
        uses: null2264/actions/gradle-setup@a4d662095a2f2af1ed24f1228eb6e55b0f9f1f29
        with:
          java: 17
          distro: temurin

      - name: Setup CHANGELOG parser
        uses: taiki-e/install-action@parse-changelog

      - name: Copy CI gradle.properties
        run: |
          mkdir -p ~/.gradle
          cp .github/runner-files/ci-gradle.properties ~/.gradle/gradle.properties

      - name: Extract branch name
        id: branch_name
        shell: bash
        run: echo "NAME=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT

      - name: Get changelog
        id: changelog
        shell: bash
        run: |
          # extended SemVer (major.minor.patch.hotfix)
          VERSION_FORMAT='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))?(-[0-9A-Za-z\.-]+)?(\+[0-9A-Za-z\.-]+)?$|^Unreleased$'
          {
            echo "CHANGELOG<<END_OF_FILE"
            parse-changelog CHANGELOG.md ${{ github.event.inputs.version == '' && 'Unreleased' || github.event.inputs.version }} --version-format $VERSION_FORMAT || parse-changelog CHANGELOG.md Unreleased --version-format $VERSION_FORMAT || echo "No documented changes so far..."
            echo ""
            echo "END_OF_FILE"
          } >> "$GITHUB_OUTPUT" 2> /dev/null

      # PROD
      - name: Prepare release build
        if: github.event.inputs.version != '' && github.event.inputs.beta != 'true'
        run: |
          set -x
          echo "VERSION_TAG=v${{github.event.inputs.version}}" >> $GITHUB_ENV
          echo "BUILD_TYPE=StandardRelease" >> $GITHUB_ENV

      # BETA
      - name: Prepare beta build
        if: github.event.inputs.version != '' && github.event.inputs.beta == 'true'
        run: |
          set -x

          BETA_COUNT=$(git tag -l --sort=refname "v${{github.event.inputs.version}}-b*" | tail -n1 | sed "s/^\S*-b//g")
          if [ -z "$BETA_COUNT" ]; then
            BETA_COUNT="1"
          else
            BETA_COUNT=$((BETA_COUNT+1))
          fi

          echo "VERSION_TAG=v${{github.event.inputs.version}}-b${BETA_COUNT}" >> $GITHUB_ENV
          echo "BUILD_TYPE=StandardBeta" >> $GITHUB_ENV

      # NIGHTLY
      - name: Prepare nightly build
        if: steps.branch_name.outputs.NAME == 'master' && github.event.inputs.version == ''
        run: |
          set -x
          echo "VERSION_TAG=r$(git rev-list --count HEAD)" >> $GITHUB_ENV
          echo "BUILD_TYPE=StandardNightly" >> $GITHUB_ENV
          echo "COMMIT_HASH=$(git rev-parse HEAD)" >> $GITHUB_ENV
          echo "COMMIT_SHORT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV

      - name: Build the app
        if: startsWith(env.BUILD_TYPE, 'Standard')
        run: ./gradlew assemble${{ env.BUILD_TYPE }}

      - name: Run unit tests
        if: startsWith(env.BUILD_TYPE, 'Standard')
        run: ./gradlew testReleaseUnitTest test${{ env.BUILD_TYPE }}UnitTest

      - name: Upload R8 APK to artifact
        uses: actions/upload-artifact@v4
        if: env.VERSION_TAG != ''
        with:
          name: arm64-v8a-${{ github.sha }}
          path: app/build/outputs/apk/standard/*/app*-arm64-v8a-*.apk

      - name: Upload R8 mapping
        uses: actions/upload-artifact@v4
        if: env.VERSION_TAG != ''
        with:
          name: mapping-${{ github.sha }}
          path: app/build/outputs/mapping/standard*

      - name: Publish test report
        uses: mikepenz/action-junit-report@v5
        if: success() || failure()
        with:
          include_passed: true
          detailed_summary: true
          report_paths: '**/build/test-results/test*/TEST-*.xml'

      - name: Get version stage
        id: version_stage
        shell: bash
        run: |
          stage=""
          case "${{ env.VERSION_TAG }}" in
            v*)
              [ "$(echo '${{ env.VERSION_TAG }}' | grep 'v*-b')" = "" ] && stage="release" || stage="beta"
              ;;
            r*) stage="nightly" ;;
          esac
          [ "$stage" = "" ] && exit 1  # something went wrong

          echo "STAGE=${stage}" >> $GITHUB_OUTPUT

      - name: Sign APK
        uses: null2264/actions/android-signer@a4d662095a2f2af1ed24f1228eb6e55b0f9f1f29
        if: env.VERSION_TAG != ''
        with:
          releaseDir: app/build/outputs/apk/standard/${{ steps.version_stage.outputs.STAGE }}
          signingKeyBase64: ${{ secrets.SIGNING_KEY }}
          keyAlias: ${{ secrets.ALIAS }}
          keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }}
          keyPassword: ${{ secrets.KEY_PASSWORD }}
          summarise: true

      - name: Clean up build artifacts
        if: env.VERSION_TAG != ''
        run: |
          set -e

          dir="app/build/outputs/apk/standard/${{ steps.version_stage.outputs.STAGE }}"

          mv $dir/app-standard-universal-*-signed.apk yokai-${{ env.VERSION_TAG }}.apk
          sha=`sha256sum yokai-${{ env.VERSION_TAG }}.apk | awk '{ print $1 }'`
          echo "APK_UNIVERSAL_SHA=$sha" >> $GITHUB_ENV

          cp $dir/app-standard-arm64-v8a-*-signed.apk yokai-arm64-v8a-${{ env.VERSION_TAG }}.apk
          sha=`sha256sum yokai-arm64-v8a-${{ env.VERSION_TAG }}.apk | awk '{ print $1 }'`
          echo "APK_ARM64_V8A_SHA=$sha" >> $GITHUB_ENV

          cp $dir/app-standard-armeabi-v7a-*-signed.apk yokai-armeabi-v7a-${{ env.VERSION_TAG }}.apk
          sha=`sha256sum yokai-armeabi-v7a-${{ env.VERSION_TAG }}.apk | awk '{ print $1 }'`
          echo "APK_ARMEABI_V7A_SHA=$sha" >> $GITHUB_ENV

          cp $dir/app-standard-x86-*-signed.apk yokai-x86-${{ env.VERSION_TAG }}.apk
          sha=`sha256sum yokai-x86-${{ env.VERSION_TAG }}.apk | awk '{ print $1 }'`
          echo "APK_X86_SHA=$sha" >> $GITHUB_ENV
          
          cp $dir/app-standard-x86_64-*-signed.apk yokai-x86_64-${{ env.VERSION_TAG }}.apk
          sha=`sha256sum yokai-x86_64-${{ env.VERSION_TAG }}.apk | awk '{ print $1 }'`
          echo "APK_X86_64_SHA=$sha" >> $GITHUB_ENV

      - name: Create Release
        if: startsWith(env.VERSION_TAG, 'v')
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ env.VERSION_TAG }}
          name: Yōkai ${{ env.VERSION_TAG }}
          body: |
            ${{ github.event.inputs.message }}

            ${{ steps.changelog.outputs.CHANGELOG }}
            ---

            ### Checksums

            | Variant | SHA-256 |
            | ------- | ------- |
            | Universal | ${{ env.APK_UNIVERSAL_SHA }}
            | arm64-v8a | ${{ env.APK_ARM64_V8A_SHA }}
            | armeabi-v7a | ${{ env.APK_ARMEABI_V7A_SHA }}
            | x86 | ${{ env.APK_X86_SHA }} |
            | x86_64 | ${{ env.APK_X86_64_SHA }} |
            
            > [!TIP]
            >
            > If you are unsure which version to download then go with **yokai-${{ env.VERSION_TAG }}.apk**
          files: |
            yokai-${{ env.VERSION_TAG }}.apk
            yokai-arm64-v8a-${{ env.VERSION_TAG }}.apk
            yokai-armeabi-v7a-${{ env.VERSION_TAG }}.apk
            yokai-x86-${{ env.VERSION_TAG }}.apk
            yokai-x86_64-${{ env.VERSION_TAG }}.apk
          draft: true
          prerelease: ${{ github.event.inputs.beta }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Create Nightly
        if: startsWith(env.VERSION_TAG, 'r')
        uses: softprops/action-gh-release@v2
        with:
          repository: null2264/yokai-nightly
          tag_name: ${{ env.VERSION_TAG }}
          name: Yōkai Nightly (${{ env.VERSION_TAG }})
          body: |
            > [!CAUTION]
            > _**This alpha version is for testing only!**_
            >
            > This build is triggered by commit [`${{ env.COMMIT_SHORT_HASH }}`](https://github.com/null2264/yokai/commit/${{ env.COMMIT_HASH }})

            It is not ready for daily use and we do not guarantee its usability. Please download the latest stable releases instead (https://github.com/null2264/yokai/releases/latest). If you insist, please be sure to ALWAYS backup before updating.
            
            ${{ steps.changelog.outputs.CHANGELOG }}
            ---

            ### Checksums

            | Variant | SHA-256 |
            | ------- | ------- |
            | Universal | ${{ env.APK_UNIVERSAL_SHA }}
            | arm64-v8a | ${{ env.APK_ARM64_V8A_SHA }}
            | armeabi-v7a | ${{ env.APK_ARMEABI_V7A_SHA }}
            | x86 | ${{ env.APK_X86_SHA }} |
            | x86_64 | ${{ env.APK_X86_64_SHA }} |
            
            > [!TIP]
            >
            > If you are unsure which version to download then go with **yokai-${{ env.VERSION_TAG }}.apk**
          files: |
            yokai-${{ env.VERSION_TAG }}.apk
            yokai-arm64-v8a-${{ env.VERSION_TAG }}.apk
            yokai-armeabi-v7a-${{ env.VERSION_TAG }}.apk
            yokai-x86-${{ env.VERSION_TAG }}.apk
            yokai-x86_64-${{ env.VERSION_TAG }}.apk
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.NIGHTLY_PAT }}
