#! /bin/bash

# Public Domain

if [ -n "$UPDATEDL" ]
then
  unset UPDATEDL
  if [ "$UPDATEDLNAME" == ldosxt ]
  then
    ./makinst.sh
    ./mak.sh onlykern
    ./makshrtl.sh
    ./makfortl.sh
    ./makinstl.sh
    exit $?
  fi
  ./makinst.sh
  ./mak.sh
  ./makshrtl.sh
  ./makfortl.sh
  ./makifstl.sh
  ./makinstl.sh
  exit $?
fi

rm -f bin/ldos.com
rm -f bin/ldos.sys
rm -f bin/ldospak.com
rm -f bin/ldospak.sys

if ! make
then
  exit $?
fi
cp -a src/BIOS/msbio.bin .
cp -a src/CMD/SHARE/share.exe .
cp -a src/CMD/FORMAT/format.com .

nocommandtracelist=0
if [ "$1" == "onlypl" ]
then
  shift
elif [ "$1" == "onlykern" ]
then
  nocommandtracelist=1
  shift
else
  [[ -z "$DOSEMU" ]] && DOSEMU=dosemu
  "$DOSEMU" -dumb -td -kt < /dev/null -K "$PWD" -E "mak.bat"
fi

notracelist=0
if [[ "$1" == "notracelist" ]]
then
  shift
  notracelist=1
fi

cp -at "${rootpath}bin" ../patchini/patldos.com
./comtoexe.sh /1 "${rootpath}bin/"patldos.com "${rootpath}bin/"patldos.exe
./lzexe.sh "${rootpath}bin/"patldos.exe
mv -t "${rootpath}bin/" patldos.exe
nasm version.asm -I src/INC/ -o tmp/version.com -l lst/version.lst "$@"
nasm comload.asm -I src/INC/ -o tmp/payload2.bin -l lst/comload.lst "$@"
nasm trail.asm -I src/INC/ -o tmp/trail.bin -l lst/trail.lst \
  -D_REVISIONID="'hg $(hg id -i) ($(hg log -r 'ancestors(.)' --template '1' | wc --bytes) ancestors), branch $(hg log -r . --template "{branch}")'" \
  "$@"
echo "0" > tmp/payload2.spc
gcc misc/sumspace.c -Wall -Og -o misc/sumspace &&
  echo "$( ./misc/sumspace tmp/payload2.bin \
      "$(perl -ne '/warning: comloadersize=([0-9]+)/ and print "$1\n";' lst/comload.lst)" \
      $(perl -ne '/^\s*[0-9]+\s+\S+.*incbin\s+"(.*)"/ and print "$1\n";' lst/comload.lst) \
    )" > tmp/payload2.spc
build_name=ldos build_pack_name=ldospak build_unpack_name=ldos \
  build_kernpl_module=lkernpl build_version_com=0 ../kernwrap/mak.sh "$@"

[ -z "$CONVLIST" ] && CONVLIST=convlist.pl

if ! (( notracelist ))
then
  echo === Creating kernel trace listing
  (cd src/BIOS/;
  cat MSBIO.LNK |
  grep -Eio '\S+\.obj' |
  sed -re 's/\\/\//g;s/\.obj/\.lst/g;s/\/inc\//\/INC\//g;s/\/dos\//\/DOS\//g' |
  xargs -n 999 -x "$CONVLIST" msbiow.map > msbio.tls)
fi

if ! (( notracelist + nocommandtracelist ))
then
  echo === Creating COMMAND trace listing
  (cd src/CMD/COMMAND/;
  cat COMMAND.LNK |
  grep -Eio '\S+\.obj' |
  sed -re 's/\\/\//g;s/\.obj/\.lst/g;s/\/inc\//\/INC\//g' |
  xargs "$CONVLIST" command.map > command.tls)
fi
