#!/usr/bin/env zsh
# Build LwIP as a pure C library without Zig runtime dependencies

set -e

mkdir -p build/lwip_objs
rm -f build/lwip_objs/*.o 2>/dev/null || true

echo "Building LwIP..."

# Compile each source file
compile() {
    local src=$1
    local obj="build/lwip_objs/$(basename ${src%.c}.o)"
    echo "  $src"
    zig cc -target riscv64-freestanding-none -mcpu=sifive_u54 -mcmodel=medany \
        -Os -fno-sanitize=all \
        -DNO_SYS=1 -Icore -Ilibs/membrane -Ilibs/membrane/include \
        -Ilibs/membrane/external/lwip/src/include \
        -c "$src" -o "$obj"
}

# Core sources
compile "libs/membrane/external/lwip/src/core/init.c"
compile "libs/membrane/external/lwip/src/core/def.c"
compile "libs/membrane/external/lwip/src/core/dns.c"
compile "libs/membrane/external/lwip/src/core/inet_chksum.c"
compile "libs/membrane/external/lwip/src/core/ip.c"
compile "libs/membrane/external/lwip/src/core/mem.c"
compile "libs/membrane/external/lwip/src/core/memp.c"
compile "libs/membrane/external/lwip/src/core/netif.c"
compile "libs/membrane/external/lwip/src/core/pbuf.c"
compile "libs/membrane/external/lwip/src/core/raw.c"
compile "libs/membrane/external/lwip/src/core/sys.c"
compile "libs/membrane/external/lwip/src/core/tcp.c"
compile "libs/membrane/external/lwip/src/core/tcp_in.c"
compile "libs/membrane/external/lwip/src/core/tcp_out.c"
compile "libs/membrane/external/lwip/src/core/timeouts.c"
compile "libs/membrane/external/lwip/src/core/udp.c"

# IPv4 sources
compile "libs/membrane/external/lwip/src/core/ipv4/autoip.c"
compile "libs/membrane/external/lwip/src/core/ipv4/dhcp.c"
compile "libs/membrane/external/lwip/src/core/ipv4/etharp.c"
compile "libs/membrane/external/lwip/src/core/ipv4/icmp.c"
compile "libs/membrane/external/lwip/src/core/ipv4/ip4.c"
compile "libs/membrane/external/lwip/src/core/ipv4/ip4_addr.c"
compile "libs/membrane/external/lwip/src/core/ipv4/ip4_frag.c"

# Netif sources
compile "libs/membrane/external/lwip/src/netif/ethernet.c"

# SysArch
compile "libs/membrane/sys_arch.c"

echo "Creating liblwip.a..."
mkdir -p zig-out/lib
rm -f zig-out/lib/liblwip.a
(cd build/lwip_objs && ar rcs ../../zig-out/lib/liblwip.a *.o)
echo "Done! liblwip.a created at zig-out/lib/liblwip.a"
ls -lh zig-out/lib/liblwip.a
