#!/bin/bash
source ~/ncs/toolchains/fbf7391cab/env.sh
target="libzboss.ed.a"

# Check if target file exists
if [ ! -f "$target" ]; then
    echo "Error: Target archive '$target' not found in current directory." >&2
    exit 1
fi

rm -rf $target.obj
rm -rf $target.no_lto_obj
mkdir $target.obj && mkdir $target.no_lto_obj && cd $target.obj
arm-zephyr-eabi-ar x ../$target

total=$(ls -1 *.o | wc -l)
count=0

for f in *.o; do
    count=$((count + 1))
    printf "\r\033[K[%d/%d] de-lto-ing: %s" "$count" "$total" "$f"

    arm-zephyr-eabi-gcc -flto -r -nostdlib \
        -ffunction-sections -fdata-sections \
        -mcpu=cortex-m33 -mthumb -mfpu=fpv5-sp-d16 -mfloat-abi=hard \
        -flinker-output=nolto-rel \
        -o "../$target.no_lto_obj/${f%.o}_delto.o" "$f"
done

printf "\rDone: %d objects processed.%20s\n" "$count" ""

cd ..

arm-zephyr-eabi-ar rcs "$target.no_lto" $target.no_lto_obj/*_delto.o
