name: build

on:
  push:
    tags:
      - 'v*'
env:
  IS_STABLE: ${{ !contains(github.ref, '-') }}

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Setup Flutter
        uses: subosito/flutter-action@v2
        with:
          channel: stable
          flutter-version: 3.41.9
          cache: true

      - name: Install dependencies
        run: flutter pub get

      - name: Analyze
        run: flutter analyze --no-fatal-infos

      - name: Run tests
        run: flutter test --reporter expanded

  build:
    needs: [ test ]
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - platform: android
            os: ubuntu-latest
          - platform: windows
            os: Windows-2022
            arch: amd64
          - platform: linux
            os: ubuntu-22.04
            arch: amd64
          - platform: macos
            os: macos-15-intel
            arch: amd64
          - platform: macos
            os: macos-latest
            arch: arm64
          - platform: windows
            os: windows-11-arm
            arch: arm64
          - platform: linux
            os: ubuntu-24.04-arm
            arch: arm64

    steps:
      - name: Setup rust
        if: startsWith(matrix.os, 'windows-11-arm')
        run: |
          Invoke-WebRequest -Uri "https://win.rustup.rs/aarch64" -OutFile rustup-init.exe
          .\rustup-init.exe -y --default-toolchain stable
          $cargoPath = "$env:USERPROFILE\.cargo\bin"
          Add-Content $env:GITHUB_PATH $cargoPath

      - name: Checkout
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Setup Android Signing
        if: startsWith(matrix.platform,'android')
        run: |
          echo "${{ secrets.KEYSTORE }}" | base64 --decode > android/app/keystore.jks
          echo "${{ secrets.SERVICE_JSON }}" | base64 --decode > android/app/google-services.json
          echo "keyAlias=${{ secrets.KEY_ALIAS }}" >> android/local.properties
          echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> android/local.properties
          echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> android/local.properties

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.24.0'
          cache-dependency-path: |
            core/go.sum

      - name: Enable git long paths (Windows)
        if: startsWith(matrix.os, 'windows')
        run: git config --global core.longpaths true

      - name: Setup Flutter
        if: ${{ !(startsWith(matrix.os, 'windows-11-arm') || startsWith(matrix.os, 'ubuntu-24.04-arm')) }}
        uses: subosito/flutter-action@v2
        with:
          channel: stable
          flutter-version: 3.41.9
          cache: true
      - name: Setup Flutter With Other
        if: startsWith(matrix.os, 'windows-11-arm') || startsWith(matrix.os, 'ubuntu-24.04-arm')
        uses: subosito/flutter-action@v2
        with:
          channel: master
          flutter-version: 3.44.0-0.1.pre
          cache: true

      - name: Setup NDK
        if: startsWith(matrix.platform,'android')
        uses: nttld/setup-ndk@v1
        with:
          ndk-version: r28c
          add-to-path: true
          link-to-sdk: true

      - name: Get Flutter Dependency
        run: |
          flutter --version
          flutter pub get

      - name: Setup
        run: dart setup.dart ${{ matrix.platform }} ${{ env.IS_STABLE == 'true' && '--env stable' || '' }} -v

      - name: Upload
        uses: actions/upload-artifact@v4
        with:
          name: artifact-${{ matrix.platform }}${{ matrix.arch && format('-{0}', matrix.arch) }}
          path: ./dist
          overwrite: true

  changelog:
    runs-on: ubuntu-latest
    needs: [ build ]
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        if: ${{ env.IS_STABLE == 'true' }}
        with:
          fetch-depth: 0
          ref: refs/heads/main
      - name: Generate
        if: ${{ env.IS_STABLE == 'true' }}
        run: |
          last_ver=$(grep -m1 '^## ' CHANGELOG.md 2>/dev/null | sed 's/^## //')
          
          tags=($(git tag --merged HEAD --sort=-creatordate))
          
          temp="NEW_CHANGELOG.md" > "$temp"
          
          for i in "${!tags[@]}"; do
              curr="${tags[i]}"
              [[ "$curr" == "$last_ver" ]] && break
          
              prev="${tags[i+1]}"
              range="${prev:+$prev..}$curr"
          
              echo -e "## $curr\n" >> "$temp"
              git log --no-merges --pretty=format:"%B" "$range" | \
              awk '!/Update changelog/ && NF {print "- " $0 "\n"}' >> "$temp"
          done
          [ -f CHANGELOG.md ] && cat CHANGELOG.md >> "$temp"
          
          mv "$temp" CHANGELOG.md

      - name: Commit
        if: ${{ env.IS_STABLE == 'true' }}
        run: |
          git add CHANGELOG.md
          if ! git diff --cached --quiet; then
            echo "Commit pushing"
            git config --local user.email "chen08209@gmail.com"
            git config --local user.name "chen08209"
            git commit -m "Update changelog"
            git push
            if [ $? -eq 0 ]; then
              echo "Push succeeded"
            else
              echo "Push failed"
              exit 1
            fi
          fi

        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  upload:
    permissions: write-all
    needs: [ build ]
    runs-on: ubuntu-latest
    services:
      telegram-bot-api:
        image: aiogram/telegram-bot-api:latest
        env:
          TELEGRAM_API_ID: ${{ secrets.TELEGRAM_API_ID }}
          TELEGRAM_API_HASH: ${{ secrets.TELEGRAM_API_HASH }}
        ports:
          - 8081:8081
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Download
        uses: actions/download-artifact@v4
        with:
          path: ./dist/
          pattern: artifact-*
          merge-multiple: true

      - name: Generate release.md
        run: |
          tags=($(git tag --merged HEAD --sort=-creatordate))
          preTag=$(curl -s "https://api.github.com/repos/chen08209/FlClash/releases/latest" | \
          sed -nE 's/.*"tag_name": "([^"]+)".*/\1/p')
          
          [ -z "$preTag" ] && preTag=""
          
          out="release.md" > "$out"
          
          for i in "${!tags[@]}"; do
            curr="${tags[i]}"
            [[ "$curr" == "$preTag" ]] && break
          
            prev="${tags[i+1]}"
            range="${prev:+$prev..}$curr"
          
            git log --no-merges --pretty=format:"%B" "$range" | \
            awk '!/Update changelog/ && NF {print "- " $0 "\n"}' >> "$out"
          done
      - name: Push to telegram
        env:
          TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
          TAG: ${{ github.ref_name }}
          RUN_ID: ${{ github.run_id }}
        run: |
          python -m pip install --upgrade pip
          pip install requests
          python release_telegram.py

      - name: Patch release.md
        run: |
          version=$(echo "${{ github.ref_name }}" | sed 's/^v//')
          sed "s|VERSION|$version|g" ./.github/release_template.md >> release.md

      - name: Generate sha256
        if: ${{ env.IS_STABLE == 'true' }}
        run: |
          cd ./dist
          sha256sum * > SHA256SUMS

      - name: Release
        if: ${{ env.IS_STABLE == 'true' }}
        uses: softprops/action-gh-release@v2
        with:
          files: ./dist/*
          body_path: './release.md'

      - name: Create Fdroid Source Dir
        if: ${{ env.IS_STABLE == 'true' }}
        run: |
          mkdir -p ./tmp
          cp ./dist/*android-arm64-v8a* ./tmp/ || true
          echo "Files copied successfully"

      - name: Push to fdroid repo
        if: ${{ env.IS_STABLE == 'true' }}
        uses: cpina/github-action-push-to-another-repository@v1.7.2
        env:
          SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
        with:
          source-directory: ./tmp/
          destination-github-username: chen08209
          destination-repository-name: FlClash-fdroid-repo
          user-name: 'github-actions[bot]'
          user-email: 'github-actions[bot]@users.noreply.github.com'
          target-branch: main
          commit-message: Update from ${{ github.ref_name }}
          target-directory: /tmp/
