#!/bin/bash

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


cmd="start"
if [ "$1" != "" ]; then
	cmd=$(echo $1 | awk '{print tolower($0)}')
fi
if [ "$cmd" != "start" ] && [ "$cmd" != "stop" ]; then
	echo " You must execute this script with params 'start' | 'stop'"
	echo ' '
	exit 1
fi

user=$(users | awk '{print $1}')
app_basename="ScaleNautilus"
target="/usr/local/bin/$app_basename"
ftp_uri="ftp://publico:publico@ftp.grupoepelsa.com/Publica/software/TS_Update/"
logfile="/home/pcscale/scale/log/nautilus.log"


# Initialize with the current installed API version
current_major="0"
current_minor="0"
current_revision="0"
current_db_version="0"
max_db_version=$(mysql -upcscale -pepelsa pcscale -B --skip-column-names -e"SELECT Version FROM Status")
candidate=""
online=0
# Detect OS version 
dist=$(lsb_release -si)
ver=$(lsb_release -sr)
nam=$(lsb_release -sc)
desc=$(lsb_release -sd)

tracelog(){
	echo $1
	echo $(date +"[%x %X]. ")$1 >> $logfile
}

TestCPU() {
	cpu=$(pcs-cpu)
	if [ "_$cpu" = "_Generic" ]; then
		echo " This is not a Scale machine. Can't install ScaleNautilus"
		echo ' '
		exit 1
	fi
}

TestInternetConnection() {
	wget -q --spider --timeout=10 http://google.com
	if [ $? -eq 0 ]; then
		online=1
		echo "Internet connection OK!"
	else
		online=0
		echo "No internet connection!"
	fi
}

GetCurrentVersion() {
	if [ -d $target ]; then
		cd $target
		version=$(cat package.json | grep -m1 \"version\": | awk '{split($0, a, "\""); print a[4]}')
		version_number=$(echo $version | awk '{split($0, b, "-"); print b[1]}')
		current_db_version=$(echo $version | awk '{split($0, c, "-"); print c[2]}')
		current_major=$(echo $version_number | awk '{split($0, d, "."); print d[1]}')
		current_minor=$(echo $version_number | awk '{split($0, d, "."); print d[2]}')
		current_revision=$(echo $version_number | awk '{split($0, d, "."); print d[3]}')
	fi
	echo Current version: $current_major.$current_minor.$current_revision
	echo Current DB version: $current_db_version
}

TestNewCandidateVersion() {
	lines=$(curl $ftp_uri$app_basename/)
	for line in $lines
	do
		if [[ $line == $app_basename*.zip ]]; then
			echo Match $line
			db_version=$(echo $line | awk '{split($0, a, "-"); print a[3]}' | awk '{split($0, b, "."); print b[1]}')
			echo DB version. Current $current_db_version candidate: $db_version
			if [ $max_db_version -ge $db_version ]; then
				echo DB version OK
				major=$(echo $line | awk '{split($0, a, "-"); print a[2]}' | awk '{split($0, b, "."); print b[1]}')
				minor=$(echo $line | awk '{split($0, a, "-"); print a[2]}' | awk '{split($0, b, "."); print b[2]}')
				revision=$(echo $line | awk '{split($0, a, "-"); print a[2]}' | awk '{split($0, b, "."); print b[3]}')
				
				v_current=$current_major.$current_minor.$current_revision
				v_candidate=$major.$minor.$revision
				printf '%s\n%s\n' "$v_candidate" "$v_current" | sort -V -C
				is_newer=($?)
				
				if [ $db_version -gt $current_db_version ] || ([ $db_version -eq $current_db_version ] && [ $is_newer -ne 0 ]); then
					current_db_version=$db_version
					current_major=$major
					current_minor=$minor
					current_revision=$revision
					candidate=$line
				fi
			else
				echo DB version not supported!
			fi
		fi
	done
	echo Candidate: $candidate
}

InstallLogrotate() {
	pm2lr="/tmp/pm2lr"
	rotate_module="pm2-logrotate"
	if [ "$nam" = "precise" ]; then 
		rotate_module="pm2-logrotate-legacy-nodejs"
		pm2 uninstall pm2-logrotate
		rm -f /home/pcscale/.pm2/logs/pm2-logrotate-error*.log /home/pcscale/.pm2/logs/pm2-logrotate-out*.log
	fi 
	#npm list -g | grep $rotate_module > /dev/null 2>&1
	pm2 status | grep $rotate_module > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		pm2 install $rotate_module 
#		env PATH=$PATH:/usr/local/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup upstart -u pcscale --hp /home/pcscale
#		env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u pcscale --hp /home/pcscale
#		su pcscale -c"pm2 startup|grep PATH"
		line1=$(su pcscale -c"pm2 startup | grep PATH")
		line=$(echo $line1 | awk -F 'sudo ' '{print $2}')
		echo "#!/bin/bash" > $pm2lr
		echo $line >> $pm2lr
		chmod +x $pm2lr
		$pm2lr
	else
		echo $rotate_module already installed!
	fi
}

InstallNodejs() {
	current_node_version=$(node --version | awk '{split($0, a, "."); print a[1]}')
	echo Ubuntu is $nam. Nodejs version $current_node_version. --
	if [ "$nam" = "noble" ]; then
		InstallLogrotate
	elif [ "$nam" = "bionic" ]; then
		if [ "_$current_node_version" != "_v12" ]; then
			tracelog "Intalling Nodejs on $nam..."
			wget -qO- https://deb.nodesource.com/setup_12.x | bash -
			if [ $? -ne 0 ]; then
				tracelog "Nodejs repository install failed! Trying to recover..."
				dpkg --configure -a
				apt-get update
				if [ $? -eq 0 ]; then
					tracelog "APT update OK! Trying to install Nodejs..."
				fi
			fi
			apt -qq -y install nodejs npm
			npm i -g pm2
		else
			echo Nodejs already installed!
		fi
		InstallLogrotate
	elif [ "$nam" = "precise" ]; then
		if [ "_$current_node_version" != "_v6" ]; then
			tracelog "Intalling Nodejs on Precise..."
			wget -qO- https://deb.nodesource.com/setup_6.x | bash -
			if [ $? -ne 0 ]; then
				tracelog "Nodejs repository install failed! Trying to recover..."
				dpkg --configure -a
				apt-get update
				if [ $? -eq 0 ]; then
					tracelog "APT update OK! Trying to install Nodejs..."
				fi
			fi
			apt-get -qq -y --force-yes install nodejs
			npm i -g pm2@3.5.1
		else
			echo Nodejs already installed!
		fi
		InstallLogrotate
	fi
}

InstallAPI() {
	if [ "_$candidate" != "_" ]; then
		tracelog "Downloading $candidate..."
		wget --no-passive-ftp -q $ftp_uri$app_basename/$candidate -O /tmp/$candidate
		if [ $? -eq 0 ]; then
			mkdir -p $target
			unzip -qq -o /tmp/$candidate -d $target
			rm -f /tmp/$candidate
			if [ "$nam" = "precise" ]; then
				modules="precise-node_modules.zip"
				wget --no-passive-ftp -q $ftp_uri$app_basename/$modules -O /tmp/$modules
				if [ $? -eq 0 ]; then
					unzip -qq -o /tmp/$modules -d $target
					rm -f /tmp/$modules
				else
					tracelog "Download precise modules failed!"
				fi
			fi
			cd $target
			tracelog "Installing new release $candidate..."
			npm install --prod
			if [ $? -eq 0 ]; then
				tracelog "Install OK!"
			else
				tracelog "Install failed!"
			fi
		else
			tracelog "Download failed!"
		fi
	fi
}

StartAPI() {
	if [ -d $target ]; then
		cd $target
		echo Starting ScaleNautilus service... 
#		pm2 stop 0
#		pm2 delete 0
		pm2 delete index
		pm2 start build/index.js --node-args="--harmony"
		if [ $? -eq 0 ]; then
			echo "Service ScaleNautilus started OK!"
		else
			echo "Start ScaleNautilus failed!"
		fi
	fi
}




## Script ##

#TestCPU

TestInternetConnection

if [ $online -eq 1 ]; then
	InstallNodejs
	GetCurrentVersion
	TestNewCandidateVersion
	InstallAPI
fi

StartAPI
