name: Android Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      tag:
        description: 'Release tag (e.g. v0.36.2)'
        required: true
        default: 'v0.36.2'

env:
  APK_OUT: target/release/apk/ferrous-solitaire.apk
  GITEA_URL: https://git.aleshym.co
  REPO: funman300/Ferrous-Solitaire

jobs:
  build-apk:
    runs-on: ubuntu-latest
    container:
      image: git.aleshym.co/funman300/android-builder:latest
      credentials:
        username: ${{ gitea.actor }}
        password: ${{ secrets.CI_TOKEN }}

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Cache Cargo registry
        uses: actions/cache@v4
        with:
          path: |
            /usr/local/cargo/registry/index
            /usr/local/cargo/registry/cache
            /usr/local/cargo/git/db
          key: cargo-registry-android-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: cargo-registry-android-

      - name: Cache sccache
        uses: actions/cache@v4
        with:
          path: /root/.cache/sccache
          key: sccache-android-aarch64-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: sccache-android-aarch64-

      - name: Get tag name
        id: tag
        run: |
          if [ -n "${{ github.event.inputs.tag }}" ]; then
            echo "name=${{ github.event.inputs.tag }}" >> "$GITHUB_OUTPUT"
          else
            echo "name=${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT"
          fi

      - name: Decode release keystore
        run: echo "${{ secrets.RELEASE_KEYSTORE_B64 }}" | base64 -d > release.jks

      - name: Build release APK
        env:
          PROFILE: release
          ABIS: arm64-v8a
          KEYSTORE: ./release.jks
          KEYSTORE_PASS: ${{ secrets.RELEASE_KEYSTORE_PASS }}
          KEY_ALIAS: release
          KEY_PASS: ${{ secrets.RELEASE_KEYSTORE_PASS }}
          VERSION_NAME: ${{ steps.tag.outputs.name }}
          RUSTC_WRAPPER: sccache
          SCCACHE_DIR: /root/.cache/sccache
        run: bash scripts/build_android_apk.sh

      - name: sccache stats
        if: always()
        run: sccache --show-stats

      - name: Create or get Gitea release
        id: release
        run: |
          TAG="${{ steps.tag.outputs.name }}"
          BASE="${{ env.GITEA_URL }}/api/v1/repos/${{ env.REPO }}"
          AUTH="Authorization: token ${{ secrets.CI_TOKEN }}"

          ID=$(curl -sf -H "$AUTH" "$BASE/releases/tags/$TAG" \
               | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" \
               2>/dev/null || true)

          if [ -z "$ID" ]; then
            ID=$(curl -sf -X POST \
                 -H "$AUTH" -H "Content-Type: application/json" \
                 "$BASE/releases" \
                 -d "{
                   \"tag_name\": \"$TAG\",
                   \"name\": \"$TAG\",
                   \"body\": \"## Android release $TAG\n\n**Install / update with Obtainium** — add this source URL:\n\`\`\`\nhttps://git.aleshym.co/funman300/Ferrous-Solitaire\n\`\`\`\n\nOr download \`ferrous-solitaire.apk\` below and sideload it directly.\",
                   \"draft\": false,
                   \"prerelease\": false
                 }" \
                 | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
          fi
          echo "id=$ID" >> "$GITHUB_OUTPUT"

      - name: Upload APK to release
        run: |
          BASE="${{ env.GITEA_URL }}/api/v1/repos/${{ env.REPO }}"
          AUTH="Authorization: token ${{ secrets.CI_TOKEN }}"
          RELEASE_ID="${{ steps.release.outputs.id }}"

          # Remove any existing APK assets so re-runs don't accumulate duplicates.
          curl -sf -H "$AUTH" "$BASE/releases/$RELEASE_ID/assets" \
            | python3 -c "import sys,json; [print(a['id']) for a in json.load(sys.stdin) if a['name'].endswith('.apk')]" \
            | while read AID; do
                curl -sf -X DELETE -H "$AUTH" "$BASE/releases/$RELEASE_ID/assets/$AID"
              done

          curl -sf -X POST \
            -H "$AUTH" \
            -F "attachment=@${{ env.APK_OUT }};type=application/vnd.android.package-archive" \
            "$BASE/releases/$RELEASE_ID/assets"
