#!/bin/sh
# vim: set ts=4 sw=4 sts=4 et:
# Download and parse Linux kernel's intel-family.h to generate src/libs/003_intel_models.sh.
# Usage: scripts/update_intel_models.sh

set -eu

SCRIPTDIR="$(cd "$(dirname "$0")" && pwd)"
REPODIR="$(dirname "$SCRIPTDIR")"
OUTFILE="$REPODIR/src/libs/003_intel_models.sh"
URL="https://raw.githubusercontent.com/torvalds/linux/refs/heads/master/arch/x86/include/asm/intel-family.h"

TMPFILE=$(mktemp /tmp/intel-family-XXXXXX.h)
trap 'rm -f "$TMPFILE"' EXIT INT TERM

echo "Downloading $URL ..."
wget -q -O "$TMPFILE" "$URL"
echo "Parsing intel-family.h ..."

{
    cat <<'HEADER'
# vim: set ts=4 sw=4 sts=4 et:
# AUTO-GENERATED FILE — DO NOT EDIT MANUALLY.
# Generated by scripts/update_intel_models.sh from:
#   https://raw.githubusercontent.com/torvalds/linux/refs/heads/master/arch/x86/include/asm/intel-family.h
# Run scripts/update_intel_models.sh to refresh when new Intel CPU families are added to the kernel.
# shellcheck disable=SC2034
{
HEADER

    awk '
/^#define INTEL_[A-Z0-9_]+[[:space:]]+IFM\(/ {
    name = $2

    # Skip wildcard and notational markers
    if (name == "INTEL_ANY") next
    if (name ~ /_START$/) next
    if (name ~ /_LAST$/) next

    # Extract the IFM(...) argument string
    line = $0
    sub(/.*IFM\(/, "", line)   # line is now: "N, 0xNN) ..."

    # Extract family
    family = line
    sub(/,.*/, "", family)
    gsub(/[[:space:]]/, "", family)
    # Skip non-numeric families (e.g. X86_FAMILY_ANY)
    if (family !~ /^[0-9]+$/) next

    # Extract model
    rest = line
    sub(/^[^,]+, */, "", rest)  # remove "N, "
    model = rest
    sub(/\).*/, "", model)
    gsub(/[[:space:]]/, "", model)

    # Extract optional C comment and convert to shell comment
    comment = ""
    if (index($0, "/*") > 0) {
        c = $0
        sub(/.*\/\*/, "/* ", c)
        gsub(/ +/, " ", c)
        sub(/ *\*\/.*/, " */", c)
        comment = "\t# " c
    }

    # Strip INTEL_ prefix; prepend INTEL_FAM<family>_
    sub(/^INTEL_/, "", name)
    varname = "INTEL_FAM" family "_" name

    printf "\treadonly %s=$(( %s ))%s\n", varname, model, comment
}
' "$TMPFILE"

    printf '}\n'

} | shfmt -i 4 -ci -ln bash > "$OUTFILE"

echo "Generated $OUTFILE ($(wc -l < "$OUTFILE") lines)"
