name: ohos

on:
  push:
    branches: [develop, main, "releases/**", "ohos/**"]
    tags:
      - "v*"
      - "!*-pre"
  pull_request:
    branches: [develop, main, "ohos/**"]
    types: [opened, synchronize, reopened, ready_for_review]
  workflow_dispatch:
    inputs:
      publish:
        description: Publish this non-main branch and dispatch downstream builds
        required: false
        default: false
        type: boolean

permissions:
  contents: read
  pull-requests: read

env:
  CARGO_TERM_COLOR: always

defaults:
  run:
    shell: bash

jobs:
  ohos:
    name: ohos
    if: github.event_name != 'pull_request' || !github.event.pull_request.draft
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Set up Rust
        uses: ./.github/actions/prepare-build
        with:
          target: aarch64-unknown-linux-ohos
          gui: false
          pnpm: false
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up HarmonyOS
        uses: ErBWs/setup-ohos@v1

      - name: Install ohrs
        uses: taiki-e/install-action@v2
        with:
          tool: ohrs

      - name: Build HAR
        id: package
        env:
          DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
        run: |
          set -euo pipefail
          sudo apt-get install -qqy \
            pkg-config curl libgl1-mesa-dev expect llvm clang lldb lld
          rustup component add rustfmt
          cargo fmt --all --manifest-path \
            easytier-contrib/easytier-ohrs/Cargo.toml -- --check

          cargo_version=$(cargo metadata --format-version 1 --no-deps \
            --manifest-path easytier/Cargo.toml | jq -r '.packages[0].version')
          last_tag=$(git describe --tags --abbrev=0 HEAD 2>/dev/null || true)
          if [ -n "$last_tag" ]; then
            base_version=$(printf '%s\n' "$cargo_version" "${last_tag#v}" \
              | sort -V | tail -n 1)
            commit_count=$(git rev-list --count "$last_tag..HEAD")
          else
            base_version=$cargo_version
            commit_count=0
          fi

          source_branch=${GITHUB_HEAD_REF:-}
          if [ -z "$source_branch" ]; then
            if [ "$GITHUB_REF_TYPE" = branch ]; then
              source_branch=$GITHUB_REF_NAME
            else
              source_branch=${DEFAULT_BRANCH:-main}
            fi
          fi
          branch_id=$(printf '%s' "$source_branch" \
            | tr '[:upper:]' '[:lower:]' \
            | sed -E 's/[^a-z0-9-]+/-/g; s/^-+//; s/-+$//' \
            | cut -c1-64)
          branch_id=${branch_id:-main}

          package_name=easytier-ohrs
          package_version="${base_version}-${branch_id}-${commit_count}-${GITHUB_RUN_NUMBER}-${GITHUB_RUN_ATTEMPT}-g$(git rev-parse --short=8 HEAD)"
          echo "name=$package_name" >> "$GITHUB_OUTPUT"
          echo "EASYTIER_PACKAGE_NAME=$package_name" >> "$GITHUB_ENV"
          echo "EASYTIER_VERSION=$package_version" >> "$GITHUB_ENV"

          package_dir=easytier-contrib/easytier-ohrs/package
          jq --arg name "$package_name" --arg version "$package_version" \
            '.name = $name | .version = $version' \
            "$package_dir/oh-package.json5" > "$package_dir/oh-package.tmp.json5"
          mv "$package_dir/oh-package.tmp.json5" "$package_dir/oh-package.json5"
          {
            echo "## $package_name $package_version"
            echo
            echo "- Core version: $base_version"
            echo "- Core commit: $GITHUB_SHA"
            git log -1 --pretty=format:'- %s'
            echo
          } > "$package_dir/CHANGELOG.md"

          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"

          cd easytier-contrib/easytier-ohrs
          source env.sh
          ohrs build --release --arch aarch
          ohrs artifact
          mv package.har "$package_name.har"

      - name: Upload HAR
        uses: actions/upload-artifact@v5
        with:
          name: ${{ steps.package.outputs.name }}
          path: easytier-contrib/easytier-ohrs/${{ steps.package.outputs.name }}.har
          retention-days: 5
          if-no-files-found: error

      - name: Publish and dispatch
        if: >-
          (github.event_name == 'push' &&
           github.ref_type == 'branch' &&
           github.ref_name == 'main' &&
           github.event.forced != true) ||
          (github.event_name == 'workflow_dispatch' &&
           github.ref_type == 'branch' &&
           (github.ref_name == 'main' || inputs.publish))
        working-directory: easytier-contrib/easytier-ohrs
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CODEARTS_PRIVATE_OHPM: ${{ secrets.CODEARTS_PRIVATE_OHPM }}
          DOWNSTREAM_DISPATCH_TOKEN: ${{ secrets.DOWNSTREAM_DISPATCH_TOKEN }}
        run: |
          set -euo pipefail
          if [ "$GITHUB_EVENT_NAME" = push ]; then
            pull_requests=$(gh api \
              -H "Accept: application/vnd.github+json" \
              "/repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls")
            if ! jq -e \
              --arg repository "$GITHUB_REPOSITORY" \
              --arg branch "$GITHUB_REF_NAME" \
              --arg sha "$GITHUB_SHA" \
              'any(.[];
                .merged_at != null and
                .base.repo.full_name == $repository and
                .base.ref == $branch and
                .merge_commit_sha == $sha)' \
              <<< "$pull_requests" >/dev/null; then
              echo "Direct push: HAR built without publishing."
              exit 0
            fi
          fi

          mkdir -p "$HOME/.ohpm"
          umask 077
          printf '%s' "$CODEARTS_PRIVATE_OHPM" > "$HOME/.ohpm/.ohpmrc"
          trap 'rm -f "$HOME/.ohpm/.ohpmrc"' EXIT
          ohpm publish "$EASYTIER_PACKAGE_NAME.har"

          payload=$(jq -nc \
            --arg repository "$GITHUB_REPOSITORY" \
            --arg ref "refs/heads/$GITHUB_REF_NAME" \
            --arg package "$EASYTIER_PACKAGE_NAME" \
            '{
              event_type: "core-har-published",
              client_payload: {
                core_repository: $repository,
                core_ref: $ref,
                package_name: $package
              }
            }')
          for repository in \
            FrankHan052176/EasyTier-ArkTS \
            FrankHan052176/easytier-pro-app; do
            curl --fail-with-body --silent --show-error \
              -X POST \
              -H "Accept: application/vnd.github+json" \
              -H "Authorization: Bearer $DOWNSTREAM_DISPATCH_TOKEN" \
              -H "X-GitHub-Api-Version: 2022-11-28" \
              "$GITHUB_API_URL/repos/$repository/dispatches" \
              --data "$payload"
          done
