#!/bin/bash

#set -e
#set -x

# Script to build the cross-gcc packages for each arch in a 'packages' dir,
# using sbuild. This is purely a convenience script: the source in cross-gcc can
# be built with any of the usual tools (dpkg-buildpackage, pbuilder, etc)


if [[ -n "$@" ]]; then
    cat <<EOF
Error! $0 script takes no arguments

The cross-gcc-buildall helper script automates the process of building the full
set for target architectures locally. It needs sbuild 0.64.3 or later installed
and a chroot for the target suite available.

You can build a specific target like this:

 TARGET_LIST=armhf PARALLEL=8 ./cross-gcc-buildall

which will generate a package called cross-gcc-4.9-armhf inside the
cross-gcc-packages-amd64 directory.
EOF
    exit 1
fi


# default build arch to amd64, overridable in env
buildarch=${BUILDARCH:=amd64}
# set arch to do source build on
# this is a hack - need a real buildd about now.
masterarch=${SRCARCH:=amd64}

# This script needs a suitable schroot chroot set up for sbuild to use.
# overide by setting SUITE in env
suite=${SUITE:=unstable}
chroot=$suite-$buildarch-sbuild
builddir=cross-gcc-packages-$buildarch
masterdir=cross-gcc-packages-$masterarch

SOURCEDIR=/usr/share/cross-gcc/template
PARALLEL=${PARALLEL:=2}
gcc_ver=4.9

#Set of (overrideable) supported targets
TARGET_LIST=${TARGET_LIST:=$(cat ${SOURCEDIR}/debian/targetlist)}

if [ "$buildarch" = "$masterarch" ]; then
  buildopt="-A -s"
else
  mkdir $builddir
  cp -r $masterdir/cross-gcc-${gcc_ver}-* $builddir 
fi

if [ -d $builddir ]; then
  cd $builddir
else
  echo -e "\e[31mCan't find crosstoolchains to build\e[0m"
  exit 1
fi

# This needs sbuild 0.64.3 or later (for multiarch builds)
# For each target set up foreign arch, install, build, tidy and remove
for arch in ${TARGET_LIST}; do
  pkgname=cross-gcc-${gcc_ver}-${arch}
  (cd $pkgname;  sbuild $buildopt --build=$buildarch --host=$buildarch -d $suite -c $chroot )
done

