#!/usr/bin/env bash
PREFIX=$1
INPUT_LIB=$2
OUTPUT_LIB=$3

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

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

xtensa-esp-elf-objcopy --redefine-syms=<(
    # Perform set subtraction of undefined symbols and defined symbols, to get globally undefined symbols.
    comm -23 \
        <(xtensa-esp-elf-nm --undefined-only "$INPUT_LIB" | awk '{print $NF}' | sort -u) \
        <(xtensa-esp-elf-nm --defined-only "$INPUT_LIB" | awk '{print $NF}' | sort -u) | \
    # Do not prefix already prefixed symbols (idempotency)
    grep -v "^${PREFIX}" | \
    # Print each symbol followed by the symbol with the prefix
    awk -v p="$PREFIX" '{print $1 " " p $1}'
) "$INPUT_LIB" "$OUTPUT_LIB"

echo "Prefixed all externally linked symbols in $INPUT_LIB with $PREFIX, and written the result to: $OUTPUT_LIB"
