name: Native S3 PyTorch Android

on:
  workflow_dispatch:

permissions:
  id-token: write
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        format: ["armeabi-v7a", "arm64-v8a", "x86" ,"x86_64"]
    env:
      NDK_VERSION: "21.1.6352462"
    steps:
      - uses: actions/checkout@v4
      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          distribution: 'corretto'
          java-version: 17
      - name: Set up Python3
        uses: actions/setup-python@v5
        with:
          python-version: '3.x'
      - name: clone pytorch
        run: |
          PYTORCH_VERSION=$(awk -F '=' '/pytorch/ {gsub(/ ?"/, "", $2); print $2}' gradle/libs.versions.toml)
          git clone https://github.com/pytorch/pytorch android_pytorch_tmp -b "v${PYTORCH_VERSION}" --recursive
      - name: install Python Dependencies
        run: pip install numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions
      - name: Install NDK
        run: echo "y" | sudo ${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager --install "ndk;${NDK_VERSION}"
      - name: build android
        run: |
          export ANDROID_NDK=${ANDROID_SDK_ROOT}/ndk/${NDK_VERSION}
          export ANDROID_ABI=${{ matrix.format }}
          cd android_pytorch_tmp
          BUILD_LITE_INTERPRETER=0 ./scripts/build_android.sh
          cd build_android
          zip -r ${{ matrix.format }}_native.zip install/include lib
      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::425969335547:role/djl-ci-publish-role
          aws-region: us-east-2
      - name: Copy files to S3 with the AWS CLI
        run: |
          PYTORCH_VERSION=$(awk -F '=' '/pytorch/ {gsub(/ ?"/, "", $2); print $2}' gradle/libs.versions.toml)
          aws s3 cp android_pytorch_tmp/build_android/${{ matrix.format }}_native.zip s3://djl-ai/publish/pytorch/${PYTORCH_VERSION}/android_native/
          aws cloudfront create-invalidation --distribution-id E371VB8JQ6NRVY --paths "/pytorch/${PYTORCH_VERSION}/android_native*"
