name: Build & Release APK

on:
  push:
    branches: ['**']
    tags:
      - 'v*'
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: write   # needed to create the release object on a tag

    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: Run unit tests
        run: |
          chmod +x gradlew
          ./gradlew testDebugUnitTest --no-daemon

      - name: Decode release keystore
        env:
          KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
        run: |
          if [ -n "$KEYSTORE_BASE64" ]; then
            echo "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore"
            echo "KEYSTORE_PATH=$RUNNER_TEMP/release.keystore" >> "$GITHUB_ENV"
            echo "Release keystore decoded — building signed release."
          else
            echo "::warning::KEYSTORE_BASE64 secret not set — release APK will be debug-signed."
          fi

      - name: Build release APK
        env:
          KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
          KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
          KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
        run: ./gradlew assembleRelease --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/release/app-release.apk \
             dist/SyncFlow-v${{ steps.ver.outputs.name }}.apk

      - name: Attach APK to release
        if: startsWith(github.ref, 'refs/tags/v')
        env:
          TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAG: ${{ github.ref_name }}
          VERSION: ${{ steps.ver.outputs.name }}
        run: |
          API="https://gitea.khodak.me/api/v1/repos/amir/SyncFlow"
          # A pushed git tag does NOT create a Gitea release object — fetch it, create if missing.
          RELEASE_ID=$(curl -s "$API/releases/tags/$TAG" -H "Authorization: token $TOKEN" \
            | python3 -c "import sys,json;d=json.load(sys.stdin);print(d.get('id','') if isinstance(d,dict) else '')" 2>/dev/null)
          if [ -z "$RELEASE_ID" ]; then
            RELEASE_ID=$(curl -s -X POST "$API/releases" -H "Authorization: token $TOKEN" \
              -H "Content-Type: application/json" -d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\"}" \
              | python3 -c "import sys,json;print(json.load(sys.stdin).get('id',''))")
            echo "created release object $RELEASE_ID for $TAG"
          fi
          curl -sf -X POST "$API/releases/$RELEASE_ID/assets?name=SyncFlow-v${VERSION}.apk" \
            -H "Authorization: token $TOKEN" \
            -F "attachment=@dist/SyncFlow-v${VERSION}.apk"
          echo "APK uploaded to release $TAG (id $RELEASE_ID)"
