#!/bin/bash

if [ -d "$CLEAN_HOME" ]; then
	rm -rf "$CLEAN_HOME.bak"
	mv "$CLEAN_HOME" "$CLEAN_HOME.bak"
else
	rm -rf "$CLEAN_HOME"
fi
mkdir -p "$CLEAN_HOME"
for pkg in \
	base \
	abc-interpreter \
	lib-argenv \
	lib-directory \
	lib-dynamics \
	lib-gast \
	lib-graphcopy \
	lib-itasks \
	lib-platform \
	lib-stdlib \
	lib-tcpip \
	test
do
	curl ftp://ftp.cs.ru.nl/pub/Clean/builds/linux-x64/clean-$pkg-linux-x64-latest.tgz\
		| tar xz --strip-components=1 -C "$CLEAN_HOME"
done

grep -h '^[[:space:]]' "$CLEAN_HOME"/etc/*.env >> "$CLEAN_HOME/etc/IDEEnvs"
cat ~/.clean/iTasksDev.env >> "$CLEAN_HOME/etc/IDEEnvs"
tail -n +2 ~/projects/top/vm/config/IDEEnvs >> "$CLEAN_HOME/etc/IDEEnvs"

ln -s lib/exe "$CLEAN_HOME/exe"

# cloogletags
cloogletags -a -c -d "$CLEAN_HOME/lib" -o "$CLEAN_HOME/lib/tags"

link_local_file(){
	echo "$1 -> $2"
	mkdir -p "$(dirname "$CLEAN_HOME/$1")"
	if [ -f "$CLEAN_HOME/$1" ]; then
		mv "$CLEAN_HOME/$1" "$CLEAN_HOME/$1.org"
		ln -s "$(realpath --no-symlinks "$2")" "$CLEAN_HOME/$1.new"
		ln -s "$(basename "$1").new" "$CLEAN_HOME/$1"
	else
		ln -s "$(realpath --no-symlinks "$2")" "$CLEAN_HOME/$1"
	fi
}

# Local versions of binaries
#link_local_file bin/cpm ~/projects/clean/ide/cpm/cpm

link_local_file lib/exe/cocl /home/camil/projects/clean/compiler/cocl
rm $CLEAN_HOME/lib/exe/cocl
ln -s cocl.org $CLEAN_HOME/lib/exe/cocl

link_local_file bin/cleantest ~/projects/clean/test/cleantest
link_local_file bin/testproperties ~/projects/clean/test-properties/src/testproperties

link_local_file data/cleandoc-default ~/projects/clean/doc/data/cleandoc-default
link_local_file bin/cleandoc ~/projects/clean/doc/src/cleandoc

link_local_file bin/cleanprof2callgrind ~/projects/clean/cleanprof2callgrind/cleanprof2callgrind

# ABC interpreter binaries
link_local_file lib/exe/abcopt ~/projects/clean/abc-interpreter/src/abcopt
link_local_file lib/exe/bcgen ~/projects/clean/abc-interpreter/src/bcgen
link_local_file lib/exe/bclink ~/projects/clean/abc-interpreter/src/bclink
link_local_file lib/exe/bcprelink ~/projects/clean/abc-interpreter/src/bcprelink
link_local_file lib/exe/bcstrip ~/projects/clean/abc-interpreter/src/bcstrip

# completion
for f in ~/projects/clean/bash-completion/*; do
	[ -f "$f" ] || continue
	base="$(basename "$f")"
	if [[ "$base" == "Makefile" ]] || [[ "$base" == "README.md" ]] || [[ "$base" =~ .tar.gz$ ]]; then
		continue
	fi
	link_local_file "etc/completion/$base" "$f"
done