#!/bin/bash
# CUSTOM_BUILD_HARDENED_EDGE
export CFLAGS="${CFLAGS:--O2} -fhardened -fPIC"
export CXXFLAGS="${CXXFLAGS:--O2} -fhardened -fPIC"
export LDFLAGS="${LDFLAGS:-} -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,ibt -Wl,-z,shstk"

cd $(dirname $0) ; CWD=$(pwd)

PKGNAM=kernel-firmware-edge
ARCH=noarch
BUILD=${BUILD:-1}

CACHE=${CACHE:-/tmp/linux-firmware-cache}
COMPRESSION=${COMPRESSION:-none}
AMD_UCODE=${AMD_UCODE:-YES}
INCLUDE_I915=${INCLUDE_I915:-YES}


# Intel QuickAssist crypto/compression accelerator firmware.
# Very useful for a TLS relay with QAT-capable hardware.
INCLUDE_QAT=${INCLUDE_QAT:-YES}

# ------------------------------------------------------------------
# Top-level firmware directories/files kept wholesale.
#
# Snapshot 739c4fb has no mpt3sas/, no megaraid*, no bnxt/,
# no atlantic/, no aquantia/, and no intel/{igb,ixgbe,i40e,iavf}.
# Those families are simply not in this tree; do not add entries
# that match nothing.
# ------------------------------------------------------------------
FW_PREFIXES=(
    # Broadcom NetXtreme / NetXtreme II wired NICs
    bnx

    # Chelsio T3/T4/T5/T6
    cxgb

    # Intel 82557/58/59 legacy e100
    e100

    # Intel SATA/SAS HBA (isci)
    isci

    # Kaweth USB-Ethernet
    kaweth

    # Cavium/Marvell FastLinQ 10/25/40/50/100GbE
    qed

    # QLogic Fibre Channel HBA blobs (root-level ql2xxx_fw.bin)
    ql2

    # QLogic newer FC adapters directory
    qlogic

    # Realtek USB Ethernet (RTL8152/8153/8156)
    realtek

    # Realtek PCIe PHY firmware for on-board NICs
    rtl_nic

    # 3Com legacy NICs (tiny)
    3com

    # Alteon Tigon 10/100/1000
    tigon

    # Tehuti Networks tn40xx 10GbE
    tehuti

    # AMD microcode raw blobs
    amd-ucode
)

# Intel GPU firmware: optional, largest single kept item.
if [ "$INCLUDE_I915" = "YES" ]; then
    FW_PREFIXES+=( i915 )
    FW_PREFIXES+=( radeon )
    # FW_PREFIXES+=( amdgpu )
    # FW_PREFIXES+=( nvidia )
fi

# Intel wired/accelerator subdirs copied back after prune.
# intel/ also contains iwlwifi, ibt-*, dsp_fw_*, ipu, ish, vpu,
# vsc, avs, catpt — all skipped.
INTEL_SUBDIRS=( ice )
if [ "$INCLUDE_QAT" = "YES" ]; then
    INTEL_SUBDIRS+=( qat )
fi

# ---- Version info ----
get_repo_info() {
    if [ -d "$CACHE/.git" ]; then
        DATE=$(git -C "$CACHE" log -1 --format=%cd --date=short 2>/dev/null | tr -d -)
        HEADISAT=$(git -C "$CACHE" rev-parse --short=7 HEAD 2>/dev/null)
    else
        DATE="$(lynx -dump -width=256 https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/commit/?id=HEAD 2>/dev/null | grep "   committer " | head -n 1 | rev | cut -f 3 -d ' ' | rev | tr -d -)"
        HEADISAT="$(lynx -dump -width=256 https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/commit/?id=HEAD 2>/dev/null | grep "    commit   " | head -n 1 | cut -f 2 -d ] | cut -b 1-7)"
    fi
}

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
    get_repo_info
    echo "$PKGNAM-${DATE}_${HEADISAT}-$ARCH-$BUILD.txz"
    exit 0
fi

TMP=${TMP:-/tmp}
PKG=$TMP/package-$PKGNAM

rm -rf $PKG
mkdir -p $TMP $PKG

# ---- Fetch or update cached clone ----
if [ -d "$CACHE/.git" ]; then
    echo "Updating cached linux-firmware at $CACHE ..."
    if git -C "$CACHE" fetch --depth 1 origin 2>/dev/null; then
        git -C "$CACHE" reset --hard FETCH_HEAD 2>/dev/null || true
        git -C "$CACHE" clean -fdx 2>/dev/null || true
    else
        echo "Fetch failed, recloning ..."
        rm -rf "$CACHE"
        git clone --depth 1 git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git "$CACHE" || exit 1
    fi
else
    echo "Initial shallow clone to $CACHE (one-time ~800MB) ..."
    git clone --depth 1 git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git "$CACHE" || exit 1
fi

DATE=$(git -C "$CACHE" log -1 --format=%cd --date=short | tr -d -)
HEADISAT=$(git -C "$CACHE" rev-parse --short=7 HEAD)
echo "Building kernel-firmware-${DATE}_${HEADISAT} from $CACHE"

# ---- AMD microcode CPIO ----
if [ "$AMD_UCODE" = "YES" ] && [ -d "$CACHE/amd-ucode" ]; then
    echo "Building /boot/amd-ucode.img ..."
    mkdir -p $PKG/boot/tmp
    pushd $PKG/boot/tmp
        mkdir -p kernel/x86/microcode
        find "$CACHE/amd-ucode" -type f -name "*.bin" | sort | \
            xargs cat > kernel/x86/microcode/AuthenticAMD.bin
        find . | cpio --no-absolute-filenames -H newc -o -F $PKG/boot/amd-ucode.img
    popd
    rm -rf $PKG/boot/tmp
fi

# ---- Install firmware (uncompressed inside .txz) ----
mkdir -p $PKG/lib/firmware
case "$COMPRESSION" in
  xz)   INSTALLTARGET="install-xz" ;;
  zstd) INSTALLTARGET="install-zst" ;;
  *)    INSTALLTARGET="install" ;;
esac

( cd "$CACHE"
  echo "Running make DESTDIR=$PKG ${INSTALLTARGET} ..."
  make -e DESTDIR=$PKG "$INSTALLTARGET" 2>/dev/null || exit 1
) || exit 1

# ---- Prune by top-level prefix ----
echo "Pruning firmware by prefix whitelist ..."
cd $PKG/lib/firmware || exit 1

shopt -s nullglob
for item in *; do
    keep=0
    for prefix in "${FW_PREFIXES[@]}"; do
        case "$item" in
            ${prefix}*) keep=1; break ;;
        esac
    done
    if [ $keep -eq 0 ]; then
        rm -rf "$item"
    else
        echo "  keep  $item"
    fi
done
shopt -u nullglob

# ---- Copy back Intel wired/accelerator subdirs ----
echo "Adding Intel subdirs: ${INTEL_SUBDIRS[*]}"
if [ -d "$CACHE/intel" ]; then
    for sub in "${INTEL_SUBDIRS[@]}"; do
        if [ -d "$CACHE/intel/$sub" ]; then
            mkdir -p $PKG/lib/firmware/intel
            cp -a "$CACHE/intel/$sub" $PKG/lib/firmware/intel/
            sz=$(du -sh "$CACHE/intel/$sub" | cut -f1)
            echo "  keep  intel/$sub ($sz)"
        else
            echo "  skip  intel/$sub (not in this snapshot)"
        fi
    done
else
    echo "  skip  intel/ (not in this snapshot)"
fi

# ---- Dedup (MUST run after prune/copy-back) ----
if command -v rdfind >/dev/null 2>&1; then
    echo "Running make dedup DESTDIR=$PKG ..."
    ( cd "$CACHE"
      make -e dedup DESTDIR=$PKG 2>/dev/null
    ) || echo "  WARN: dedup failed, continuing without dedup"
else
    echo "  rdfind not installed, skipping dedup"
fi

# ---- Sanity: dangling symlinks ----
dangling=$(find $PKG/lib/firmware -xtype l 2>/dev/null | head -20)
if [ -n "$dangling" ]; then
    echo "WARN: dangling symlinks after prune/dedup:"
    echo "$dangling" | sed 's/^/      /'
fi

echo "==== Kept firmware (uncompressed) ===="
du -sh $PKG/lib/firmware/* 2>/dev/null | sort -rh
echo "======================================"

# ---- Documentation ----
cd $PKG
DOCDIR=$PKG/usr/doc/$PKGNAM-${DATE}_${HEADISAT}
mkdir -p $DOCDIR
cp -a "$CACHE"/GPL* "$CACHE"/LICEN* "$DOCDIR" 2>/dev/null || true
cp -a "$CACHE"/README.md "$DOCDIR"/README.linux-firmware 2>/dev/null || true
cp -a "$CACHE"/WHENCE "$DOCDIR"/WHENCE.linux-firmware 2>/dev/null || true
cp -a "$CACHE"/amd-ucode/README "$DOCDIR"/README.amd-ucode 2>/dev/null || true

chown -R root:root $PKG
mkdir -p $PKG/install
if [ -f "$CWD/slack-desc" ]; then
    cat "$CWD/slack-desc" > $PKG/install/slack-desc
else
    echo "WARN: no $CWD/slack-desc, package will lack a description"
fi

# ---- Pack ----
cd $PKG
/sbin/makepkg -l y -c n $TMP/$PKGNAM-${DATE}_${HEADISAT}-$ARCH-$BUILD.txz
echo "Result: $(du -h $TMP/$PKGNAM-${DATE}_${HEADISAT}-$ARCH-$BUILD.txz | cut -f1)"