#this is meant to be sourced because it sets variables, not executed

set -x
set -e
set -o pipefail
set -u
datestring=$(date '+on-%Y%m-%dd%Hh%Mm%S%z')

if [ -z "$projectstring" ]
then true NEED projectstring
    exit 1
fi

# ts is in moreutils
exec >& >(ts '%.s: ' > ~/logs/$projectstring-$datestring.log)
# this is "process substitution"
date

if [ -z "${is_main_script+x}" ]
then other_scripts=..
else other_scripts=.
fi

# todo: check that this system still works with the computation of cdir_container below
ghc_version=8.6.5
stackage_version=14.27

attempt_suffix=j
#abcdefghi
#jklmnopqr
#stuvwxyz

# OPTIMIZATION for first pass, omit -p
default_profiling=-p
container=ghcbuild
#hackagepoint=
# 13.30 (somewhat arbitrarily chosen)
#hackagepoint=${hackagepoint-hackage.haskell.org,2019-07-31T20:42:25Z}
hackagepoint=hackage.haskell.org,2020-02-16T11:28:34Z
#ultimatedestination=afs
ultimatedestination=opt

# allow local overrides of variables, often container name
if [ -e $other_scripts/override.sh ]
then . $other_scripts/override.sh
fi

. $other_scripts/latest-versions.sh

hostname
pwd
git describe --always
git diff

inner=iuser
if [ "${ATHENA_SYS-}" ]
   then locker=/afs/sipb.mit.edu/project/ghc/src
	sources=$locker/tarballs
	tarballs_done=$HOME/tarballs
	random=$locker/random
	#this container location is for mkc
	if [ $container = ghcbuild ]
	then cdir_container=/scratch/kenta/kenta2/btrfs/$container/rootfs
	     dir_option="" # location specified in ~/.config/lxc/lxc.conf
	     backing=btrfs
	else cdir_container=/hdd-scratch/kenta2/b/$container
	     dir_option="--dir $cdir_container"
	     backing=dir
	fi
else # on laptop
    sources=$HOME/ghc/sources
    tarballs_done=$HOME/ghc/tarballs
    random=$HOME/ghc/random
    cdir_container=$HOME/.local/share/lxc/$container/rootfs
    dir_option="" # location specified in ~/.config/lxc/lxc.conf
    backing=btrfs
    ATHENA_SYS=amd64_ubuntu1804
fi


if [[ ( $container == ghcbuild ) && ( $PWD =~ ^/home/kenta/ghc/[0-9]+/lxc ) ]]
then echo "wrong directory or container"
     exit 1
fi

#pause before potentially drastic action
sleep 15

#we need to check --running before lxc-stop or else an undeletable file gets created in ~/.local/ which interferes with lxc-create
if [ $container = ghcbuild ]
then lxc-ls -1 --running | grep '^ghcbuild-continue$' && lxc-stop -n ghcbuild-continue || true
    lxc-destroy -n ghcbuild-continue || true
fi
lxc-ls -1 --running | grep "^${container}\$" && lxc-stop -n $container || true
lxc-destroy -n $container || true

# It looks like the "download" template can handle all kinds of new releases, e.g., s/trusty/bionic .
# See http://us.images.linuxcontainers.org/
lxc-create -t download -n $container -B $backing $dir_option -- -d ubuntu -r bionic -a amd64
lxc-start -n $container -o ~/logs/lxc-$projectstring-$datestring.log --logpriority=DEBUG -d

#these two are now dangerous as the container name changes mid way
#incontainer="lxc-attach -n $container --"
#inlocal="$incontainer sudo -u $inner"

function incontainer () {
    # cuda installs some stuff in /usr/local though nothing yet in /usr/local/bin or sbin
    lxc-attach -n $container -- env -i PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" "$@"
}

incontainer env

function inlocal () {
    incontainer sudo -u $inner "$@"
}

#setting UIDs to match the host does not work
incontainer useradd -m $inner
inlocal env
#needed for networking to start
sleep 5
# this also needs to be updated to bionic , etc.
tar cf - -C $random -h sources.list | incontainer tar xf - -C /etc/apt
incontainer apt-get update -q
inlocal dpkg -l
# how out of date is the downloaded lxc binary image?
inlocal apt-get dist-upgrade -sV


udir=/home/$inner/i
inlocal mkdir $udir
tar cf - -h user.sh | inlocal tar xf - -C $udir

if [ "$ultimatedestination" = afs ]
# we do not need to install to afs but make it potentially available just in case
then
afspath=/afs/sipb.mit.edu/project/ghc
elif [ "$ultimatedestination" = opt ]
then afspath=/opt/allthehaskell
else
echo cannot set afspath 1>&2
exit 1
fi

incontainer mkdir -p $afspath
incontainer chown $inner:$inner $afspath

# this gets overwritten by lxc/driver.sh FIXME
cat <<EOF | inlocal tee -a $udir/vars.sh
afspath=$afspath
datestring=$datestring
projectstring=$projectstring
parallel_make=8
EOF

cat <<EOF | incontainer tee /etc/sudoers.d/iuser-internet
$inner ALL = NOPASSWD: /sbin/ip link set eth0 down, /sbin/ip link set eth0 up
EOF
incontainer chmod 0440 /etc/sudoers.d/iuser-internet

function packages_install () {
    # jackd2 pops up a dialog, which (silently) hangs unless we specify FRONTEND
    incontainer env DEBIAN_FRONTEND=noninteractive apt-get install -q --no-install-recommends -y -V $@
}

function untar_built () {
    plzip -dc $tarballs_done/$1-$2.tar.lz | sha224sum
    plzip -dc $tarballs_done/$1-$2.tar.lz | b2sum
    plzip -dc $tarballs_done/$1-$2.tar.lz | inlocal tar xf - -C $afspath
    inlocal ln -s $2 $afspath/$1/current
}
