#!/usr/bin/env bash
set -euo pipefail

die() { echo "ERROR: $*" >&2; exit 1; }
need_file() { [[ -f "$1" ]] || die "Missing file: $1"; }
need_dir() { [[ -d "$1" ]] || die "Missing directory: $1"; }

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

ARMBIAN_BUILD_DIR="${ARMBIAN_BUILD_DIR:-/home/dmn/d100/armbian/build}"
WORKTREE_DIR="${WORKTREE_DIR:-$ARMBIAN_BUILD_DIR/cache/sources/linux-kernel-worktree/6.1__rk35xx__arm64}"
PATCH_DIR="${PATCH_DIR:-$ARMBIAN_BUILD_DIR/userpatches/kernel/rk35xx-vendor-6.1}"

SRC_DTS="${SRC_DTS:-$SCRIPT_DIR/rk3568-napi2.dts}"

KERNEL_DTS_REL="arch/arm64/boot/dts/rockchip/rk3568-napi2.dts"
KERNEL_MAKEFILE_REL="arch/arm64/boot/dts/rockchip/Makefile"

PATCH_MAKEFILE_NAME="${PATCH_MAKEFILE_NAME:-0001-rockchip-rk3568-napi2-makefile.patch}"
PATCH_DTS_NAME="${PATCH_DTS_NAME:-0100-rockchip-rk3568-napi2-dts.patch}"

need_dir "$ARMBIAN_BUILD_DIR"
need_dir "$WORKTREE_DIR"
need_dir "$PATCH_DIR"
need_file "$SRC_DTS"

cd "$WORKTREE_DIR"
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || die "Not a git worktree: $WORKTREE_DIR"

KERNEL_MAKEFILE="$WORKTREE_DIR/$KERNEL_MAKEFILE_REL"
need_file "$KERNEL_MAKEFILE"

mkdir -p "$PATCH_DIR"

echo "[1/4] Copy main DTS into kernel worktree"
install -m 0644 "$SRC_DTS" "$WORKTREE_DIR/$KERNEL_DTS_REL"

echo "[2/4] Ensure main Makefile contains rk3568-napi2.dtb (only if missing)"
if ! grep -qE '(^|[[:space:]])rk3568-napi2\.dtb($|[[:space:]]|\\)' "$KERNEL_MAKEFILE"; then
  echo "      inserting dtb line into Makefile"
  printf "\n%s\n" 'dtb-$(CONFIG_ARCH_ROCKCHIP) += rk3568-napi2.dtb' >> "$KERNEL_MAKEFILE"
else
  echo "      already present"
fi

echo "[3/4] Generate DTS patch"
git reset -q
git add "$KERNEL_DTS_REL"
git diff --cached > "/tmp/$PATCH_DTS_NAME"
grep -q "$KERNEL_DTS_REL" "/tmp/$PATCH_DTS_NAME" || die "DTS patch does not reference $KERNEL_DTS_REL"
cp -v "/tmp/$PATCH_DTS_NAME" "$PATCH_DIR/$PATCH_DTS_NAME"

echo "[4/4] Generate Makefile patch (only if Makefile changed)"
git reset -q
git add "$KERNEL_MAKEFILE_REL"
if git diff --cached --name-only | grep -qx "$KERNEL_MAKEFILE_REL"; then
  git diff --cached > "/tmp/$PATCH_MAKEFILE_NAME"
  cp -v "/tmp/$PATCH_MAKEFILE_NAME" "$PATCH_DIR/$PATCH_MAKEFILE_NAME"
  echo "      saved $PATCH_MAKEFILE_NAME"
else
  echo "      Makefile unchanged, skip"
fi

echo "Done. Patches in: $PATCH_DIR"

