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

die() { echo "ERROR: $*" >&2; exit 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}"

OVERLAY_SRC_DIR="${OVERLAY_SRC_DIR:-$SCRIPT_DIR/overlays}"

KERNEL_OVERLAY_DIR_REL="${KERNEL_OVERLAY_DIR_REL:-arch/arm64/boot/dts/rockchip/overlay}"
KERNEL_OVERLAY_MAKEFILE_REL="${KERNEL_OVERLAY_MAKEFILE_REL:-$KERNEL_OVERLAY_DIR_REL/Makefile}"

PATCH_OVERLAY_MK="${PATCH_OVERLAY_MK:-0190-rockchip-overlay-makefile.patch}"
PATCH_NUM_START="${PATCH_NUM_START:-200}"

need_dir "$WORKTREE_DIR"
need_dir "$PATCH_DIR"
need_dir "$OVERLAY_SRC_DIR"

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

KERNEL_OVERLAY_DIR="$WORKTREE_DIR/$KERNEL_OVERLAY_DIR_REL"
KERNEL_OVERLAY_MAKEFILE="$WORKTREE_DIR/$KERNEL_OVERLAY_MAKEFILE_REL"
mkdir -p "$KERNEL_OVERLAY_DIR"

# Ensure overlay Makefile exists
if [[ ! -f "$KERNEL_OVERLAY_MAKEFILE" ]]; then
  die "Overlay Makefile not found: $KERNEL_OVERLAY_MAKEFILE_REL (kernel tree mismatch?)"
fi

# Detect dtbo list variable by always-y line (most reliable for dtbs_install)
DTBO_VAR="dtbo-y"
if grep -qE '^[[:space:]]*always-y[[:space:]]*:=[[:space:]]*.*\$\((dtbo-m)\)' "$KERNEL_OVERLAY_MAKEFILE"; then
  DTBO_VAR="dtbo-m"
elif grep -qE '^[[:space:]]*always-y[[:space:]]*:=[[:space:]]*.*\$\((dtbo-y)\)' "$KERNEL_OVERLAY_MAKEFILE"; then
  DTBO_VAR="dtbo-y"
fi
echo "Using dtbo list variable: $DTBO_VAR"

# Gather overlays
shopt -s nullglob
overlays=( "$OVERLAY_SRC_DIR"/*.dts )
shopt -u nullglob
(( ${#overlays[@]} > 0 )) || die "No overlays (*.dts) in $OVERLAY_SRC_DIR"

# ---------- Step 1: copy & optionally fix overlays, build list of dtbos ----------
dtbos=()
for src in "${overlays[@]}"; do
  base="$(basename "$src")"
  name="${base%.dts}"
  dtbo="${name}.dtbo"
  dtbos+=( "$dtbo" )

  dst_rel="$KERNEL_OVERLAY_DIR_REL/$base"
  dst_abs="$WORKTREE_DIR/$dst_rel"

  echo "Copy overlay: $base"
  install -m 0644 "$src" "$dst_abs"

  # Fix common overlay errors (safe, only if patterns exist)
  # 1) target-path = <&foo>;  -> target = <&foo>;
  # 2) overlay { ... }        -> __overlay__ { ... }
  if grep -qE 'target-path[[:space:]]*=[[:space:]]*<\&' "$dst_abs"; then
    sed -i -E 's/target-path[[:space:]]*=[[:space:]]*<\&/target = <\&/g' "$dst_abs"
  fi
  if grep -qE '^[[:space:]]*overlay[[:space:]]*\{' "$dst_abs"; then
    sed -i -E 's/^([[:space:]]*)overlay[[:space:]]*\{/\1__overlay__ {/' "$dst_abs"
  fi
done

# ---------- Step 2: update overlay Makefile ONCE (dedup, insert before targets) ----------
# ---------- Step 2: update overlay Makefile ONCE (dedup, insert before targets) ----------
echo "STEP2:Update overlay Makefile once (dedup, insert before targets)"

sed -i '/^dtbo-\$(CONFIG_ARCH_ROCKCHIP)[[:space:]]\++=.*\.dtbo$/d' "$KERNEL_OVERLAY_MAKEFILE"

to_add=()
for dtbo in "${dtbos[@]}"; do
  if ! grep -qF "$dtbo" "$KERNEL_OVERLAY_MAKEFILE"; then
    to_add+=( "$dtbo" )
  fi
done

if (( ${#to_add[@]} == 0 )); then
  echo "  nothing to add"
else
  tmp="$(mktemp)"

  # сформируем блок с гарантированным \n в конце каждой строки
  block="$(printf 'dtbo-y += %s\n' "${to_add[@]}")"

echo "---$block"

  awk -v block="$block" '
    BEGIN { inserted=0 }
    $0 ~ /^targets[[:space:]]+\+?=[[:space:]]+\$\((dtbo-y)\)/ && inserted==0 {
      printf "%s\n\n bbbb", block
      inserted=1
    }
    { print }
    END {
      if (inserted==0) {
        printf "%s\n\n bbbb ", block
      }
    }
  ' "$KERNEL_OVERLAY_MAKEFILE" > "$tmp"

  cat "$tmp" > "$KERNEL_OVERLAY_MAKEFILE"
  rm -f "$tmp"
fi

# ---------- Step 3: generate overlay Makefile patch ----------
echo "Generate patch: $PATCH_OVERLAY_MK"
git reset -q
git add "$KERNEL_OVERLAY_MAKEFILE_REL"
if git diff --cached --name-only | grep -qx "$KERNEL_OVERLAY_MAKEFILE_REL"; then
  git diff --cached > "/tmp/$PATCH_OVERLAY_MK"
  cp -v "/tmp/$PATCH_OVERLAY_MK" "$PATCH_DIR/$PATCH_OVERLAY_MK"
else
  echo "Overlay Makefile unchanged; not writing $PATCH_OVERLAY_MK"
fi

# ---------- Step 4: generate one patch per overlay DTS (NO Makefile inside) ----------
n="$PATCH_NUM_START"
for src in "${overlays[@]}"; do
  base="$(basename "$src")"
  name="${base%.dts}"

  dst_rel="$KERNEL_OVERLAY_DIR_REL/$base"

  patch_name="$(printf "%04d-rockchip-overlay-%s.patch" "$n" "$name")"

  echo "Generate patch: $patch_name"
  git reset -q
  git add "$dst_rel"
  git diff --cached > "/tmp/$patch_name"
  grep -q "$dst_rel" "/tmp/$patch_name" || die "Patch missing $dst_rel (unexpected)"
  cp -v "/tmp/$patch_name" "$PATCH_DIR/$patch_name"

  n=$((n+1))
done

echo "Done. Patches in: $PATCH_DIR"
echo "  - $PATCH_OVERLAY_MK (if Makefile changed)"
echo "  - $(printf "%04d" "$PATCH_NUM_START")... overlay patches"

