name: EasyTier OHOS

on:
  push:
    branches: ["develop", "main", "releases/**"]
    tags:
      - 'v*'
      - '!*-pre'
  pull_request:
    branches: ["develop", "main"]
    types: [opened, synchronize, reopened, ready_for_review]
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

env:
  CARGO_TERM_COLOR: always

defaults:
  run:
    # necessary for windows
    shell: bash

jobs:
  cargo_fmt_check:
    if: github.event_name != 'pull_request' || !github.event.pull_request.draft
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - name: fmt check
        working-directory: ./easytier-contrib/easytier-ohrs
        run: |
          bash ../../.github/workflows/install_rust.sh
          rustup component add rustfmt
          cargo fmt --all -- --check
  pre_job:
    # continue-on-error: true # Uncomment once integration is finished
    runs-on: ubuntu-latest
    if: github.event_name != 'pull_request' || !github.event.pull_request.draft
    # Map a step output to a job output
    outputs:
      # do not skip push on branch starts with releases/
      should_skip: ${{ steps.skip_check.outputs.should_skip == 'true' && !startsWith(github.ref_name, 'releases/') }}
    steps:
      - id: skip_check
        uses: fkirc/skip-duplicate-actions@v5
        with:
          # All of these options are optional, so you can remove them if you are happy with the defaults
          concurrent_skipping: "same_content_newer"
          skip_after_successful_duplicate: "true"
          cancel_others: "true"
          paths: '["Cargo.toml", "Cargo.lock", "easytier/**", "easytier-contrib/easytier-ohrs/**", ".github/workflows/ohos.yml", ".github/workflows/install_rust.sh"]'
  build-ohos:
    runs-on: ubuntu-latest
    needs: pre_job
    env:
      OHPM_PUBLISH_CODE: ${{ secrets.OHPM_PUBLISH_CODE }}
    if: needs.pre_job.outputs.should_skip != 'true'
    steps:
      - uses: actions/checkout@v5
      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            build-essential \
            wget \
            unzip \
            git \
            pkg-config curl libgl1-mesa-dev expect
          sudo apt-get clean

      - name: Resolve easytier version
        run: |
          set -e
      
          UPSTREAM_REPO="https://github.com/EasyTier/EasyTier.git"
      
          git remote add upstream "$UPSTREAM_REPO" 2>/dev/null || true
          git fetch --unshallow upstream main || git fetch upstream main
          git fetch --tags upstream --force
      
          # 读取 cargo 版本
          CARGO_VERSION=$(cargo metadata --format-version 1 --no-deps --manifest-path easytier/Cargo.toml \
            | jq -r '.packages[0].version')
      
          # 获取 upstream/main 最新 tag
          LAST_TAG=$(git describe --tags --abbrev=0 upstream/main 2>/dev/null || echo "")
          LAST_TAG_VERSION="${LAST_TAG#v}"
      
          # 语义版本比较
          version_gt() {
            [ "$(printf '%s\n' "$1" "$2" | sort -V | tail -n1)" = "$1" ] && [ "$1" != "$2" ]
          }
      
          if [ -z "$LAST_TAG_VERSION" ]; then
            BASE_VERSION="$CARGO_VERSION"
            DIFF_COUNT=$(git rev-list --count upstream/main)
          elif version_gt "$CARGO_VERSION" "$LAST_TAG_VERSION"; then
            BASE_VERSION="$CARGO_VERSION"
            DIFF_COUNT=0
          else
            BASE_VERSION="$LAST_TAG_VERSION"
            DIFF_COUNT=$(git rev-list --count "${LAST_TAG}..upstream/main")
          fi
      
          COMMIT_HASH=$(git rev-parse --short upstream/main)
          EASYTIER_VERSION="${BASE_VERSION}-${DIFF_COUNT}-${COMMIT_HASH}"
      
          echo "EASYTIER_VERSION=$EASYTIER_VERSION"
          echo "EASYTIER_VERSION=$EASYTIER_VERSION" >> $GITHUB_ENV
      
          cd ./easytier-contrib/easytier-ohrs/package
          jq --arg v "$EASYTIER_VERSION" '.version = $v' oh-package.json5 > oh-package.tmp.json5
          mv oh-package.tmp.json5 oh-package.json5


      - name: Generate CHANGELOG.md for current commit
        working-directory: ./easytier-contrib/easytier-ohrs/package
        run: |
          {
            echo "## easytier-ohrs ${EASYTIER_VERSION}"
            echo
            git log -1 --pretty=format:"- %s"
            echo
          } > CHANGELOG.md

      - name: Setup HarmonyOS CLI tools
        uses: ErBWs/setup-ohos@v1

      - name: Download and Extract Custom SDK
        run: |
          wget https://github.com/FrankHan052176/Easytier-OHOS-sdk/releases/download/v1/ohos-sdk.zip -O /tmp/ohos-sdk.zip
          sudo unzip -o /tmp/ohos-sdk.zip -d /tmp/custom-sdk
          sudo cp -rf /tmp/custom-sdk/linux/native/* $OHOS_NDK_HOME/native
          echo "Custom SDK files deployed to $OHOS_NDK_HOME/native"
          ls -a $OHOS_NDK_HOME/native

      - name: Setup build environment
        run: |
          echo "TARGET_ARCH=aarch64-linux-ohos" >> $GITHUB_ENV

      - name: Create clang wrapper script
        run: |
          sudo mkdir -p $OHOS_NDK_HOME/native/llvm
          sudo tee $OHOS_NDK_HOME/native/llvm/aarch64-unknown-linux-ohos-clang.sh > /dev/null <<'EOF'
          #!/bin/sh
          exec $OHOS_NDK_HOME/native/llvm/bin/clang \
            -target aarch64-linux-ohos \
            --sysroot=$OHOS_NDK_HOME/native/sysroot \
            -D__MUSL__ \
            "$@"
          EOF
          sudo chmod +x $OHOS_NDK_HOME/native/llvm/aarch64-unknown-linux-ohos-clang.sh

      - name: Build latest Har
        working-directory: ./easytier-contrib/easytier-ohrs
        run: |
          sudo apt-get install -y llvm clang lldb lld
          sudo apt-get install -y protobuf-compiler
          bash ../../.github/workflows/install_rust.sh
          source env.sh
          cargo install ohrs
          rustup target add aarch64-unknown-linux-ohos
          cargo update easytier
          ohrs doctor
          ohrs build --release --arch aarch
          ohrs artifact
          mv package.har easytier-ohrs.har

      - name: Build Release Package
        if: startsWith(github.ref, 'refs/tags/')
        working-directory: ./easytier-contrib/easytier-ohrs
        run: |
          echo "🎉 Official Release detected. Building easytier-release..."
          TAG_NAME="${{ github.ref_name }}"
          TAG_VERSION="${TAG_NAME#v}"
          echo "Release Version: $TAG_VERSION"
          cd package
          jq --arg v "$TAG_VERSION" '.name = "easytier-release" | .version = $v' oh-package.json5 > oh-package.tmp.json5 && mv oh-package.tmp.json5 oh-package.json5
          cd ..
          ohrs build --release --arch aarch
          cd dist/arm64-v8a
          mv libeasytier_ohrs.so libeasytier_release.so
          cd ../..
          ohrs artifact
          mv package.har easytier-release.har

      - name: Upload artifact
        uses: actions/upload-artifact@v5
        with:
          name: easytier-ohos
          path: |
            ./easytier-contrib/easytier-ohrs/easytier-ohrs.har
          retention-days: 5
          if-no-files-found: error

      - name: Publish To Center Ohpm
        working-directory: ./easytier-contrib/easytier-ohrs
        env:
          OHPM_PRIVATE_KEY: ${{ secrets.OHPM_PRIVATE_KEY }}
          OHPM_KEY_PASSPHRASE: ${{ secrets.OHPM_KEY_PASSPHRASE }}
        if: ${{ env.OHPM_PUBLISH_CODE != '' && github.event_name == 'push' }}
        run: |
          ohpm config set publish_id "$OHPM_PUBLISH_CODE"
          ohpm config set publish_registry https://ohpm.openharmony.cn/ohpm
          TMP_DIR=$(mktemp -d)
          PRIVATE_KEY_FILE="$TMP_DIR/private_key"
          printf '%s' "$OHPM_PRIVATE_KEY" > "$PRIVATE_KEY_FILE"
          chmod 600 "$PRIVATE_KEY_FILE"
          ohpm config set key_path $PRIVATE_KEY_FILE
          unzip ohpm_crypto.zip -d /home/runner/work/
          ohpm config set crypto_path /home/runner/work/ohpm_crypto
          chmod 755 /home/runner/work/ohpm_crypto/*
          PASSPHRASE="$(printf '%s' "$OHPM_KEY_PASSPHRASE" | tr -d '\r\n')"
          ohpm config set key_passphrase "$PASSPHRASE"
          ohpm publish easytier-ohrs.har
          
      - name: Publish To Private Ohpm
        working-directory: ./easytier-contrib/easytier-ohrs
        if: ${{ env.OHPM_PUBLISH_CODE != '' && github.event_name == 'push' }}
        run: |
          printf '%s' "${{ secrets.CODEARTS_PRIVATE_OHPM }}" > ~/.ohpm/.ohpmrc
          ohpm config set strict_ssl false
          ohpm publish easytier-ohrs.har
          if [ -f "easytier-release.har" ]; then
             echo "🚀 Publishing Release package..."
             ohpm publish easytier-release.har
          fi
          curl --header "Content-Type: application/json" --request POST --data "{}" ${{ secrets.CODEARTS_WEBHOOKS }}

