#!/bin/bash

function DeleteTempDirs() {
	cd /
	if [ $Approach -eq 1 ]; then
		umount "$ApplicationUpgradeDirectory"
	fi
	[ -e "$ApplicationUpgradeDirectory" ] && rm -rf "$ApplicationUpgradeDirectory"
	rm -f /tmp/stoprest
}

function DisplayErrorMessage() {
	DeleteTempDirs
	local Message="$( Trans "We regret to inform you that an automatic upgrade is not possible. Please contact your support agent." "$TMPDIR/wap.dic" )"
	if [ $DistroVersion -lt 412 ]; then
		echo "$Message" > /dev/vc/1
	else
		local -i Counter=0
		while [ $Counter -lt 30 ]; do
			wconnect showlicensemessage "$Message"
			[ $? -eq 0 ] && break
			sleep 1
		done
	fi
	exit 1
}

function UseArchBinary() {
	if [[ $(uname -m) == "arm"* ]]; then
		if [ -x "${USE_NAME}.arm" ]; then
			mv "${USE_NAME}.arm" "${USE_NAME}"
		fi
		if [ -x plugins/wbrowser/wbrowser.arm ]; then
			mv plugins/wbrowser/wbrowser.arm plugins/wbrowser/wbrowser
		fi
	elif [[ $(uname -m) == "x86_64" ]]; then
		rm -f config/keyconfig.xml
		if [ -x "${USE_NAME}.x86_64" ]; then
			mv "${USE_NAME}.x86_64" "${USE_NAME}"
		fi
		if [ -x plugins/wbrowser/wbrowser.x86 ]; then
			mv plugins/wbrowser/wbrowser.x86 plugins/wbrowser/wbrowser
		fi
	else
		rm -f config/keyconfig.xml
		if [ -x "${USE_NAME}.x86" ]; then
			mv "${USE_NAME}.x86" "${USE_NAME}"
		fi
		if [ -x plugins/wbrowser/wbrowser.x86 ]; then
			mv plugins/wbrowser/wbrowser.x86 plugins/wbrowser/wbrowser
		fi
	fi

	rm -f *.x86
	rm -f *.x86_64
	rm -f *.arm
	rm -f plugins/wbrowser/wbrowser.x86
	rm -f plugins/wbrowser/wbrowser.arm
}

declare -x TMPDIR="$1"
declare PENDIR="$2"

declare USE_NAME="pingwin"

# Load GrupoPIE functions
[ -f /etc/functions.grupopie ] && . /etc/functions.grupopie

# Check if it is a new install
if [ ! -d "/home/${USE_NAME}" ]; then
	mkdir -p "/home/${USE_NAME}"
	cd "/home/${USE_NAME}"

	tar -xf "$TMPDIR/data.tar"

	UseArchBinary

	if [ -f files/database.clean ]; then
		cp -f files/database.clean files/database.db
	fi

	cd "$TMPDIR"
	sync

	if [ -z "$AutoUpgrade" ]; then
		switchto "${USE_NAME}"

		killall crplus
		killall pingwin
		killall winrest
	fi

	exit 0
fi

# Upgrade Application
declare -i DistroVersion=$(( $( DistroVersion ) ))
[ $DistroVersion -lt 510 ] && DisplayErrorMessage

# Get Installed Application
declare InstalledApplication="$( CheckInstalledApplication )"
[ "$InstalledApplication" != "${USE_NAME}" ] && DisplayErrorMessage

# Gather values needed in order to proceed
declare -i InstalledMemory=$(( $( grep MemTotal /proc/meminfo | awk '{print $2}' ) / 1024 ))
declare -i UsableMemory=$(( $InstalledMemory - 100 ))
declare -i FreeStorage=$(( $( df -m | grep lvroot | awk '{print $4}' ) ))
declare -i DataBaseSize=$(( $( du -m -c /home/"${USE_NAME}"/files/database.db* | tail -n 1 | awk '{print $1}' ) ))
declare -i NeededStorage=$(( $DataBaseSize * 2 +10 ))
declare -i NeededMemory=$(( $DataBaseSize * 3 + 10 ))
declare -i NeededStorageApproach2=$(( $DataBaseSize * 3 + 10 ))
declare -ix Approach=0

# Check requirements
if [ $UsableMemory -le $NeededMemory ] || [ $FreeStorage -le $NeededStorage ]; then
	if [ $FreeStorage -le $NeededStorageApproach2 ]; then
		DisplayErrorMessage
	else
		Approach=2
	fi
else
	Approach=1
fi

if [[ $(uname -m) == "arm"* ]]; then
	Approach=2
fi

# Prepare everything
# mount new tmpfs
declare -x ApplicationUpgradeDirectory="/tmp/ApplicationUpgrade"
[ $Approach -eq 2 ] && ApplicationUpgradeDirectory="/home/${USE_NAME}.new" && echo "LowMemMode"
declare TimeTag=$( date +%H%M%S%N )
mkdir -p "$ApplicationUpgradeDirectory"
[ $? -ne 0 ] && DisplayErrorMessage
if [ $Approach -eq 1 ]; then
	mount -t tmpfs -o size=$(( $UsableMemory * 1024 * 1024 )) none "$ApplicationUpgradeDirectory"
	[ $? -ne 0 ] && DisplayErrorMessage
fi
# stop Application
> /tmp/stoprest
echo "stopping ${USE_NAME}"
declare IsStopped=""
for i in `seq 1 5`;
do
	if [ `ps ax | grep ${USE_NAME} | wc -l` -le "1" ]; then
		declare IsStopped="1"
		break
	else
		killall "${USE_NAME}"
		sleep 1
	fi
done
[ -z "$IsStopped" ] && DisplayErrorMessage
echo "${USE_NAME} stopped"
# copy files needed for upgrade
tar -C "$ApplicationUpgradeDirectory" -xf $TMPDIR/data.tar
[ $? -ne 0 ] && DisplayErrorMessage
mkdir -p "$ApplicationUpgradeDirectory"/files
[ $? -ne 0 ] && DisplayErrorMessage
cp -f /home/"${USE_NAME}"/files/database.db* "$ApplicationUpgradeDirectory"/files/
[ $? -ne 0 ] && DisplayErrorMessage

# Change to upgrade directory and upgrade. Test result in the end
cd "$ApplicationUpgradeDirectory"
[ $? -ne 0 ] && DisplayErrorMessage
UseArchBinary
./"${USE_NAME}" dbupgrade > "/home/${USE_NAME}/dbupgrade.log" 2>&1
[ $? -ne 0 ] && DisplayErrorMessage

# Copy new databases files
declare i=""
cd files
[ $? -ne 0 ] && DisplayErrorMessage
for i in database.db*; do
	cp -f "$i" "/home/${USE_NAME}/files/${i}.new"
	[ $? -ne 0 ] && DisplayErrorMessage
done
cd ..
sync

# Change to new Application. This must be an atomic operation
# install WAP
tar -C "/home/${USE_NAME}/" -xf $TMPDIR/data.tar --exclude=config*.js
for file in $(tar -tf "${TMPDIR}/data.tar" --wildcards "*config*.js"); do
  if [[ ! -f "/home/${USE_NAME}/${file}" ]]; then
    tar -C "$/home/${USE_NAME}/" -xf "${TMPDIR}/data.tar" "${file}"
  fi
  echo "$file"
done
mkdir -p "/home/${USE_NAME}/files/dbbackup-${TimeTag}"
[ -f "/home/${USE_NAME}/dbupgrade.log" ] && \
	mv -f "/home/${USE_NAME}/dbupgrade.log" "/home/${USE_NAME}/files/dbbackup-${TimeTag}"/
cd "/home/${USE_NAME}"
UseArchBinary
# Change to new Application database
cd "/home/${USE_NAME}/files"
for i in database.db*; do
	mv -f "$i" "dbbackup-${TimeTag}"/
done
cd "dbbackup-${TimeTag}"
for i in database.db*.new; do
	mv -f "$i" ../"${i:0:${#i}-4}"
done
rm -f "/home/${USE_NAME}/config/eula_accepted.txt"
cd /
sync

# All done
DeleteTempDirs
sync
