#!/bin/bash
# Armin Diehl <ad@ardiehl.de> 27 Dec 2020

# build vbcc for compiling test programs

VBCC=vbcc.tar.gz
VASM=vasm.tar.gz
VLINK=vlink.tar.gz
INSTALLDIR=../vc
MAKEOPT=-s

mkdir -p src build $INSTALLDIR/bin $INSTALLDIR/include $INSTALLDIR/lib

if [ ! -f src/$VBCC ]; then
	cd src
	echo "Downloading c compiler source"
	wget http://www.ibaug.de/vbcc/$VBCC || exit 1
	cd ..
fi

if [ ! -f src/$VASM ]; then
        cd src
	echo "Downloading Assembler source"
        #wget http://sun.hasenbraten.de/vasm/release/$VASM || exit 1
	wget http://sun.hasenbraten.de/vasm/daily/$VASM || exit 1
        cd ..
fi

if [ ! -f src/$VLINK ]; then
        cd src
	echo "Downloading Linker source"
        #wget http://sun.hasenbraten.de/vlink/release/$VLINK || exit 1
	wget http://sun.hasenbraten.de/vlink/daily/$VLINK || exit 1
        cd ..
fi

pushd build 2>&1 >/dev/null || exit 1
if [ ! -d vasm ]; then
	echo "Unpacking assembler"
        tar x --gunzip < ../src/$VASM || exit 1
fi


if [ ! -d vbcc ]; then
	echo "unpacking c compiler"
	tar x --gunzip < ../src/$VBCC || exit 1
fi


if [ ! -d vlink ]; then
	echo "Unpacking linker"
        tar x --gunzip < ../src/$VLINK || exit 1
fi


echo "Building linker"
pushd vlink 2>&1 >/dev/null || exit 1
make $MAKEOPT
if [ $? != 0 ]; then
	echo "*** Build failed"
	exit 1
fi
popd 2>&1 >/dev/null
echo -e "Done\n"

echo "Building Assembler"
pushd vasm 2>&1 >/dev/null || exit 1
make $MAKEOPT SYNTAX=mot CPU=m68k
if [ $? != 0 ]; then
        echo "*** Assembler Build failed"
        exit 1
fi
popd 2>&1 >/dev/null
echo -e "Done\n"

echo "Building c compiler"
pushd vbcc 2>&1 >/dev/null|| exit 1
[ -d bin ] || mkdir bin
make $MAKEOPT TARGET=m68k <../../answers
if [ $? != 0 ]; then
        echo "*** Build failed"
        exit 1
fi
echo -e "\n\nDone\n"

popd 2>&1>/dev/null
popd 2>&1>/dev/null

echo "Installing to $INSTALLDIR"
I=`pwd`
cp -f build/vbcc/bin/* $INSTALLDIR/bin || exit 1
cp -f build/vlink/vlink $INSTALLDIR/bin || exit 1
cp -f build/vasm/vasmm68k_mot build/vasm/vobjdump $INSTALLDIR/bin || exit 1
ln -sf $I/Makefile.common $INSTALLDIR/Makefile.common
ln -sf $I/eagle.ld $INSTALLDIR/eagle.ld
ln -sf $I/eagle-elf.ld $INSTALLDIR/eagle-elf.ld

echo "Build and install libc"
pushd 2>&1>/dev/null libc/libc || exit 1
make $MAKEOPT clean install
if [ $? -ne 0 ]; then
	echo "*** Build libc failed"
	exit 1
fi

echo "** install success"

exit 0

P=~/.bash_profile

grep "^export PATH=\$PATH\:$INSTALLDIR" $P >/dev/null
if [ $? -ne 0 ]; then
  echo -n "vbcc path ($INSTALLDIR) not in $P, adding "
  echo >> $P
  echo "export PATH=\$PATH:$INSTALLDIR" >> $P
  echo
fi

I=$(readlink -f $INSTALLDIR)
grep "^export VBCC=$I" $P >/dev/null
if [ $? -ne 0 ]; then
  echo -n "vbcc not in $P, adding "
  echo >> $P
  echo "export VBCC=$I" >> $P
  echo
fi


