#!/usr/bin/env bash
# Put KernelSU-Next into kernel/samsung/exynos9820, pinned, idempotently.
# Usage: kernel/ksu.sh <android-source-root>
#
# v3.3.0 is pinned on purpose: it is the manager version already on the phone
# (KernelSU_Next_v3.3.0_33214), and manager/kernel versions must agree.
# Bumping it is a two-line change here plus a manager update on the phone.
set -euo pipefail
KSU_TAG=v3.3.0
SRC=${1:?usage: ksu.sh <android-source-root>}
K="$SRC/kernel/samsung/exynos9820"
HERE=$(cd "$(dirname "$0")" && pwd)
[ -d "$K/drivers" ] || { echo "ksu: no kernel at $K" >&2; exit 2; }

cd "$K"
if [ -d KernelSU-Next/.git ] && [ "$(git -C KernelSU-Next describe --tags --exact-match 2>/dev/null)" = "$KSU_TAG" ] \
   && [ -L drivers/kernelsu ] && grep -q kernelsu drivers/Makefile; then
  echo "ksu: $KSU_TAG already set up"
else
  # The upstream script clones the repo, links drivers/kernelsu and edits
  # drivers/Makefile + drivers/Kconfig; it is what KernelSU-Next documents.
  curl -fsSL "https://raw.githubusercontent.com/KernelSU-Next/KernelSU-Next/$KSU_TAG/kernel/setup.sh" | bash -s "$KSU_TAG"
fi

install -m 0644 "$HERE/vanta.config" arch/arm64/configs/vanta.config
grep -q '^CONFIG_KPROBES=y' arch/arm64/configs/exynos9820-beyond2lte_defconfig \
  || echo "ksu: WARNING defconfig lacks CONFIG_KPROBES=y; vanta.config forces it, verify the merged .config" >&2
echo "ksu: ok ($KSU_TAG, fragment arch/arm64/configs/vanta.config)"
