name: build

on:
  push:
    branches:
      - main
    paths:
      - 'module/**'
  pull_request:
    paths:
      - 'module/**'
  workflow_dispatch:

jobs:
  build:
    name: build
    runs-on: ubuntu-latest
    outputs:
      version_tag_exists: ${{ steps.check_tag.outputs.version_tag_exists }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          fetch-tags: true

      - name: Update dependency
        run: |
          curl -Ls https://cdn.jsdelivr.net/npm/marked/marked.min.js > module/webui/scripts/assets/marked.min.js
          wget -q $(curl -Ls https://api.github.com/repos/KOWX712/openssl-static-build/releases/latest | jq -r '.assets[].browser_download_url') -O openssl.tar.gz
          tar -xzf openssl.tar.gz
          mv openssl-arm64 module/bin/arm64-v8a/openssl
          mv openssl-arm32 module/bin/armeabi-v7a/openssl

          # Commit if found changes
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git config --global user.name "github-actions[bot]"

          # Commit marked.min.js if changed
          if git status --porcelain | grep 'module/webui/scripts/assets/marked.min.js'; then
            git add module/webui/scripts/assets/marked.min.js
            git commit -m "deps: update marked.min.js"
          fi

          # Commit OpenSSL files if changed
          if git status --porcelain | grep -E 'module/bin/arm64-v8a|module/bin/armeabi-v7a'; then
            git add module/bin/arm64-v8a/openssl module/bin/armeabi-v7a/openssl
            git commit -m "deps: update OpenSSL binaries"
          fi

          # Push all commits
          git push

      - name: Extract Module Info
        id: extract_info
        run: |
          MODULE_VERSION=$(grep '^version=' module/module.prop | sed 's/version=//')
          COMMIT_NUM=$(git rev-list --count HEAD)
          BUILD_COUNT=${{ github.run_number }}
          ARTIFACT_NAME="TrickyAddonModule-${MODULE_VERSION}-${COMMIT_NUM}${BUILD_COUNT}-canary"
          sed -i "s/^version=.*/& (${COMMIT_NUM}${BUILD_COUNT}-canary)/" module/module.prop
          echo "MODULE_VERSION=${MODULE_VERSION}" >> $GITHUB_ENV
          echo "ARTIFACT_NAME=${ARTIFACT_NAME}" >> $GITHUB_ENV
          echo "VERSION=${MODULE_VERSION}" >> $GITHUB_ENV

      - name: Upload Artifact
        uses: actions/upload-artifact@v4
        with:
          name: ${{ env.ARTIFACT_NAME }}
          path: module/
          include-hidden-files: true

      - name: Check if valid to release
        id: check_tag
        run: |
          if [ "${{ github.event_name }}" = "pull_request" ]; then
            echo "version_tag_exists=true" >> $GITHUB_OUTPUT
          else
            git fetch --tags
            VERSION=${{ env.VERSION }}
            if git tag | grep -qx "^${VERSION}"; then
              echo "version_tag_exists=true" >> $GITHUB_OUTPUT
            else
              echo "version_tag_exists=false" >> $GITHUB_OUTPUT
            fi
          fi

  release:
    name: release
    runs-on: ubuntu-latest
    needs: build
    if: ${{ needs.build.outputs.version_tag_exists == 'false' }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: Set release variables
        id: set_release_variables
        run: |
          VERSION=$(grep '^version=' module/module.prop | sed 's/version=//')
          RELEASE_NOTES=$(awk -v tag="### $VERSION" '
            $0 == tag {flag=1; next}
            /^###/ && flag {exit}
            flag {print}
          ' changelog.md)

          if [[ "$VERSION" == *"beta"* ]]; then
            PRERELEASE=true
            FORMATTED_RELEASE_NOTES=$(echo -e "- Due to extensive code refactoring, you might encounter unexpected bugs in this version, feedback in [Telegram](https://t.me/kowchannel) or [create issue](https://github.com/KOWX712/Tricky-Addon-Update-Target-List/issues) if you found any issues.\n---\n### Tricky Addon module\n$RELEASE_NOTES")
          else
            PRERELEASE=false
            FORMATTED_RELEASE_NOTES=$(echo -e "### Tricky Addon module\n$RELEASE_NOTES\n")
          fi

          echo "CURRENT_TAG=$VERSION" >> $GITHUB_ENV
          echo "ZIP_NAME=TrickyAddonModule-${VERSION}.zip" >> $GITHUB_ENV
          echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
          echo "$FORMATTED_RELEASE_NOTES" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV
          echo "PRERELEASE=$PRERELEASE" >> $GITHUB_ENV

      - name: Compress module folder
        run: |
          cd module && zip -r "../${{ env.ZIP_NAME }}" ./*

      - name: Create release
        uses: softprops/action-gh-release@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          files: ${{ env.ZIP_NAME }}
          tag_name: ${{ env.CURRENT_TAG }}
          name: ${{ env.CURRENT_TAG }}
          body: ${{ env.RELEASE_NOTES }}
          draft: false
          prerelease: ${{ env.PRERELEASE }}