# Maintainer: David P. <megver83@parabola.nu>
# Contributor: André Silva <emulatorman@hyperbola.info>
# Contributor: Márcio Silva <coadde@hyperbola.info>
# Contributor: Nicolás Reynolds <fauno@kiwwwi.com.ar>
# Contributor: Sorin-Mihai Vârgolici <smv@yobicore.org>
# Contributor: Michał Masłowski <mtjm@mtjm.eu>
# Contributor: Luke R. <g4jc@openmailbox.org>

# Based on linux-zen package

_replacesarchkernel=(linux%)  # '%' gets replaced with kernel suffix
_replacesoldkernels=(linux-libre-pck)  # '%' gets replaced with kernel suffix
_replacesoldmodules=()  # '%' gets replaced with kernel suffix

pkgbase=linux-libre-zen
pkgver=7.0.11.zen1
pkgrel=1
pkgdesc='Linux-libre ZEN'
url='https://linux-libre.fsfla.org/'
arch=(
  x86_64
  i686
  armv7h
)
license=(GPL-2.0-only)
makedepends=(
  bc
  binutils
  cpio
  gettext
  glibc
  libelf
  libgcc
  openssl
  'pahole>=1:1.30' # minimun version required for vmlinux.h
  perl
  python
  #rust
  #rust-bindgen
  #rust-src
  tar
  xxhash
  xz
  zlib
  zstd

  # htmldocs
  graphviz
  imagemagick
  python-sphinx
  python-yaml
  texlive-latexextra
)
makedepends_x86_64=(
  # RUST is only enabled in x86_64
  rust
  rust-bindgen
  rust-src
)
options=(
  !debug
  !strip
)
_upstream_ver=${pkgver%.*}
_srcname=linux-7.0
_srctag=v${pkgver%.*}-${pkgver##*.}
source=(
  "https://linux-libre.fsfla.org/pub/linux-libre/releases/${_srcname##*-}-gnu/linux-libre-${_srcname##*-}-gnu.tar.xz"{,.sign}
  "https://linux-libre.fsfla.org/pub/linux-libre/releases/$_upstream_ver-gnu/patch-${_srcname##*-}-gnu-$_upstream_ver-gnu.xz"{,.sign}
  "https://repo.parabola.nu/other/linux-libre/logos/logo_linux_"{clut224.ppm,vga16.ppm,mono.pbm}{,.sig}
  "https://github.com/zen-kernel/zen-kernel/releases/download/$_srctag/linux-$_srctag.patch.zst"{,.sig}

  # maintain the TTY over USB disconnects
  # http://www.coreboot.org/EHCI_Gadget_Debug
  0001-usb-serial-gadget-no-TTY-hangup-on-USB-disconnect-WI.patch
  # fix Atmel maXTouch touchscreen support
  # https://labs.parabola.nu/issues/877
  # http://www.fsfla.org/pipermail/linux-libre/2015-November/003202.html
  0002-fix-Atmel-maXTouch-touchscreen-support.patch
)
source_x86_64=(
  config.x86_64
)
source_i686=(
  config.i686
  # avoid using zstd compression in ultra mode (exhausts virtual memory)
  no-ultra-zstd.patch
)
source_armv7h=(
  config.armv7h
  # armv7h preset file for mkinitcpio ramdisk
  linux-armv7h.preset
)
validpgpkeys=(
  474402C8C582DAFBE389C427BCB7CF877E7D47A7  # Alexandre Oliva
  6DB9C4B4F0D8C0DC432CF6E4227CA7C556B2BA78  # David P.
  83BC8889351B5DEBBB68416EB8AC08600F108CDF  # Jan Alexander Steffens (heftig)
)
sha256sums=('14e107d8650fa2fe75a3876b0f3f46de11d8eb40cb7312cdd46b213d9bce3804'
            'SKIP'
            'd4a4ce8629bd88798800de6f1539a2ace26ec050b39ad5b4c50dda28af2f2121'
            'SKIP'
            'bfd4a7f61febe63c880534dcb7c31c5b932dde6acf991810b41a939a93535494'
            'SKIP'
            '6de8a8319271809ffdb072b68d53d155eef12438e6d04ff06a5a4db82c34fa8a'
            'SKIP'
            '13bd7a8d9ed6b6bc971e4cd162262c5a20448a83796af39ce394d827b0e5de74'
            'SKIP'
            '7ebbe6d5804034989e6be17c75e2a61e42679a01da799678df9b83b169f46ee4'
            'SKIP'
            '0376bd5efa31d4e2a9d52558777cebd9f0941df8e1adab916c868bf0c05f2fc3'
            '351fd96be8cd5ebd0435c0a8a978673fc023e3b1026085e67f86d815b2285e25')
sha256sums_x86_64=('841f6bdd4a90a2be61fe687c9262e86dfb0eeeee73f9cb0fa5573feddfa7ae17')
sha256sums_i686=('ecf5cf7a2c8b60d195b3640ef097e82780464c4b4ff07bb13439aab319060123'
                 'd32270be5fd9c3e3ba50f3aef33f6cfcb85be0c8216f03b777287cc621fdff28')
sha256sums_armv7h=('7bed69bdabec2a434e8ae654d64972816885d68917ae07957d95625e5db3c506'
                   '36fece52ce8dd219f15d572a5ca48d0f10956ff04376f05a5e719f23e2639c8a')
b2sums=('45893cd901662c1a684f649aebdd2e765c16cfe520d7bc08ae5150748c6cd809452258f89f2cd331bdb8dff898a4a60e798a397f9aa22080476eab3145ec14d6'
        'SKIP'
        '62a67ccf6abb18f99d1e108b09a1d55c3aad3a3fdfa2f0943064f5cc8f2c69c122b2bf52a480a1928b98f1f643885349235ed63c2b6881528b31ff367587dd96'
        'SKIP'
        '73fee2ae5cb1ffd3e6584e56da86a8b1ff6c713aae54d77c0dab113890fc673dc5f300eb9ed93fb367b045ece8fa80304ff277fe61665eccf7b7ce24f0c045eb'
        'SKIP'
        'd02a1153a4285b32c774dca4560fe37907ccf30b8e487a681b717ed95ae9bed5988875c0a118938e5885ae9d2857e53a6f216b732b6fa3368e3c5fe08c86382c'
        'SKIP'
        '580911af9431c066bbc072fd22d5e2ef65f12d8358cec5ff5a4f1b7deebb86cef6b5c1ad631f42350af72c51d44d2093c71f761234fb224a8b9dbb3b64b8201d'
        'SKIP'
        '02953c3b7f97987f88ef4a50ae2cd5d6a3d787cb7d866c19b3ba80e64884e836e89fd4192f352722944a29fd0725c2658625f4ff94f5f0dcf95a940d2678ce8a'
        'SKIP'
        'c2214154c36900e311531bfe68184f31639f5c50fed23bc3803a7f18439b7ff258552a39f02fed0ea92f10744e17a6c55cef0ef1a98187f978fe480fb3dddc14'
        '0c7ceba7cd90087db3296610a07886f337910bad265a32c052d3a703e6eb8e53f355ab9948d72d366408d968d8ee7435084dd89bef5ed0b69355fd884c2cd468')
b2sums_x86_64=('3a3e00b0d7bfc8929cd8e2570e0e429593b88f79676fa10fb093436a803bb349a1a10cffb66bdf83341180b772920ce70661541c185812f1496d9d4c49b7db9d')
b2sums_i686=('c4ba48f4fc1fc0c004fafd7f38fbafe8605c41fe29f0286a05374c673fba96367e90319545dc8d70b869361c087559dc1f9a04c58e3ae2a253b0080c625dbff9'
             '165ab9dd8cedeaae5327accc1581c19cf0be55f923b03feb889cad3351b74c7c4cd3d3c206938e5152bfe1d947513dea8f630f8f5544099ec13d16d254725c40')
b2sums_armv7h=('9c710aadf3c9cac23d5fe5c8b9ffe616d1f49e23ea90c2b83c632a3233d59183ecc9d7fe6816c4130ccf6b988d00339695d1bc02377c01f5429e6b5b7eb594ac'
               '271fc9608fd7a48ca52e4487a565a9c5afe9551c04369f4f35220c6d511b5da2c3e073fad3de576d1ca674b488a8b45f20948b16916b7f073846b2a2115e63fd')

_replacesarchkernel=("${_replacesarchkernel[@]/\%/${pkgbase#linux-libre}}")
_replacesoldkernels=("${_replacesoldkernels[@]/\%/${pkgbase#linux-libre}}")
_replacesoldmodules=("${_replacesoldmodules[@]/\%/${pkgbase#linux-libre}}")

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

prepare() {
  cd $_srcname

  if [ "${_srcname##*-}" != "$_upstream_ver" ]; then
    echo "Applying upstream patch..."
    patch -Np1 < "../patch-${_srcname##*-}-gnu-$_upstream_ver-gnu"
  fi

  echo "Adding freedo as boot logo..."
  install -m644 -t drivers/video/logo \
    ../logo_linux_{clut224.ppm,vga16.ppm,mono.pbm}

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

  # save extraversion as localversion to fit Zen patch while keeping the original value
  awk '/^EXTRAVERSION/ {print $3}' Makefile > localversion.00-extraversion
  sed -i '/^EXTRAVERSION[[:space:]]*=/ s/=.*$/=/' Makefile

  local source=("${source[@]}")
  eval "source+=(\${source_${CARCH}[@]})"

  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

  # save extraversion as localversion after patching for correct string concatenation order
  awk '/^EXTRAVERSION/ {print $3}' Makefile > localversion.01-extraversion
  sed -i '/^EXTRAVERSION[[:space:]]*=/ s/=.*$/=/' Makefile

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

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

  if ! [[ $(scripts/config -s CONFIG_DEBUG_INFO_BTF) = y ]]; then
    echo "CONFIG_DEBUG_INFO_BTF is required to build vmlinux.h"
    exit 1
  fi
}

build() {
  cd $_srcname
  make all
  make -C tools/bpf/bpftool vmlinux.h feature-clang-bpf-co-re=1
  make htmldocs SPHINXOPTS=-QT
}

_package() {
  pkgdesc="The $pkgdesc kernel and modules"
  depends=(
    coreutils
    initramfs
    kmod
  )
  optdepends=(
    "$pkgbase-headers: headers and scripts for building modules"
    'linux-libre-firmware: firmware images needed for some devices'
    #'scx-scheds: to use sched-ext schedulers'
    'wireless-regdb: to set the correct wireless channels of your country'
  )
  optdepends_x86_64=(
    'scx-scheds: to use sched-ext schedulers' # only available for x86_64
  )
  provides=(
    KSMBD-MODULE
    NTSYNC-MODULE
    VHBA-MODULE
    VIRTUALBOX-GUEST-MODULES
    WIREGUARD-MODULE
  )
  replaces=(
  )
  provides+=(
    "${_replacesarchkernel[@]/%/=$_upstream_ver}"
    "LINUX-ABI_VERSION=$_upstream_ver"
  )
  conflicts+=(
    "${_replacesarchkernel[@]}"
    "${_replacesoldkernels[@]}"
    "${_replacesoldmodules[@]}"
  )
  replaces+=(
    "${_replacesarchkernel[@]}"
    "${_replacesoldkernels[@]}"
    "${_replacesoldmodules[@]}"
  )

  cd $_srcname
  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

  # remove build link
  rm "$modulesdir"/build

  if [ "$CARCH" = "armv7h" ]; then
    echo "Installing dtbs..."
    make INSTALL_DTBS_PATH="$pkgdir/boot/dtbs/$pkgbase" dtbs_install

    # sed expression for following substitutions
    local _subst="
      s|%PKGBASE%|${pkgbase}|g
      s|%KERNVER%|$(<version)|g
    "

    # install mkinitcpio preset file
    sed "${_subst}" ../linux-armv7h.preset |
      install -Dm644 /dev/stdin "${pkgdir}/etc/mkinitcpio.d/${pkgbase}.preset"
  fi
}

_package-headers() {
  pkgdesc="Headers and scripts for building modules for the $pkgdesc kernel"
  depends=(
    binutils
    glibc
    libelf
    libgcc
    openssl
    pahole
    xxhash
    zlib
    zstd
  )
  provides=(LINUX-HEADERS)
  provides+=(
    "${_replacesarchkernel[@]/%/-headers=$_upstream_ver}"
  )
  conflicts+=(
    "${_replacesarchkernel[@]/%/-headers}"
    "${_replacesoldkernels[@]/%/-headers}"
  )
  replaces+=(
    "${_replacesarchkernel[@]/%/-headers}"
    "${_replacesoldkernels[@]/%/-headers}"
  )

  cd $_srcname
  local builddir="$pkgdir/usr/lib/modules/$(<version)/build"

  case "$CARCH" in
    i686|x86_64) karch=x86;;
    armv7h) karch=arm;;
    *) echo "Unknown CARCH $CARCH"; exit 1 ;;
  esac

  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/$karch" -m644 arch/$karch/Makefile
  [ "$CARCH" != i686 ] || install -Dt "$builddir/arch/x86" -m644 arch/x86/Makefile_32.cpu
  cp -t "$builddir" -a scripts
  ln -srt "$builddir" "$builddir/scripts/gdb/vmlinux-gdb.py"

  if [[ $(scripts/config -s CONFIG_HAVE_STACK_VALIDATION) = y ]]; then
    install -Dt "$builddir/tools/objtool" tools/objtool/objtool
  fi

  if [[ $(scripts/config -s CONFIG_DEBUG_INFO_BTF_MODULES) = y ]]; then
    install -Dt "$builddir/tools/bpf/resolve_btfids" tools/bpf/resolve_btfids/resolve_btfids
  fi

  echo "Installing headers..."
  cp -t "$builddir" -a include
  cp -t "$builddir/arch/$karch" -a arch/$karch/include
  install -Dt "$builddir/arch/$karch/kernel" -m644 arch/$karch/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 "Installing Rust files..."
  if [[ $(scripts/config -s CONFIG_RUST) = y ]]; then
    install -Dt "$builddir/rust" -m644 rust/*.rmeta
    install -Dt "$builddir/rust" rust/*.so
  fi

  echo "Installing unstripped VDSO..."
  make INSTALL_MOD_PATH="$pkgdir/usr" vdso_install \
    link=  # Suppress build-id symlinks

  echo "Removing unneeded architectures..."
  local arch
  for arch in "$builddir"/arch/*/; do
    [[ $arch = */$karch/ ]] && 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"
}

_package-docs() {
  pkgdesc="Documentation for the $pkgdesc kernel"
  provides=(
    "${_replacesarchkernel[@]/%/-docs=$_upstream_ver}"
  )
  conflicts=(
    "${_replacesarchkernel[@]/%/-docs}"
    "${_replacesoldkernels[@]/%/-docs}"
  )
  replaces=(
    "${_replacesarchkernel[@]/%/-docs}"
    "${_replacesoldkernels[@]/%/-docs}"
  )

  cd $_srcname
  local builddir="$pkgdir/usr/lib/modules/$(<version)/build"

  echo "Installing documentation..."
  local src dst
  while read -rd '' src; do
    dst="${src#Documentation/}"
    dst="$builddir/Documentation/${dst#output/}"
    install -Dm644 "$src" "$dst"
  done < <(find Documentation -name '.*' -prune -o ! -type d -print0)

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

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

# vim:set ts=8 sts=2 sw=2 et:
