name: Build & Release APK

on:
  push:
    tags:
      - 'v*'

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'
          cache: gradle

      - uses: android-actions/setup-android@v3

      - name: Build debug APK
        run: |
          chmod +x gradlew
          ./gradlew assembleDebug --no-daemon

      - name: Get version name
        id: ver
        run: echo "name=$(grep VERSION_NAME version.properties | cut -d= -f2)" >> $GITHUB_OUTPUT

      - name: Rename APK
        run: |
          mkdir dist
          cp app/build/outputs/apk/debug/app-debug.apk \
             dist/SyncFlow-v${{ steps.ver.outputs.name }}.apk

      - name: Attach APK to release
        env:
          TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAG: ${{ github.ref_name }}
          VERSION: ${{ steps.ver.outputs.name }}
        run: |
          RELEASE_ID=$(curl -sf \
            "https://gitea.khodak.me/api/v1/repos/amir/SyncFlow/releases/tags/$TAG" \
            -H "Authorization: token $TOKEN" \
            | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
          curl -sf -X POST \
            "https://gitea.khodak.me/api/v1/repos/amir/SyncFlow/releases/$RELEASE_ID/assets" \
            -H "Authorization: token $TOKEN" \
            -F "attachment=@dist/SyncFlow-v${VERSION}.apk"
          echo "APK uploaded to release $TAG"
