#!/bin/bash
# conftest.sh: Kernel Feature Detection Script
# Purpose: Detect changes in Linux Serial Core and Timer APIs across different kernel versions.
KERNEL_SRC=$1

if [ ! -d "$KERNEL_SRC" ]; then
    exit 1
fi

# -------------------------------------------------------------------------
# 1. Detect 'timeout' member in 'struct uart_port'
# Background: Historically, uart_port had a 'timeout' member. In newer kernels 
# (around 5.15+), this was refactored or moved.
# -------------------------------------------------------------------------
if grep -q "int[[:space:]]*timeout;" "$KERNEL_SRC/include/linux/serial_core.h" 2>/dev/null; then
    echo "-DHAVE_UART_PORT_TIMEOUT"
fi

# -------------------------------------------------------------------------
# 2. Detect 'xmit' member in 'struct uart_state'
# Background: 
# - Pre-6.10: Data buffer is managed via 'struct circ_buf xmit' in uart_state.
# - 6.10+:    Serial core migrated to 'kfifo' (xmit_fifo in tty_port).
# This check attempts to compile a small snippet to verify if 'xmit' exists.
# If this returns HAVE_LEGACY_XMIT_CIRC, the kernel is likely < 6.10.
# -------------------------------------------------------------------------
cat << EOF > .tmp_xmit_test.c
#include <linux/serial_core.h>
int test(struct uart_state *s) { return (int)sizeof(s->xmit); }
EOF

if make -C $KERNEL_SRC M=$(pwd) .tmp_xmit_test.o > /dev/null 2>&1; then
    echo "-DHAVE_LEGACY_XMIT_CIRC"  #if echo means above kernel 6.10
fi
rm -f .tmp_xmit_test.*

# -------------------------------------------------------------------------
# 3. Detect Timer API change (timer_setup vs init_timer)
# Background: 
# - Pre-4.15: Uses init_timer() with 'unsigned long' callback argument.
# - 4.15+:    Uses timer_setup() with 'struct timer_list *' callback argument.
# This transition improved type safety and security (Commit 686fef104630).
# -------------------------------------------------------------------------
if grep -q "timer_setup" "$KERNEL_SRC/include/linux/timer.h" 2>/dev/null; then
    echo "-DHAVE_TIMER_SETUP" #if echo means after kernel 4.15
fi
