#!/bin/bash

# Script to produce source packages for the matrix of supported arches
absdir_local=$(realpath $(dirname $0))
if [ $absdir_local != "/usr/bin" ]; then
    localbuild=1
fi

if [[ -n "$@" ]]; then
    echo "Error! $0 script takes no arguments."
    echo "README.source file describes the usage. Here it is:";

    echo "============="
    if [[ -n $localbuild ]]; then
        cat $(dirname $0)/debian/README.source
    else
        cat /usr/share/doc/cross-gcc-dev/README.source
    fi
    exit 1
fi

set -x

# if we are running from /usr/bin, use the global templates path. Otherwise use
# the local one
if [[ -n $localbuild ]]; then
    SOURCEDIR=$absdir_local/template
else
    SOURCEDIR=/usr/share/cross-gcc/template
fi

gcc_ver=4.9

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

builddir=cross-gcc-packages-$masterarch

mkdir -p $builddir

# For each target make a source package configured for that target
# Including adding a target arch line to rules file
for arch in ${TARGET_LIST}; do
  rm -rf $builddir/cross-gcc-4.9-$arch

  pkgname=cross-gcc-${gcc_ver}-${arch}
  mkdir $builddir/${pkgname}
  cp -r ${SOURCEDIR}/debian $builddir/${pkgname}

  # in the tree, template/ is missing the copyright and changelog files, so I
  # copy them. When building cross-gcc-dev, these are copied into it separately
  # as well
  if [[ -n $localbuild ]]; then
      cp $absdir_local/debian/{changelog,copyright} $builddir/${pkgname}/debian
  fi

  ( cd $builddir/${pkgname}; export DEB_TARGET_ARCH=${arch}; debian/rules control;\
  sed -i -e "s/^cross-gcc/${pkgname}/g" debian/changelog;\
  sed -i -e "2 a\
  DEB_TARGET_ARCH=${arch}" debian/rules; )
done
