#!/usr/bin/en sh

# destination folder's name
DEST_DIR="temma_project"

# archive URL
DOWNLOAD_URL="https://github.com/Digicreon/Temma/archive/refs/tags/main.tar.gz"

# ANSI function
ansi() {
	if [ "$TERM" = "" ] || [ "$NOANSI" = "1" ]; then
		return
	fi
	if ! type tput > /dev/null; then
		return
	fi
	case "$1" in
		"reset")	tput sgr0
		;;
		"bold")		tput bold
		;;
		"dim")		tput dim
		;;
		"rev")		tput setab 4
		;;
		"red")		tput setaf 1
		;;
		"yellow")	tput setaf 3
		;;
	esac
}


echo "$(ansi rev)                                                                        $(ansi reset)"
echo "$(ansi rev)                             Temma install                              $(ansi reset)"
echo "$(ansi rev)                                                                        $(ansi reset)"
echo

# ask for destination directory
echo -n "What is the name of the destination directory to create? [$DEST_DIR] "
read DESTINATION < /dev/tty
if [ "$DESTINATION" = "" ]; then
	DESTINATION="$DEST_DIR"
fi

# check destination directory
if [ "$(echo "$DESTINATION" | cut -c 1)" = "." ]; then
	echo "$(ansi red)$(ansi bold)Error:$(ansi reset) Invalid directory name '$(ansi bold)$DESTINATION$(ansi reset)'."
	exit 1
fi
if [ -e "$DESTINATION" ]; then
	echo "$(ansi red)$(ansi bold)Error:$(ansi reset) The path '$(ansi bold)$DEST_DIR$(ansi reset)' already exists."
	exit 1
fi

# create temp file
TMP_FILE="$(mktemp temma-install-XXXXXXXX)"
if [ "$TMP_FILE" = "" ]; then
	echo "$(ansi red)$(ansi bold)Error:$(ansi reset) Unable to create temporary file."
	exit 2
fi

# download archive
curl -Ls $DOWNLOAD_URL > $TMP_FILE
if [ $? -ne 0 ] || [ ! -s $TMP_FILE ]; then
	echo "$(ansi red)$(ansi bold)Error:$(ansi reset) Unable to download file '$(ansi bold)$DOWNLOAD_URL$(ansi reset)'"
	rm -f $TMP_FILE
	exit 3
fi

# extract archive
tar xzf $TMP_FILE
if [ $? -ne 0 ]; then
	echo "$(ansi red)$(ansi bold)Error:$(ansi reset) Unable to extract archive."
	rm -f $TMP_FILE
	exit 4
fi

# rename directory
mv "Temma-main" $DESTINATION
# set folder rights
chmod -R 777 $DESTINATION/log $DESTINATION/tmp
chmod +x $DESTINATION/bin/*
# remove files
rm -f $DESTINATION/bin/validate.sh
rm -f $DESTINATION/bin/dpk_pkg-pre_script.sh
rm -f $DESTINATION/etc/dispak.conf
rm -f $DESTINATION/autoextract.sh

rm -f $TMP_FILE

echo
echo "$(ansi bold)Your Temma project is installed in '$(ansi reset)$(ansi dim)$DESTINATION$(ansi reset)$(ansi bold)'.$(ansi reset)"
echo
echo "$(ansi dim)Temma website:$(ansi reset)"
echo "  $(ansi yellow)$(ansi bold)https://www.temma.net$(ansi reset)"
echo "$(ansi dim)Installation documentation:$(ansi reset)"
echo "  $(ansi yellow)$(ansi bold)https://www.temma.net/documentation/installation$(ansi reset)"

