#!/bin/bash

# morepackages/singles.list

set -x
set -e
set -o pipefail
set -u

date
echo "\$Id: singles-install.sh,v 1.39 2017/03/01 00:57:35 kenta Exp $"

version=8.0.1
#unfortunately, each new stackage requires a new compiler build, because prefix is hardcoded
stackage=lts-7.19
allow_newer=
fullsuffix=$version-$stackage-c
#using /tmp allows easier migration to other machines
localhd=/var/tmp/kenta/hdd/ghc
#indexed by stackage because hardcoded prefix
builddir=$localhd/ghc-build-$fullsuffix
basedir=/afs/sipb.mit.edu/project/ghc/arch/$ATHENA_SYS/install

# 2 = simple -v switch
cabal_verbosity=2

# Note: gcc is often found in the output of ghc --info and not PATH
my_gcc_dir=/afs/sipb.mit.edu/project/gcc-6plus
llvm_path=$localhd/full-llvm-37-gcc6/install/bin
system_path=$my_gcc_dir/bin:/usr/bin:/bin
export LD_RUN_PATH=$my_gcc_dir/lib
ls -l $LD_RUN_PATH

# GHC does not see LD_RUN_PATH, if there is another Wl rpath on the command line (and there is)
ghc_option_rpath=--ghc-option=-optl-Wl,-rpath,$my_gcc_dir/lib

# kenta has a local perl dir, which causes perl to fail if unreadable (due to unlog)
unset PERL5LIB

if [ "$1" = "local" ]
then basedir=$localhd$basedir
    #create a symlink
    test -e $localhd
#avoid misbehaving packages from doing too much harm
kdestroy
unlog
elif [ "$1" = "afs" ]
then :
else echo "specify local or afs"
    exit 1
fi
oldinstall=/var/tmp/kenta/hdd/ghc/afs/sipb.mit.edu/project/ghc/arch/amd64_ubuntu1404/install/8.0.1-lts-7.16-a/bin
target=$basedir/$fullsuffix
extrabin=$target/hackage-bin/versioned
workarea=$target/workarea
stracedir=$localhd/strace-$fullsuffix
cabalhome=$workarea/home

cabalrc=$cabalhome/.cabal
cabalconfig=$cabalrc/config

export PATH=$target/bin:$oldinstall:$system_path
hash -r

which cabal
cabal -V
which ghc
ghc --version

mkdir -p $stracedir

while read -r file
do checksum=$(perl -we 'printf("%01x",unpack("%8C*","'$file'")%16)')
    HOME=$cabalhome nice -19 strace -f -o $stracedir/$file time cabal --config-file=$cabalconfig install $allow_newer --offline --verbose=$cabal_verbosity -p --global --prefix=$target --bindir=$extrabin/$file --libdir=$target/lib-separated/$checksum --extra-include-dirs=$target/nettle  --extra-lib-dirs=$target/nettle/nettle $ghc_option_rpath $file || true ROOT FAILURE $file
done < $workarea/more-packages/20/singles.list
dirs
date
echo all done
