#!/bin/bash

# Installs EFSTA middleware (DE) latest version (default) on 64 bits
country='DE'
if [ "$1" != "" ]; then
	version=$1
else
	version=$(curl -sL http://public.efsta.net/efr/install/de/ | grep -Eo '(/[2]\.[0-9]\.[0-9](\.([0-9]|[0-9][0-9])))' | tail -n 1 | awk '{print substr($0,2)}')
#	echo $version
fi

# Detect OS version 
dist=$(lsb_release -si)
ver=$(lsb_release -sr)
nam=$(lsb_release -sc)
desc=$(lsb_release -sd)
platform=$(uname -m)
if [ "$platform" = "x86_64" ] && [ "$nam" = "bionic" ]; then
	platform="linux64"
	zipname="EFR_${country}_${version}_install_${platform}.zip"
else
	echo "Can't install EFR on $desc ($platform)"
	exit 1
fi

user=$(users | awk '{print $1}')
target="/home/${user}/EFR"


account=`whoami`
if [ ${account} != "root" ]; then
	echo " Hi ${account}, you are NOT the supervisor."
	echo " The root permission is required to run this installer."
	echo " You must execute this script with sudo"
	echo ' '
	exit 1
fi

InstallNodejs() {
	apt-get -qq -y install nodejs
}


InstallEFR_64() {
	# Test if service exist
	if [ -d ${target} ]; then
		echo " Disabling current EFR service..."
		systemctl -q stop efr
		systemctl -q disable efr
	else
		mkdir -p ${target}
	fi
	echo " Installing EFR $version (64 bits) on $desc..."
	cd ${target}
	wget -q https://public.efsta.net/efr/install/$country/${version}/${zipname}
	if [ $? -ne 0 ]; then
		echo " ${zipname} download failed!"
		exit 1
	else
		echo " ${zipname} download OK!"
	fi
	# Installing...
	echo " Installing..."
	unzip -qq -o ${zipname} -d .
	rm -f ${zipname}
	chmod +x ${target}/run.sh
	chmod +x ${target}/app/node
	chown -R ${user}:${user} ${target}

	service='/etc/systemd/system/efr.service'
	echo "[Unit]" > ${service}
	echo "Description=EFR Service" >> ${service}
	echo " " >> ${service}
	echo "[Service]" >> ${service}
	echo "User=${user}" >> ${service}
	echo "ExecStart=/bin/bash /home/${user}/EFR/run.sh" >> ${service}
	echo "TimeoutSec=10" >> ${service}
	echo "Restart=always" >> ${service}
	echo " " >> ${service}
	echo "[Install]" >> ${service}
	echo "WantedBy=multi-user.target" >> ${service}
	
	rm -f ${target}/efr.service
	rm -f ${target}/README
	
	systemctl -q enable efr
	if [ $? -ne 0 ]; then
		echo " Error! Can't enable EFR service!"
		exit 1
	else
		systemctl -q start efr
		if [ $? -ne 0 ]; then
			echo " Error! Can't start EFR service!"
			exit 1
		fi
	fi
	echo " EFR service installed & started."
}


InstallNodejs
InstallEFR_64
