name: Publish Memby release

on:
  push:
    tags:
      - "v*.*.*"

permissions:
  contents: read

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Check out source
        uses: actions/checkout@v4

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

      - name: Set up Android SDK
        uses: android-actions/setup-android@v3

      - name: Install Android 35 build tools
        shell: bash
        run: sdkmanager "platforms;android-35" "build-tools;35.0.0"

      - name: Read version from tag
        shell: bash
        run: |
          VERSION="${GITEA_REF_NAME#v}"
          if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Tag must look like v0.1.54" >&2
            exit 1
          fi
          echo "VERSION=$VERSION" >> "$GITEA_ENV"

      - name: Restore release keystore
        shell: bash
        env:
          KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
        run: |
          printf '%s' "$KEYSTORE_BASE64" | base64 --decode > "$GITEA_WORKSPACE/memby-release.jks"

      - name: Test and build signed APK
        shell: bash
        env:
          MEMBY_KEYSTORE: ${{ gitea.workspace }}/memby-release.jks
          MEMBY_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
          MEMBY_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
          MEMBY_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
        run: |
          chmod +x ./gradlew
          ./gradlew --console=plain testDebugUnitTest assembleRelease \
            -Pmemby.versionName="$VERSION"

      - name: Publish to Memby gateway
        shell: bash
        env:
          RELEASE_TOKEN: ${{ secrets.MEMBY_RELEASE_PUBLISH_TOKEN }}
        run: |
          NOTES="$(git log -1 --pretty=%B)"
          curl --fail-with-body --show-error --silent \
            -X POST \
            -H "Authorization: Bearer $RELEASE_TOKEN" \
            -F "version=$VERSION" \
            -F "notes=$NOTES" \
            -F "apk=@app/build/outputs/apk/release/app-release.apk;type=application/vnd.android.package-archive" \
            https://mserver.sublogue.com/admin/api/release
