#!/bin/bash

# http://www.nongnu.org/avr-libc/user-manual/install_tools.html

# Stop on errors
set -e
if [ ! -f .prereq ];then ./prerequise.sh;fi

source avr-file-names

TIME_START=$(date +%s)

makeDir()
{
	rm -rf "$1/"
	mkdir -p "$1"
}


echo "Downloading sources..."

if [ ! -f $NAME_GCC.tar.xz ]; then
    wget http://wareck.free.fr/cross_compilation/avr_toolchain/$NAME_GCC.tar.xz
fi


# Make AVR-GCC
NAME_GCC_BLD=${NAME_GCC}_bld
echo "Making GCC in $NAME_GCC_BLD..."
echo "Extracting..."
rm -rf $NAME_GCC/
tar xJf $NAME_GCC.tar.xz

# Patch the download_prerequisites script
cd $NAME_GCC
sed -i 's/ftp/https/g' ./contrib/download_prerequisites
./contrib/download_prerequisites
cd ..

makeDir $NAME_GCC_BLD
cd $NAME_GCC_BLD
../$NAME_GCC/configure --prefix=$PREFIX --target=avr --enable-languages=c,c++ --disable-nls --disable-libssp --disable-libada --with-dwarf2 --disable-shared --enable-static
make -j $JOBCOUNT
sudo make install-strip
cd ..


TIME_END=$(date +%s)
TIME_RUN=$(($TIME_END - $TIME_START))

echo ""
echo "Done in $TIME_RUN seconds"

exit 0