#!/usr/bin/env bash
set -u

PATCH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$PATCH_DIR")"
PATCH_DIR="$ROOT_DIR/patches"

apply_patch_once() {
  local target_dir="$1"
  local patch_file="$2"

  if [[ ! -d "$target_dir/.git" ]]; then
    echo "[FAIL] target repo not found: $target_dir" >&2
    return 2
  fi

  if [[ ! -f "$patch_file" ]]; then
    echo "[FAIL] patch not found: $patch_file" >&2
    return 2
  fi

  git -C "$target_dir" apply --check "$patch_file" >/dev/null 2>&1 \
    && git -C "$target_dir" apply "$patch_file" >/dev/null 2>&1 \
    || git -C "$target_dir" apply --reverse --check "$patch_file" >/dev/null 2>&1
}

apply_patch_once "$ROOT_DIR/src/upstream/FAST_LIO" "$PATCH_DIR/fast_lio.patch"
apply_patch_once "$ROOT_DIR/src/upstream/livox_sdk" "$PATCH_DIR/livox_sdk.patch"
apply_patch_once "$ROOT_DIR/src/upstream/livox_ros_driver2" "$PATCH_DIR/livox_ros_driver2.patch"
apply_patch_once "$ROOT_DIR/src/upstream/slam_gmapping" "$PATCH_DIR/slam_gmapping.patch"
apply_patch_once "$ROOT_DIR/src/upstream/unilidar_sdk2" "$PATCH_DIR/unilidar_sdk2.patch"
