#!/bin/bash
#
#  build.tool
#  Lilu
#
#  Copyright © 2018 vit9696. All rights reserved.
#

cd $(dirname "$0") || exit 1

rm -f *.o *.bin wrappers.inc entry32 entry64

clang -m32 -c entry32.S || exit 1
clang -m64 -c entry64.S || exit 1

clang -m32 entry32.o -o entry32 || exit 1
clang -m64 entry64.o -o entry64 || exit 1

if [ "$(nm entry32.o | grep '00000000 T _main')" == "" ] || [ "$(nm entry64.o | grep '0000000000000000 T _main')" == "" ]; then
  echo "Invalid main address"
  exit 1
fi

otool -t entry32 | grep -E '^0000' | sed 's#^[0-9a-f]*##' | xxd -r -p > entry32.bin
otool -t entry64 | grep -E '^0000' | sed 's#^[0-9a-f]*##' | xxd -r -p > entry64.bin

sz32=$(stat -f '%z' entry32.bin)
sz64=$(stat -f '%z' entry64.bin)

btr32=$(nm entry32.o | grep -E 't booter$' | cut -f1 -d' ')
btr64=$(nm entry64.o | grep -E 't booter$' | cut -f1 -d' ')

ep32=$(nm entry32.o | grep -E 't entrypoint$' | cut -f1 -d' ')
ep64=$(nm entry64.o | grep -E 't entrypoint$' | cut -f1 -d' ')

echo '//' > wrappers.inc
echo '//  wrappers.inc' >> wrappers.inc
echo '//  Lilu' >> wrappers.inc
echo '//' >> wrappers.inc
echo '//  Copyright © 2018 vit9696. All rights reserved.' >> wrappers.inc
echo '//' >> wrappers.inc
echo '' >> wrappers.inc
echo '// This is an autogenerated file, do not edit!' >> wrappers.inc
echo 'static uint8_t entryWrapper32[] = {' >> wrappers.inc
cat entry32.bin | xxd -i >> wrappers.inc
echo '};' >> wrappers.inc
echo 'static uint8_t entryWrapper64[] = {' >> wrappers.inc
cat entry64.bin | xxd -i >> wrappers.inc
echo '};' >> wrappers.inc
echo "static_assert(sizeof(entryWrapper32) == ${sz32}, \"Invalid entryWrapper32 size\");" >> wrappers.inc
echo "static_assert(sizeof(entryWrapper64) == ${sz64}, \"Invalid entryWrapper64 size\");" >> wrappers.inc
echo "static constexpr size_t EntryWrapper32Booter {0x${btr32}};" >> wrappers.inc
echo "static constexpr size_t EntryWrapper64Booter {0x${btr64}};" >> wrappers.inc
echo "static constexpr size_t EntryWrapper32Entry {0x${ep32}};" >> wrappers.inc
echo "static constexpr size_t EntryWrapper64Entry {0x${ep64}};" >> wrappers.inc

rm -f *.o *.bin entry32 entry64
