#!/bin/bash
set -e

# Nexus Mksh Builder
# "Grafting Mksh into Nexus"

TARGET="riscv64-freestanding-none"
MCPU="sifive_u54"
CFLAGS="-target $TARGET -mcpu=$MCPU -mabi=lp64d -mcmodel=medany \
-ffunction-sections -fdata-sections -ffreestanding -fno-stack-protector -fno-builtin -Os \
-DMKSH_BINSHREDUCED -DMKSH_DISABLE_DEPRECATED -D_GNU_SOURCE -DMKSH_BUILDSH -DMKSH_BUILD_R=593 \
-DHAVE_MEMMOVE=1 -DHAVE_STRCHR=1 -DHAVE_STRSTR=1 -DHAVE_QSORT=1 \
-DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_UNISTD_H=1 \
-DHAVE_SYS_TIME_H=1 -DHAVE_SYS_RESOURCE_H=1 -DHAVE_SIGNAL_H=1 \
-DHAVE_SETJMP_H=1 -DHAVE_DIRENT_H=1 -DHAVE_FCNTL_H=1 \
-DHAVE_GRP_H=1 -DHAVE_PWD_H=1 -DHAVE_TERMIOS_H=1 \
-DHAVE_SYS_IOCTL_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_SYS_WAIT_H=1 -DHAVE_SYS_TIMES_H=1 \
-DHAVE_SIGSETJMP=1 -DHAVE_SIG_T=1 -DHAVE_BOTH_TIME_H=1 -DHAVE_TIME_H=1 \
-I ../../core/include \
-I ../../libs/membrane/include \
-I ../lwip/src/include \
-I ../littlefs"


# Change to script directory
cd "$(dirname "$0")"

echo "[Graft] Compiling Mksh..."

# Compile sources
SOURCES="edit.c eval.c exec.c expr.c funcs.c histrap.c jobs.c lalloc.c lex.c main.c misc.c shf.c syn.c tree.c var.c strlcpy.c"

# We compile directly to an ELF for now to test linking
# But usually we want object files first
OBJS=""
for src in $SOURCES; do
    echo "  -> $src"
    zig cc $CFLAGS -c mksh/$src -o mksh/${src%.c}.o
    OBJS="$OBJS mksh/${src%.c}.o"
done


# Compile stubs
echo "  -> stubs_mksh.c"
zig cc $CFLAGS -c stubs_mksh.c -o stubs_mksh.o

echo "[Graft] Linking Mksh..."
LINKER_SCRIPT="../../apps/linker_user.ld"
BUILD_DIR="../../build"

# We must link against Membrane (libnexus.a)
# And startup objects (subject_entry.o) if we want it to be a valid Nexus app
# Wait, userland programs in Nexus are typically fibers or distinct address spaces?
# If "init.nim" execs it, it's likely a distinct binary loaded by kernel or init.

zig cc -target $TARGET -nostdlib -static -T $LINKER_SCRIPT \
    $BUILD_DIR/subject_entry.o \
    $BUILD_DIR/stubs_user.o \
    $BUILD_DIR/libc_shim.o \
    stubs_mksh.o \
    $OBJS \
    -L$BUILD_DIR -lnexus \
    -o mksh.elf

echo "[Graft] Mksh ELF created: mksh.elf"
