#!/bin/bash

# practicing stuff after making partial.tar.lz

set -x
set -e
set -u
set -o pipefail
echo '$Id: 2017-finalize.sh,v 1.12 2017/10/11 00:56:42 kenta Exp $'

date
pwd
hostname
dpkg -l

#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).  There is no cryptographic signature.

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

#xz
gcc=7.2.0
locker=/afs/sipb/project/gcc-6plus/src
if [ -z "$1" ]
    then exit 1
fi
datestring="$1"
original_path="$PATH"

install_location=/afs/sipb.mit.edu/project/gcc-6plus/.install/$datestring
buildprefix=/tmp/gcc-6plus
buildroot=$buildprefix/$datestring

function untar_extra_libs () {
    tar xf $locker/tarballs/gmp-$gmp.tar.xz
    tar xf $locker/tarballs/mpfr-$mpfr.tar.xz
    tar xf $locker/tarballs/mpc-$mpc.tar.gz
    tar xf $locker/tarballs/isl-$isl.tar.bz2
}
time rm -fr $install_location
mkdir $install_location
pushd $buildroot
time tar xf partial.tar.lz -C $install_location -I plzip
rm -fr gmp-* mpfr-* mpc-* isl-*
popd
toolsparallel=5

###############################

# we build these because libgccjit.so will need them
export PATH=$install_location/gcc/bin:$original_path
export LD_RUN_PATH=$install_location/gcc/lib64
which gcc
gcc -v

pushd $buildroot
untar_extra_libs
gmpinstall_location=$install_location/gmp
pushd gmp-$gmp
#avoid tuning exactly for this machine
CFLAGS='-O2 -pedantic -fomit-frame-pointer -m64' ./configure --prefix=$gmpinstall_location
CFLAGS='-O2 -pedantic -fomit-frame-pointer -m64' make -j$toolsparallel
CFLAGS='-O2 -pedantic -fomit-frame-pointer -m64' make check -j$toolsparallel
CFLAGS='-O2 -pedantic -fomit-frame-pointer -m64' make install
popd

pushd isl-$isl
#isl is too dumb to make this
mkdir $install_location/isl
./configure --prefix=$install_location/isl --with-gmp=$gmpinstall_location
make -j$toolsparallel
make install
popd

pushd mpfr-$mpfr
./configure --prefix=$install_location/mpfr --with-gmp=$gmpinstall_location
make -j$toolsparallel
make check -j$toolsparallel
make install
popd

pushd mpc-$mpc
./configure --prefix=$install_location/mpc --with-gmp=$gmpinstall_location --with-mpfr=$install_location/mpfr
make -j$toolsparallel
make check -j$toolsparallel
make install
popd

realsuffix=.real
mkdir $install_location/selflaunch
cat > $install_location/selflaunch/selflaunch.sh <<EOF
#!/bin/bash
LD_LIBRARY_PATH=$install_location/gcc/lib64:"\$LD_LIBRARY_PATH" $install_location/gcc/bin/\$(basename "\$0")$realsuffix "\$@"
EOF
chmod a+x $install_location/selflaunch/selflaunch.sh

pushd $install_location/gcc/bin
for file in go gofmt
do mv $file $file$realsuffix
    ln -s ../../selflaunch/selflaunch.sh $file
done
popd

mkdir $install_location/extralibs
pushd $install_location/extralibs
for file in gmp mpfr isl mpc
do ln -s ../$file/lib $file
done
popd

pushd $install_location
for file in gcc/*
do ln -s $file
done
popd

popd
dirs
true $0 all done
