name: Build APK

on:
  workflow_dispatch:
    inputs:
      release_tag:
        required: false
        type: string
  push:
    branches:
      - master
    tags:
      - 'v*'

permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v6
      with:
        submodules: 'recursive'
        fetch-depth: '0'

    - name: Setup Android SDK
      uses: android-actions/setup-android@v4.0.0
      with:
        log-accepted-android-sdk-licenses: false
        cmdline-tools-version: '13114758'
        packages: 'platforms;android-36.1 build-tools;36.1.0 platform-tools'

    - name: Install NDK
      run: |
        echo "y" | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager \
          --channel=0 \
          --install "ndk;28.2.13676358"
        echo "NDK_HOME=$ANDROID_HOME/ndk/28.2.13676358" >> $GITHUB_ENV
        sed -i '10i\
        \
            ndkVersion = "28.2.13676358"' ${{ github.workspace }}/V2rayNG/app/build.gradle.kts

    - name: Restore cached libhevtun
      id: cache-libhevtun-restore
      uses: actions/cache/restore@v4
      with:
        path: ${{ github.workspace }}/libs
        key: libhevtun-${{ runner.os }}-${{ env.NDK_HOME }}-${{ hashFiles('.git/modules/hev-socks5-tunnel/HEAD') }}-${{ hashFiles('compile-hevtun.sh') }}

    - name: Build libhevtun
      if: steps.cache-libhevtun-restore.outputs.cache-hit != 'true'
      run: |
        bash compile-hevtun.sh
    
    - name: Save libhevtun
      if: steps.cache-libhevtun-restore.outputs.cache-hit != 'true'
      uses: actions/cache/save@v4
      with:
        path: ${{ github.workspace }}/libs
        key: libhevtun-${{ runner.os }}-${{ env.NDK_HOME }}-${{ hashFiles('.git/modules/hev-socks5-tunnel/HEAD') }}-${{ hashFiles('compile-hevtun.sh') }}

    - name: Copy libhevtun
      run: |
        cp -r ${{ github.workspace }}/libs ${{ github.workspace }}/V2rayNG/app

    - name: Fetch AndroidLibXrayLite tag
      run: |
        pushd AndroidLibXrayLite
        CURRENT_TAG=$(git describe --tags --abbrev=0)
        echo "Current tag in this repo: $CURRENT_TAG"
        echo "CURRENT_TAG=$CURRENT_TAG" >> $GITHUB_ENV
        popd

    - name: Download libv2ray
      uses: robinraju/release-downloader@v1.12
      with:
        repository: '2dust/AndroidLibXrayLite'
        tag: ${{ env.CURRENT_TAG }}
        fileName: 'libv2ray.aar'
        out-file-path: V2rayNG/app/libs/

    - name: Setup Java
      uses: actions/setup-java@v5
      with:
        distribution: 'temurin'
        java-version: '21'

    - name: Extract version from tag
      id: version
      run: |
        if [[ "${{ github.ref }}" == refs/tags/* ]]; then
          TAG_NAME="${{ github.ref_name }}"
          VERSION_NAME="${TAG_NAME#v}"
        elif [[ "${{ github.event.inputs.release_tag }}" != "" ]]; then
          TAG_NAME="${{ github.event.inputs.release_tag }}"
          VERSION_NAME="${TAG_NAME#v}"
        else
          VERSION_NAME="dev-$(git rev-parse --short HEAD)"
        fi
        
        IFS='.' read -ra VERSION_PARTS <<< "$VERSION_NAME"
        MAJOR=${VERSION_PARTS[0]:-0}
        MINOR=${VERSION_PARTS[1]:-0}
        PATCH=${VERSION_PARTS[2]:-0}
        VERSION_CODE=$((MAJOR * 1000000 + MINOR * 1000 + PATCH))
        
        echo "VERSION_NAME=$VERSION_NAME" >> $GITHUB_ENV
        echo "VERSION_CODE=$VERSION_CODE" >> $GITHUB_ENV
        echo "Version: $VERSION_NAME ($VERSION_CODE)"

    - name: Decode Keystore
      uses: timheuer/base64-to-file@v1.2.4
      id: android_keystore
      with:
        fileName: "android_keystore.jks"
        encodedString: ${{ secrets.APP_KEYSTORE_BASE64 }}

    - name: Build APK
      env:
        KEYSTORE_FILE: ${{ steps.android_keystore.outputs.filePath }}
        KEYSTORE_PASSWORD: ${{ secrets.APP_KEYSTORE_PASSWORD }}
        KEY_ALIAS: ${{ secrets.APP_KEYSTORE_ALIAS }}
        KEY_PASSWORD: ${{ secrets.APP_KEY_PASSWORD }}
      run: |
        cd ${{ github.workspace }}/V2rayNG
        echo "sdk.dir=${ANDROID_HOME}" > local.properties
        echo "Keystore file path: ${KEYSTORE_FILE}"
        echo "Key alias: ${KEY_ALIAS}"
        if [ -f "${KEYSTORE_FILE}" ]; then
          echo "Keystore file exists"
          ls -lh "${KEYSTORE_FILE}"
          keytool -list -v -keystore "${KEYSTORE_FILE}" -storepass "${KEYSTORE_PASSWORD}" 2>&1 | head -20 || echo "Failed to list keystore contents"
        else
          echo "ERROR: Keystore file not found at ${KEYSTORE_FILE}"
          exit 1
        fi
        chmod 755 gradlew
        ./gradlew licenseFdroidReleaseReport
        ./gradlew assembleRelease --info 2>&1 | grep -i "signing\|keystore" || true
    
    - name: Upload arm64-v8a APK
      uses: actions/upload-artifact@v7
      if: ${{  success() }}
      with:
        name: arm64-v8a
        path: ${{ github.workspace }}/V2rayNG/app/build/outputs/apk/*/release/*arm64-v8a*.apk

    - name: Upload armeabi-v7a APK
      uses: actions/upload-artifact@v7
      if: ${{  success() }}
      with:
        name: armeabi-v7a
        path: ${{ github.workspace }}/V2rayNG/app/build/outputs/apk/*/release/*armeabi-v7a*.apk

    - name: Upload x86 APK
      uses: actions/upload-artifact@v7
      if: ${{  success() }}
      with:
        name: x86-apk
        path: ${{ github.workspace }}/V2rayNG/app/build/outputs/apk/*/release/*x86*.apk

    - name: Upload to release
      uses: softprops/action-gh-release@v2
      if: github.event.inputs.release_tag != '' || startsWith(github.ref, 'refs/tags/')
      with:
        files: ${{ github.workspace }}/V2rayNG/app/build/outputs/apk/*/release/*.apk
        tag_name: ${{ github.event.inputs.release_tag || github.ref_name }}
        prerelease: true
        generate_release_notes: true
