#!/bin/sh

if [ ! "$STUDIO_VERSION_MAJOR_MINOR" ]; then
	STUDIO_VERSION_MAJOR_MINOR=25.02
fi

if [ -z "$WORKINGDIR" ]; then
	WORKINGDIR=`pwd`
fi
if [ -z "$INIT_DIR" ]; then
	INIT_DIR=$WORKINGDIR
fi

if [ -f "$INIT_DIR/.env" ]; then
	echo Loading local environment $INIT_DIR/.env
	. "$INIT_DIR/.env"
fi

if [ -f "$INIT_DIR/set_custom_aliases" ]; then
	echo Loading custom aliases  $INIT_DIR/set_custom_aliases
	. "$INIT_DIR/set_custom_aliases"
fi

# File in which the status of the installation generation is logged
INSTALL_LOG=$WORKINGDIR/install.log
# File in which the status of the installation compilation is logged
COMPILE_LOG=$WORKINGDIR/compile.log
# Where the new delivery is set up. Warning: this directory is erased!
INSTALL_DIR=$WORKINGDIR/Eiffel_$STUDIO_VERSION_MAJOR_MINOR
# Where the final delivery is set up (local machine). Warning: directory erased too!
FINAL_INSTALL_DIR=$WORKINGDIR/Eiffel_$STUDIO_VERSION_MAJOR_MINOR
# Where documentation will be generated
DOCUMENT_DIR=$WORKINGDIR
# Where all.tar.bz2 files should be stored
EXPORT_DIR=$WORKINGDIR
SCM_DIR=$WORKINGDIR/Sources

# What repo and branch to use to export everything (ISE svn repo, and Git repo)
if [ ! "$DEFAULT_ISE_SVN" ]; then
	DEFAULT_ISE_SVN=svn://$LOGNAME@svn.ise/ise_svn/branches/Eiffel_25.02
fi
if [ ! "$ISE_SVN_REVISION" ]; then
	ISE_SVN_REVISION=HEAD
fi

if [ ! "$DEFAULT_ES_ROOT" ]; then
	# Note: it could be similar to 
	# DEFAULT_ES_ROOT=https://oauth2:{{glpat-ACCESS-TOKEN}}@gitlab.com/eiffelsoftware/es.git
	DEFAULT_ES_ROOT=https://gitlab.com/eiffelsoftware/es.git
fi
if [ ! "$DEFAULT_ES_BRANCH" ]; then
	DEFAULT_ES_BRANCH=Eiffel_25.02
fi

# This section is commented out be cause it won't work on non-bash shell
# we use the other one while waiting for a better solution
#if [ ! "$ES_REPO_ID" ]; then
#	mkdir -p /tmp/eiffelstudio_revision
#	svn checkout --config-option config:miscellany:use-commit-times=yes $DEFAULT_ORIGO_SVN_ROOT/revision /tmp/eiffelstudio_revision
#	ES_REPO_ID=$(svnversion /tmp/eiffelstudio_revision)
#fi
if [ ! "$ES_REPO_ID" ]; then
	ES_REPO_ID=HEAD
fi

# Used to create the build id on the package.
BUILD_ID=98732
# Version of GTK to build "ec"
#GTK_DIR=gtk2
GTK_DIR=gtk3

if [ ! "$INCLUDE_GTK3" ]; then
	if [ "$GTK_DIR" = "gtk3" ]; then
		#By default include GTK3
		INCLUDE_GTK3="True"
	fi
fi
if [ ! "$INCLUDE_GTK3" = "True" ]; then
	unset INCLUDE_GTK3
fi

if [ ! "$INCLUDE_GTK2" ]; then
	if [ "$GTK_DIR" = "gtk2" ]; then
		#By default include GTK2
		INCLUDE_GTK2="True"
	fi
fi
if [ ! "$INCLUDE_GTK2" = "True" ]; then
	unset INCLUDE_GTK2
fi

if [ ! "$INCLUDE_GUI" ]; then
	INCLUDE_GUI="True"
fi

case "$ISE_PLATFORM" in
	*-x86)
		# on x86, no support for GTK >= 3.22
		unset INCLUDE_GTK3
		if [ -z "$INCLUDE_GTK2" ]; then
			unset INCLUDE_GUI
		fi
		;;
	*)
		;;
esac

# Update configuration
. $INIT_DIR/update_config

# Used only when making PorterPackage to checkout the sources
NEW_EIFFEL_SRC=$WORKINGDIR/tmpdev
NEW_ISE_SRC=$NEW_EIFFEL_SRC
NEW_ISE_LIBRARY=$NEW_EIFFEL_SRC
# The following directory is going to be used to compile the compiler
FINALIZATION_DIR=$WORKINGDIR/finalized

echo > $INSTALL_LOG

# OK, this is all for user-defined data. Leave me alone now, I'll do my magic :)

# File management
# Copy all files
copy ()
{
cp -r $*
}
move ()
{
mv $*
}
md ()
{
mkdir -p $*
}
# Compress a file and move it to $EXPORT_DIR
tgz ()
{
pax -w -f $1.tar $1
bzip2 $1.tar
}
# Completely remove a directory
fullrd ()
{
rm -rf $*
}
# Remove a file
fullrf ()
{
rm -f $*
}
# Retrieve a file from the old delivery and put it in the new one
quick_move ()
{
if [ $# -eq 1 ]; then
copy $ISE_EIFFEL/$1 $INSTALL_DIR/$1 >> $INSTALL_LOG
else
copy $1 $ISE_EIFFEL/$2 $INSTALL_DIR/$2 >> $INSTALL_LOG
fi
}
# Create a directory if it doesn't exist already
safe_md ()
{
if [ ! -d $1 ]; then
if [ -f $1 ]; then
fullrf $1
fi
md $1
fi
}
# Save current path into TMP_PATH
save_path ()
{
TMP_PATH=`pwd`
}

# Helpers for the script
# Give some info on what's happening, both in the log and on the screen
remtrace ()
{
echo $*
echo -------------------------------- >> $INSTALL_LOG
echo $* >> $INSTALL_LOG
}
# Clean exit
TERMINATE ()
{
echo Exiting...
remtrace final time:
remtrace `date +%c`
PATH=$OLD_PATH
cd $INIT_DIR
}
# Exit with an error
CANCEL()
{
TERMINATE
exit 1
}

# SCM Commands: clone, export

ise_exprt ()
{
repo=$DEFAULT_ISE_SVN
path=$1
dest=$2
	# svn export from ISE svn repository $repo the path $path into path $dest

nb=1
svncmd="svn --force export --config-option config:miscellany:use-commit-times=yes $repo$path $dest"

until \
	echo $svncmd >> $INSTALL_LOG; \
	$svncmd >> $INSTALL_LOG; \
	do \
		echo "svn export .. $* failed [$nb]" >> $INSTALL_LOG
		nb=`expr $nb + 1`
		if [ "$nb" -gt 10 ]; then
			echo "More than 10 failures, exit" >> $INSTALL_LOG
			exit -1
		else
			echo "Retrying in 1 sec...";  >> $INSTALL_LOG
			sleep 1
		fi
	done
}

_get_es() {
	dir=$1
	if [ ! -d `dirname $dir` ]; then
		mkdir -p `dirname $dir`
	fi
	if [ ! -d "$dir" ]; then
		echo Get ES source into $dir >> $INSTALL_LOG
		#gitcmd=git clone --depth 1 --quiet --single-branch --branch $DEFAULT_ES_BRANCH  $DEFAULT_ES_ROOT $dir 
		gitcmd="git clone --quiet --single-branch --branch $DEFAULT_ES_BRANCH  $DEFAULT_ES_ROOT $dir "
		echo $gitcmd >> $INSTALL_LOG;

		nb=0
    	until \
    		$gitcmd >> $INSTALL_LOG; \
    	do \
    		echo "git clone ES repo into $dir failed"; >> $INSTALL_LOG
			nb=`expr $nb + 1`
			if [ "$nb" -gt 10 ]; then
				echo "More than 10 failures, exit" >> $INSTALL_LOG
				exit -1
			else
				echo "Retrying in 1 sec...";  >> $INSTALL_LOG
				sleep 1
			fi
    	done
	fi
}

es_co ()
{
if [ "$1" = "-N" ]; then
	rec=false
	shift
else
	rec=true
fi
path=$1
dest=`realpath $2`

dir="$SCM_DIR/repo-es"
_get_es $dir
case "${path}" in
	/*) dir="$dir${path}" ;;
	*) dir="$dir/${path}" ;;
esac

if [ -d "$dir" ]; then 
	if [ "$rec" = "false" ]; then
		# FIXME: hopefully the files are not modified...
		mkdir -p ${dest}
		for p in $dir/* ; do
			[ -f "$p" ] && cp -p "$p" ${dest}/.
		done
	else
		# FIXME: cp or ln or rsync ?
		ln -s "$dir" "$dest" >> $INSTALL_LOG
	fi
else
	echo "Checkout ${path} [NOT FOUND] directory $dir is missing" >> $INSTALL_LOG
fi
}

es_exprt ()
{
if [ "$1" = "-N" ]; then
	rec=false
	shift
else
	rec=true
fi
path=$1
dest=`realpath $2`

dir="$SCM_DIR/repo-es"
_get_es $dir
case "${path}" in
	/*) dir="$dir${path}" ;;
	*) dir="$dir/${path}" ;;
esac

if [ -d "$dir" ]; then
	if [ -d "${dest}" ]; then
		echo "Dir already exists" >> $INSTALL_LOG
	fi
	mkdir -p ${dest}
	if [ "$rec" = "false" ]; then
		# FIXME: hopefully the files are not modified...
		for p in $dir/* ; do
			[ -f "$p" ] && cp -p "$p" ${dest}/.
		done
	else
		# Note: even if the local files are modified, git archive gets the not modified files and dirs
		cd "$dir"
		git archive --format="tar" ${DEFAULT_ES_BRANCH} | tar -x -C ${dest}
		cd - > /dev/null
	fi
else
	echo "Export ${path} [NOT FOUND] directory $dir is missing" >> $INSTALL_LOG
fi

}


# C Compilation
default_make ()
{
save_path
$INSTALL_DIR/studio/spec/$ISE_PLATFORM/bin/finish_freezing -library >> $COMPILE_LOG
cd $TMP_PATH
}
all_makes ()
{
save_path
# What should we do??? Compile for all platforms???
cd $TMP_PATH
}
#On MacOS X you need to run `ranlib' each time you move a library.
mac_ranlib ()
{
if [ ! -d $1 ]; then
if echo "$ISE_PLATFORM" | grep "macosx" >/dev/null 2>&1; then ranlib $1; fi
fi
}
# Eiffel Compilation
# Remove a project from the current directory, if any
clean_project ()
{
if [ -d EIFGENs ]; then fullrd EIFGENs; fi
}
# Create a portable compressed archive of the C code. Parameter: name of the compressed archive file
tgz_ccode ()
{
if [ -d EIFGENs/$1/F_code ]; then
cd EIFGENs/$1
# To workaround the eventual usage of ECF_CONFIG_PATH, let us replace the full path with relative path from $EIFFEL_SRC
find F_code -type f -name 'Makefile.SH' -exec sed -i 's+'$EIFFEL_SRC'+\\\$(EIFFEL_SRC)+g' {} \; || echo sed was not found
pax -w -f F_code.tar F_code >> $INSTALL_LOG
bzip2 F_code.tar
mv F_code.tar.bz2 ../../$2
cd ../..
fi
}
# Unzip the F_code of $1, compile it, clean up
untgz_ccode ()
{
if [ -d F_code ]; then
	fullrd F_code
fi
if [ ! -f $1.tar.bz2 ]; then
	remtrace "Couldnt find $1.tar.bz2"
	CANCEL
fi
bunzip2 -c $1.tar.bz2 | tar -xf -
if [ ! -d F_code ]; then
	remtrace "No F_code for $1"
	CANCEL
fi
cd F_code
$INSTALL_DIR/studio/spec/$ISE_PLATFORM/bin/finish_freezing -silent >> $COMPILE_LOG
if [ ! -f $1 ]; then
	remtrace Couldnt generate $1
	# Do not cancel if requested by providing a 2nd argument.
	if [ -z "$2" ]; then
		CANCEL
	fi
fi
mv $1 ..
cd ..
fullrf $1.tar
fullrd F_code
}
# Finalize at the Eiffel level only
finalize ()
{
$ISE_EIFFEL/studio/spec/$ISE_PLATFORM/bin/ecb -batch -finalize -config $1 -target $2 >> $INSTALL_LOG 2>&1
if [ ! -f EIFGENs/$2/F_code/Makefile.SH ]; then
echo "Couldn't finalize $1"
CANCEL
fi
}

# Tests....
testpar ()
{
	ls $*
}

