#!/usr/bin/env bash

set -euo pipefail

SCRIPT_PATH="${BASH_SOURCE[0]:-$0}"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
REPOSITORY_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SKIA_DIR="${1:-$REPOSITORY_ROOT/dependencies/skia/m150-1f14f1166a}"
PATCH_FILE="$SCRIPT_DIR/patches/skia-m150-ohos.patch"
EXPECTED_COMMIT="1f14f1166a847cb0e148f981600bf1e3e6ca6e46"

if [ ! -d "$SKIA_DIR/.git" ]; then
  echo "[skia] ERROR: Skia checkout not found: $SKIA_DIR"
  exit 1
fi

ACTUAL_COMMIT="$(git -C "$SKIA_DIR" rev-parse HEAD)"
if [ "$ACTUAL_COMMIT" != "$EXPECTED_COMMIT" ]; then
  echo "[skia] ERROR: expected m150 commit $EXPECTED_COMMIT, found $ACTUAL_COMMIT"
  exit 1
fi

if git -C "$SKIA_DIR" apply --reverse --check "$PATCH_FILE" >/dev/null 2>&1; then
  echo "[skia] OHOS m150 patch is already applied."
  exit 0
fi

git -C "$SKIA_DIR" apply --check "$PATCH_FILE"
git -C "$SKIA_DIR" apply "$PATCH_FILE"
echo "[skia] Applied OHOS m150 patch to $SKIA_DIR"
