# Maintainer: Markus Fritsche <fritsche.markus@gmail.com>
# Forked from: linux-pinetab2 by Danct12 <danct12@disroot.org>
# Original Contributor: Jan Alexander Steffens (heftig) <heftig@archlinux.org>
#
# linux-pinetab2-danctnix-besser: linux-pinetab2 + the BESser
# bes2600 driver patchset (race-fix, lock-removal, attribution-restore,
# fossil-cleanup; +73% throughput vs the in-tree baseline).  Soft-upstream
# fork of linux-pinetab2 — drop-in replacement, same kernel version, only
# the bes2600 staging driver differs.  See git.reauktion.de/marfrit/besser
# and git.reauktion.de/marfrit/bes2600-dkms for full provenance.

pkgbase=linux-pinetab2-danctnix-besser
pkgver=7.0.danctnix1
pkgrel=6
pkgdesc='PineTab2 (BESser bes2600 driver patchset)'
_srcname=linux-pinetab2
_srctag=v${pkgver%.*}-${pkgver##*.}
arch=(aarch64)
_url_git="https://codeberg.org/DanctNIX/${_srcname}"
url="${_url_git}/commits/tag/$_srctag"
license=(GPL-2.0-only)
makedepends=(
  bc
  cpio
  gettext
  git
  libelf
  pahole
  perl
  python
  tar
  xz
)
options=(
  !debug
  !strip
)
source=(
  https://cdn.kernel.org/pub/linux/kernel/v${pkgver%%.*}.x/linux-${pkgver%.*}.tar.{xz,sign}
  ${_url_git}/releases/download/${_srctag}/${_srctag}.patch.zst{,.sig}
  0001-bes2600-defer-scan-and-soften-WARN-on-firmware-rejec.patch
  0002-bes2600-widen-scan-defer-backoff-to-30s-and-decay-co.patch
  0003-bes2600-recover-wedged-firmware-via-mmc_hw_reset-on-.patch
  0004-bes2600-gate-PM-indication-completion-on-pending-req.patch
  0005-bes2600-short-circuit-wake-handshake-when-chip-is-co.patch
  0006-bes2600-self-detect-when-firmware-does-not-honor-PSM.patch
  0007-bes2600-handle-multi-function-SDIO-cards-in-mmc_hw_r.patch
  0008-bes2600-pre-empt-AP-deauth-6-with-mac80211-reassoc-o.patch
  0009-bes2600-bus_reset-on-connection-loss-storm-to-dodge-.patch
  0010-bes2600-replace-a-set-of-atomic_add.patch
  0011-bes2600-fix-missing-destroy_workqueue-on-error-in-in.patch
  0012-bes2600-fix-concurrency-UAF-in-bes2600_hw_scan-and-s.patch
  0013-bes2600-drop-sdio_rx_work-relay-IRQ-bh-direct-no-rel.patch
  0014-bes2600-Patch-G-restore-SPDX-identifiers-ST-Ericsson.patch
  0015-bes2600-Patch-D-atomicize-ba_lock-counters-drop-the-.patch
  0016-bes2600-Patch-E-skip-ps_state_lock-when-PSM-known-di.patch
  0017-bes2600-Patch-C2-replace-ieee80211_rx_irqsafe-with-i.patch
  0018-bes2600-Patch-H-bh.c-hygiene-cleanup-drop-fossil-blo.patch
  0019-bes2600-take-pending_record_lock-with-_bh-to-fix-SOF.patch
  0020-bes2600-export-bus_reset-helpers-for-danctnix-bes260.patch
  0021-bes2600-bounce-sdio-tx-buffers.patch
  0022-bes2600-reset-firmware-state-on-wsm_join_confirm-fai.patch
  0002-bes2600-filter-5ghz-scan.patch
  config  # the main kernel config file
)
validpgpkeys=(
  ABAF11C65A2970B130ABE3C479BE3E4300411886  # Linus Torvalds
  647F28654894E3BD457199BE38DBBDC86092693E  # Greg Kroah-Hartman
  F09A933C0FE0331E558CA4E166CAB7EAA45DD781  # Danct12
)
b2sums=('3d9795083c8938f80f480de0d10bfd9c525640e59d5c7f22983de3f12ee42c84c31be902cafb05579ddb1c32bac5ed06b0d4953f9705450be185bd2d9ab08f89'
        'SKIP'
        '71fe98221e802b315e54b4b10d3e8c8f376695a36bae3541d876e5776a37f3fa33c8f8dfa6e51fcbd6f5396add02e5166634165f2351836a0ea0453c172fe56c'
        'SKIP'
        '5268f55c132441e1ef2e0042e48940a51556286c2e2813c99e983bf89606c2aa05df56e42ebd8bcfd201ceaf63493ca3f2639a39f926e8419b3bc27a4ac4aced'
        'ebf786a401b5883431068b7a88ff1890ff4f2936cfceb6560828ba202a548c0c6f1f89d721837f1b67e85165d4dd1a2973cbe97e396e1b258efe5288a17d1a81'
        'ddf0f8c052f7d40f324791353b3831827cdb80da4726fb5596a0e61d6f194e84cbd0ceb036e22cb89a1af2baccb15ef7850621799d90e96a4049f9b11fc61565'
        'c811e415a549100da927e2caa4ef46ccdd6b2b834b0a781db6ca232a12d90278744133e19916de6421be2f95780b2978ec10eb620fe81a9697df3f2539b5747a'
        '4c28c0ee7443445986a4631d61e9c9f82944c4fd8380d6ba28a14dc85c8e641e88407f25c8abeb47000db25e267946a0d401d0bae4ad1c0b91e4f13953ad0081'
        '597b648ef625aff58fab7ca2067c303c1b7abdf03b78296c7b656260982eaded1938f294975abda75e864499f2bad4801941ff7acc5713d2628ae6550c9ecea3'
        '0f6e20acb800f55c853307a4fe9129280fd440a2b5214c068d91d3dbe5e7e207466ca5019d1792800ac9e4f072f006a5bbcb9b4004700426fc8f2eac6cbef5b2'
        'b793908df0483e64d98e91c7cae1496668f2597d5b6669e2f313abd3a648ba4a685562338e649cbe12a33ab142c90a129f9d642309ee38ad188cbc92fe99ae84'
        '3a41ced2ebbc6773fc4f2803ac835b7e839d81bae529c84191355ad2768065c2ef5e67a165af6bed29c0775c608869425bd1d20c8e2632faceac5bfa8ecb18d5'
        '2aa236f4a72712b974f3d4870ff6557892df8e05c748bc89a195284a3ab7330e0859a52815ee1c4447fd64365283117301fced72b590ea1d16cfc450cfd07018'
        '8c0de659c5dcb70cd6d993c9c8b7607476491440fa62a26a9aea4ee075e20016fe05ce8023c43125bd82b7f8879b20537a0d74e5de2d1b7211b5b37e787b48aa'
        '6e343e15b14ccc980e5ff21641051db57c8c8cb0705426403c0d0e2f7d1adf3efb79f331c34a5e1714ac5103b28e073404229588d8042ab5b8bb95c9ef8421a2'
        '54c9529e1d4fe55d028341fd761e24630f4f0a1c43b287db67bc878aa84ceca8e64283560399980bdcd10987ad3222c30e173e33ac1d341190d1237d6cf4f806'
        '0839ab95b408483774aaff978ece3a1e54ba8ec4bd8146cb2c649ee044224f3ad9c024bd534df09e6883e1d6d4b92593f7e168b6bd51bb32d9b3ee11f7b52716'
        '7b11001ba0638c24e36926a934448203c94240261742df999429954b9a5253e7e72ddda93d47c39b44e61b99491b83b7a46be2d098d3054bf92f73c226048715'
        '154a1a564a6d6ac316869456d271024c0af4cf7175c31579e6ac7293bdb20f413dcf5fd4684e63376627545c13c231ba2cbd28026684e33daec14e3751c25a1e'
        '4611b825d9a79589c427569f2d9521cc3c8d21603d7aae980b763414bbfd96c8d2ef04917805c0af4a8abf397228a866ff5f2c0540ae035662eb1f376bae5312'
        'e318299e4cb828220ac7d5142dc41969f22f83f1f791bd46f7f4ce19dbd1d7074b0faa9ac6a4daac4f70e6c7852b38a6482de62111bb7e653cd870d2968fce70'
        '5c71b88f2ae8a7ebd0932db9a4da72a3ba8c636f31a1bed953a81359588bcb0309f62aa9dee98db62bdc988a9b669341910da2b133d9fb92d14c27d64b54efe9'
        'e09273ddcdc44f4d40fe8a69e0fd70b963681ec4434ce63cf6114ea38954891e709ced877e0be914054854e2d295a2991e8c3d8dc0deb244bfc8b0568c681687'
        '3be2f7d74baf721ad933f04dea39d79e87a2a1dac3e987615d976e984b1043b90d8ede5ab01c4eb371784eb6ca21cdf69ff7b7c8ee6c678c0aea4bf464fdb92f'
        'e1b3977096a79252d23525d9757f7cb38255a737c7bd3bcc9b845db87d486acadbf6901dbaec8a73ae6adee1846e5a2d17bbab23e20471a39046798d23d5ba8e'
        '396acbdcf570eada62533c0b8f505ed18077e8432249bab5b8ac8d1107cabc9489bdb91a5780446237ec4fd9ba5fc57a49dff34c16ddab60dc30513fc535f00f'
        '656a998ab40cb85ee4c00f087b071a91632a6c091da2c84b0f74236b51d2dea6e9db6886625f80ad81dc249d8494ec47cd79d6dd9ea4f5e44f3cde857f861e10')

export KBUILD_BUILD_HOST=archlinux
export KBUILD_BUILD_USER=$pkgbase
export KBUILD_BUILD_TIMESTAMP="$(date -Ru${SOURCE_DATE_EPOCH:+d @$SOURCE_DATE_EPOCH})"

prepare() {
  cd linux-${pkgver%.*}

  echo "Setting version..."
  echo "-$pkgrel" > localversion.10-pkgrel
  echo "${pkgbase#linux}" > localversion.20-pkgname

  local src
  for src in "${source[@]}"; do
      src="${src%%::*}"
      src="${src##*/}"
      src="${src%.zst}"
      [[ $src = *.patch ]] || continue
      echo "Applying patch: $src..."
      patch -Np1 < "../$src"
  done

  echo "Setting config..."
  cp ../config .config
  make olddefconfig
  diff -u ../config .config || :

  make -s kernelrelease > version
  echo "Prepared $pkgbase version $(<version)"
}

build() {
  cd linux-${pkgver%.*}
  make DTC_FLAGS="-@" all
  make -C tools/bpf/bpftool vmlinux.h feature-clang-bpf-co-re=1
}

_package() {
  pkgdesc="The $pkgdesc kernel and modules"
  depends=(
    coreutils
    kmod
    mkinitcpio
  )
  optdepends=(
    'wireless-regdb: to set the correct wireless channels of your country'
    'linux-firmware: firmware images needed for some devices'
  )
  provides=(
    KSMBD-MODULE
    WIREGUARD-MODULE
    "linux-pinetab2=$pkgver-$pkgrel"
  )
  conflicts=(linux-pinetab2)
  replaces=(
    wireguard-arch
  )

  cd linux-${pkgver%.*}
  local modulesdir="$pkgdir/usr/lib/modules/$(<version)"

  echo "Installing boot image..."
  # systemd expects to find the kernel here to allow hibernation
  # https://github.com/systemd/systemd/commit/edda44605f06a41fb86b7ab8128dcf99161d2344
  install -Dm644 "$(make -s image_name)" "$modulesdir/vmlinuz"

  # Used by mkinitcpio to name the kernel
  echo "$pkgbase" | install -Dm644 /dev/stdin "$modulesdir/pkgbase"

  echo "Installing modules..."
  ZSTD_CLEVEL=19 make INSTALL_MOD_PATH="$pkgdir/usr" INSTALL_MOD_STRIP=1 \
    DEPMOD=/doesnt/exist modules_install  # Suppress depmod

  echo "Installing device trees..."
  make INSTALL_DTBS_PATH="$pkgdir/boot/dtbs" dtbs_install

  # Removing unnecessary device trees (keep only pinetab2 variants).
  # Use find -delete instead of a bash for-loop: the previous for-loop
  # silently no-op'd in the makepkg environment, leaving 234 unrelated
  # board DTBs in the package.  find is robust to nullglob/cwd quirks.
  find "$pkgdir"/boot/dtbs/rockchip/ -mindepth 1 -maxdepth 1 -type f \
       ! -name 'rk3566-pinetab2-*' -delete

  # remove build link
  rm "$modulesdir"/build
}

_package-headers() {
  pkgdesc="Headers and scripts for building modules for the $pkgdesc kernel"
  depends=(pahole)

  cd linux-${pkgver%.*}
  local builddir="$pkgdir/usr/lib/modules/$(<version)/build"

  echo "Installing build files..."
  install -Dt "$builddir" -m644 .config Makefile Module.symvers System.map \
    localversion.* version vmlinux tools/bpf/bpftool/vmlinux.h
  install -Dt "$builddir/kernel" -m644 kernel/Makefile
  install -Dt "$builddir/arch/arm64" -m644 arch/arm64/Makefile
  cp -t "$builddir" -a scripts

  # required when DEBUG_INFO_BTF_MODULES is enabled
  install -Dt "$builddir/tools/bpf/resolve_btfids" tools/bpf/resolve_btfids/resolve_btfids

  echo "Installing headers..."
  cp -t "$builddir" -a include
  cp -t "$builddir/arch/arm64" -a arch/arm64/include
  install -Dt "$builddir/arch/arm64/kernel" -m644 arch/arm64/kernel/asm-offsets.s

  install -Dt "$builddir/drivers/md" -m644 drivers/md/*.h
  install -Dt "$builddir/net/mac80211" -m644 net/mac80211/*.h

  # https://bugs.archlinux.org/task/13146
  install -Dt "$builddir/drivers/media/i2c" -m644 drivers/media/i2c/msp3400-driver.h

  # https://bugs.archlinux.org/task/20402
  install -Dt "$builddir/drivers/media/usb/dvb-usb" -m644 drivers/media/usb/dvb-usb/*.h
  install -Dt "$builddir/drivers/media/dvb-frontends" -m644 drivers/media/dvb-frontends/*.h
  install -Dt "$builddir/drivers/media/tuners" -m644 drivers/media/tuners/*.h

  # https://bugs.archlinux.org/task/71392
  install -Dt "$builddir/drivers/iio/common/hid-sensors" -m644 drivers/iio/common/hid-sensors/*.h

  echo "Installing KConfig files..."
  find . -name 'Kconfig*' -exec install -Dm644 {} "$builddir/{}" \;

  echo "Removing unneeded architectures..."
  local arch
  for arch in "$builddir"/arch/*/; do
    [[ $arch = */arm64/ ]] && continue
    echo "Removing $(basename "$arch")"
    rm -r "$arch"
  done

  echo "Removing documentation..."
  rm -r "$builddir/Documentation"

  echo "Removing broken symlinks..."
  find -L "$builddir" -type l -printf 'Removing %P\n' -delete

  echo "Removing loose objects..."
  find "$builddir" -type f -name '*.o' -printf 'Removing %P\n' -delete

  echo "Stripping build tools..."
  local file
  while read -rd '' file; do
    case "$(file -Sib "$file")" in
      application/x-sharedlib\;*)      # Libraries (.so)
        strip -v $STRIP_SHARED "$file" ;;
      application/x-archive\;*)        # Libraries (.a)
        strip -v $STRIP_STATIC "$file" ;;
      application/x-executable\;*)     # Binaries
        strip -v $STRIP_BINARIES "$file" ;;
      application/x-pie-executable\;*) # Relocatable binaries
        strip -v $STRIP_SHARED "$file" ;;
    esac
  done < <(find "$builddir" -type f -perm -u+x ! -name vmlinux -print0)

  echo "Stripping vmlinux..."
  strip -v $STRIP_STATIC "$builddir/vmlinux"

  echo "Adding symlink..."
  mkdir -p "$pkgdir/usr/src"
  ln -sr "$builddir" "$pkgdir/usr/src/$pkgbase"
}

pkgname=(
  "$pkgbase"
  "$pkgbase-headers"
)
for _p in "${pkgname[@]}"; do
  eval "package_$_p() {
    $(declare -f "_package${_p#$pkgbase}")
    _package${_p#$pkgbase}
  }"
done
