name: Сборка мода

on:
  workflow_dispatch:
  push:
    tags:
      - 'v*'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Скачивание APK
        run: |
          curl -L -o app.apk "https://mirror-dl.anixart-app.com/anixart-beta.apk"

      - name: Проверка наличия aapt
        run: |
          if ! command -v aapt &> /dev/null; then
            echo "aapt не найден, устанавливаем..."
            sudo apt-get update && sudo apt-get install -y --no-install-recommends android-sdk-build-tools
          fi

      - name: Проверка наличия pngquant
        run: |
          if ! command -v pngquant &> /dev/null; then
            echo "pngquant не найден, устанавливаем..."
            sudo apt-get update && sudo apt-get install -y --no-install-recommends pngquant
          fi

      - name: Извлечение хранилища ключей
        env:
          KEYSTORE: ${{ secrets.KEYSTORE }}
          KEYSTORE_PASS: ${{ secrets.KEYSTORE_PASS }}
        run: |
          # Export so later steps can reference them
          echo "$KEYSTORE" | base64 -d > keystore.jks
          echo "$KEYSTORE_PASS" > keystore.pass

      - name: Подготовка к модифицированию APK
        id: build
        run: |
          mkdir original
          mv app.apk original/
          pip install -r ./requirements.txt --break-system-packages
          python ./main.py init

      - name: Пересборка APK
        id: build
        run: |
          python ./main.py build -f

      - name: Чтение title из report.md
        id: get_title
        run: |
          TITLE=$(head -n 1 modified/report.md)
          echo "title=${TITLE}" >> $GITHUB_OUTPUT

      - name: Чтение body из report.md
        id: get_body
        run: |
          BODY=$(tail -n +3 modified/report.md)
          echo "body<<EOF" >> $GITHUB_OUTPUT
          echo "$BODY" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Установка go
        if: steps.build.outputs.BUILD_EXIT == '0'
        uses: actions/setup-go@v4
        with:
          go-version: '>=1.20'

      - name: Создание релиза
        if: steps.build.outputs.BUILD_EXIT == '0'
        uses: https://gitea.com/actions/release-action@main
        with:
          title: ${{ steps.get_title.outputs.title }}
          body: ${{ steps.get_body.outputs.body }}
          draft: true
          api_key: '${{secrets.RELEASE_TOKEN}}'
          files: |-
            modified/*-mod.apk
            modified/report.log
