#!/bin/bash
INPUT_LIB=$1
OUTPUT_LIB=$2
PREFIX="__xkbc_"

if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <input_lib.a> <output_lib.a>"
    exit 1
fi

echo "Redefining symbols from $INPUT_LIB into $OUTPUT_LIB..."

# We use <(...) to stream the symbol map directly into objcopy
# xtensa-esp-elf-objcopy --redefine-syms=<(
#     xtensa-esp-elf-nm -u "$INPUT_LIB" | 
#     awk '{print $NF}'                 | 
#     sort -u                           | 
#     awk -v p="$PREFIX" '{print $1 " " p $1}'
# ) "$INPUT_LIB" "$OUTPUT_LIB"

xtensa-esp-elf-objcopy --redefine-syms=<(
    comm -23 \
        <(xtensa-esp-elf-nm -u "$INPUT_LIB" | awk '{print $NF}' | sort -u) \
        <(xtensa-esp-elf-nm --defined-only "$INPUT_LIB" | awk '{print $NF}' | sort -u) | \
        awk -v p="$PREFIX" '{print $1 " " p $1}'
) "$INPUT_LIB" "$OUTPUT_LIB"

echo "Done! Prefixed all externally linked symbols with $PREFIX."
