#!/bin/bash
#Do the whole thing using Ubuntu packages only.
set -x
set -e
set -o pipefail
set -u

date

#to destroy
# lxc-stop --name $container
# lxc-destroy --name $container

container=cbuild
inner=iuser
locker=/afs/sipb.mit.edu/project/gcc-6plus/src

#xz
gmp=6.1.2

#xz
mpfr=3.1.6

#gz
mpc=1.0.3

# isl stands for Integer Set Library.  The version of fsf is older (0.16.1) than the one at inria (0.17.1), but we use the recommended fsf version.  There is no cryptographic signature.

#bz2
#isl=0.16.1

#lets try the inria version, dl bz2 version even though xz exists
isl=0.18

#xz
gcc=7.2.0

gccpatchdir=/tmp/gccpatch
mkdir $gccpatchdir

#this container location is for mkc
lxc-create -t download -n $container --dir /scratch/kenta/kenta2/$container -- -d ubuntu -r trusty -a amd64
rm -f ~/mylxc.log
lxc-start -n $container -o ~/mylxc.log -d
incontainer="lxc-attach -n $container --"
inlocal="$incontainer sudo -u $inner"
#setting UIDs to match the host does not work
$incontainer useradd -m $inner
#needed for networking to start
sleep 5
tar cf - -C $locker sources.list | $incontainer tar xf - -C /etc/apt
$incontainer apt-get update -q

# gnat-4.8 does not install gnatgcc

if [ -n "${setuponly+x}" ]
then true exiting due to setuponly="$setuponly"
    exit 0
fi

udir=/home/$inner/i

$inlocal mkdir $udir

#in preparation for doing it twice
onedir=$udir/1
twodir=$udir/2
$inlocal mkdir $onedir
$inlocal mkdir $twodir

xzcat $locker/tarballs/gcc-$gcc.tar.xz | $inlocal tar xf - -C $twodir

tar cf - user.sh env.sh make.sh | $inlocal tar xf - -C $udir

pushd $gccpatchdir
tar xf $locker/tarballs/gcc-$gcc.tar.xz
pushd gcc-$gcc
patch -b -p0 < $locker/Makefile.def.patch
autogen Makefile.def
popd
tar cf - gcc-$gcc | $inlocal tar xf - -C $onedir
popd
rm -fr $gccpatchdir

$incontainer dpkg -l
$incontainer apt-get install -q --no-install-recommends -y dpkg-dev aptitude

$incontainer apt-get build-dep -q -y --no-install-recommends gcc-4.8
$incontainer aptitude build-dep -q -y -R gnat-4.8

for target in $onedir $twodir
do xzcat $locker/tarballs/gmp-$gmp.tar.xz | $inlocal tar xf - -C $target
xzcat $locker/tarballs/mpfr-$mpfr.tar.xz | $inlocal tar xf - -C $target
$inlocal tar xzf - -C $target < $locker/tarballs/mpc-$mpc.tar.gz
$inlocal tar xjf - -C $target < $locker/tarballs/isl-$isl.tar.bz2
done

nice time $inlocal bash $udir/user.sh $gmp $mpfr $mpc $isl $gcc
date
true $0 all done
