#! /bin/sh
#! --------------------------------------------------------------
#! Retro Development Kit
#!
#! This is the build script for RDEV. It is currently being
#! updated to be a bit more modular and easier to extend in the
#! future.
#! --------------------------------------------------------------

SDL="no"
DL="no"
THIS=`pwd`

function help
{
  clear
  echo Retro Development Kit
  echo --------------------------------------------------------------
  echo This script will build Retro 10 and the neccesary support
  echo tools.
  echo
  echo ./build
  echo Build Retro, Ngaro, and Toka. Attempts to detect SDL support.
  echo
  echo ./build --clean
  echo Remove all built and temporary files
  echo
  echo ./build --tty
  echo Builds Retro, Ngaro, and Toka. Does not link against SDL.
  echo
  echo ./build --image
  echo Builds Retro, but not Ngaro. Useful for quick updates.
  echo
  echo ./build --help
  echo Show this text.
}


function toka
{
  echo Building Toka...
  cd $THIS/toka
  if [ "$DL" = "yes" ]; then
    gcc -ldl *.c -o toka
  else
    gcc *.c -o toka
  fi
  cd ..
  mv toka/toka bin
}


function ngaro_sdl
{
  if [ "$SDL" = "no" ]; then
    echo SDL Libraries not found. Please visit http://libsdl.org to obtain a copy.
    echo Will build console version of Ngaro
    ngaro_tty
  else
    echo Building Ngaro...
    cd $THIS/ngaro
    gcc disassemble.c endian.c loader.c ngaro.c sdl_devices.c vm.c -DUSE_SDL -Wall `sdl-config --cflags --libs` -o ngaro
    cd ..
    mv ngaro/ngaro bin
  fi
}


function ngaro_tty
{
  echo Building Ngaro...
  cd $THIS/ngaro
  gcc disassemble.c endian.c loader.c ngaro.c tty_devices.c vm.c -o ngaro
  cd ..
  mv ngaro/ngaro bin
}


function image
{
  echo Building forth.image
  cd $THIS/retro
  ln -s ../bin/bootstrap.toka
  ../bin/toka retro.toka
  rm bootstrap.toka
  cd ..
  mv retro/forth.image bin
  mv retro/forth.image.map bin

  gcc _build/fix-image.c -o bin/fix-image
  cd bin
  ./fix-image forth.image

  echo Building image for Ngaro-JS...
  toka ../_build/image2js.toka forth.image >ngaro-js/image.js
  cd ..
}


function cleanup
{
  echo Removing old files...
  rm -f bin/forth*
  rm -f bin/ngaro
  rm -f bin/ngaro-js/image.js
  rm -f bin/toka
  rm -f bin/fix-image
}


function deps
{
  echo Checking prerequisites...
  gcc _build/test.c -o a.out `sdl-config --cflags --libs` 2>/dev/null && SDL="yes" && rm a.out*
  gcc _build/test.c -o a.out -ldl 2>/dev/null && DL="yes" && rm a.out*
}



if [ "$1" == "--help" ]; then
   help
   exit
fi

if [ "$1" == "--clean" ]; then
   cleanup
   exit
fi

if [ "$1" == "--tty" ]; then
  cleanup
  deps
  toka
  image
  ngaro_tty
  exit
fi

if [ "$1" == "--image" ]; then
  deps
  toka
  image
  exit
fi

#! 
echo $THIS
cleanup
deps
toka
image
ngaro_sdl
echo All done!

