#!/bin/bash
# sync_template.sh - Refresh the standalone app SDK (template/sysroot) from the
# live tree: headers from programs/include + freestanding toolchain headers,
# libraries from programs/lib build outputs.
# Usage: ./scripts/sync_template.sh (from project root; run 'make programs' first)

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

SYSROOT="$PROJECT_ROOT/template/sysroot"
INC="$SYSROOT/include"
LIB="$SYSROOT/lib"

# Include directories from programs/include that form the app SDK surface.
# (gui/dialogs.hpp depends on libloader/, so it ships too.)
SDK_DIRS=(Api gui http libc libloader montauk tls)

# Library build outputs copied into sysroot/lib.
SDK_LIBS=(
    "programs/lib/libc/liblibc.a"
    "programs/lib/libc/crt1.o"
    "programs/lib/libc/crti.o"
    "programs/lib/libc/crtn.o"
    "programs/lib/bearssl/libbearssl.a"
    "programs/lib/libjpeg/libjpeg.a"
    "programs/lib/tls/libtls.a"
)

# All libraries must exist before we wipe anything.
for f in "${SDK_LIBS[@]}"; do
    if [ ! -f "$PROJECT_ROOT/$f" ]; then
        echo "sync_template: missing $f - run 'make programs' first" >&2
        exit 1
    fi
done

# The sysroot is fully generated from the sources below, so rebuild it from
# scratch to drop headers that no longer exist upstream.
rm -rf "$INC" "$LIB"
mkdir -p "$INC" "$LIB"

# Freestanding C headers (intrinsics, stddef.h, ...) and C++ headers,
# flattened into the sysroot root like the compiler's default search path.
cp -r "$PROJECT_ROOT/kernel/freestnd-c-hdrs/x86_64/include/." "$INC/"
cp -r "$PROJECT_ROOT/kernel/freestnd-cxx-hdrs/x86_64/include/." "$INC/"

# MontaukOS SDK headers.
for d in "${SDK_DIRS[@]}"; do
    cp -r "$PROJECT_ROOT/programs/include/$d" "$INC/$d"
done

# BearSSL public headers, available both as <bearssl.h> and <bearssl/bearssl.h>.
cp "$PROJECT_ROOT"/programs/lib/bearssl/inc/*.h "$INC/"
mkdir -p "$INC/bearssl"
cp "$PROJECT_ROOT"/programs/lib/bearssl/inc/*.h "$INC/bearssl/"

# Libraries and CRT objects.
for f in "${SDK_LIBS[@]}"; do
    cp "$PROJECT_ROOT/$f" "$LIB/"
done

echo "sync_template: refreshed $SYSROOT"
echo "  headers:   freestnd-c-hdrs, freestnd-cxx-hdrs, programs/include/{${SDK_DIRS[*]}}, bearssl"
echo "  libraries: $(cd "$LIB" && ls | tr '\n' ' ')"
