#!/bin/bash

export PATH=$PATH:/bin/:/sbin/:/usr/bin/:/usr/sbin/:
cd $(dirname $0)

LOG_FILE=lastRun.log

exec &>$LOG_FILE

msg() {

	sleep 1

	if [ $# -lt 1 ]; then
		psplashBuffer=""
		echo
		return
	fi

	while [ $# -gt 0 ]; do
		echo -e $1
		psplashBuffer="${psplashBuffer}\n$1"
		shift
	done
	
	psplash-write "MSG $( echo -e $psplashBuffer )


"
}

die(){

	msg
	msg	"$@"
	sync
	msg	"Log saved to \"$LOG_FILE\""
	
	while (true); do
		dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:200 &>/dev/null ; sleep 3
		# Reboot once the USB stick is unplugged
		[ -d "$( pwd )" ] || reboot -f
	done
}

dbus-send --print-reply --system --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:100;

killall -9 psplash
sleep 1
psplash --notouch &

[ ! -e "package.zip" ] && die "Could not find package.zip file"

# Exit kiosk mode
dbus-send --print-reply --system --dest=com.exor.JMLauncher '/' com.exor.JMLauncher.exitKiosk boolean:false || die "Failed starting package installation"

# Get the application name
rm -rf /tmp/package.info
unzip "$(pwd)/package.zip" package.info -d /tmp
pkgName="$( cat /tmp/package.info 2>/dev/null | grep '<name>' | sed 's:.*<name>\(.*\)</name>.*:\1:' )"
[ ! -e /tmp/package.info -o -z "$pkgName" ] && die "ERROR: Can not parse package"

echo Package name: $pkgName


# Start package installation in background
(
sleep 1

echo Starting package installation...
msg "Installing package..."
dbus-send --print-reply --system --reply-timeout=180000 --dest=com.exor.JMLauncher '/' com.exor.JMLauncher.install string:"$(pwd)/package.zip" || die "ERROR: Installation failed"

)&


# Start listening to dbus signals
(
while read eline; do

	( echo $eline | grep -q "member=installationFailed" ) && die "ERROR: Installation failed"

done < <(dbus-monitor --system type='signal',interface=com.exor.JMLauncher,member=installationFailed)
) &

(
while read lline; do

	( echo $lline | grep -q "member=licenseAgreementRequest" ) || continue

	# We need to accept the license so that user interaction is not needed, also there is no
	# other way for devices without touchscreen. The user should be already aware of the license agreement
	dbus-send --print-reply --system --reply-timeout=120000 --dest=com.exor.JMLauncher '/' com.exor.JMLauncher.licenseAgreed \
		string:"$pkgName" boolean:true || die "ERROR: Installation failed"

	echo License agreed!

done < <(dbus-monitor --system type='signal',interface=com.exor.JMLauncher,member=licenseAgreementRequest)
) &

while read sline; do

	( echo $sline | grep -q "member=installationSuccess" ) || continue
	
	# Check if the application is enabled
	# Returns the value between <autostart></autostart> for our package
	pkgEnabled="$( cat /mnt/data/hmi/jmlauncher.xml | tr '\n' 'N' | sed 's:</package>:</package>\n:g' | grep "<name>$pkgName</name>" | sed 's:.*<autostart>\(.*\)</autostart>.*:\1:' )"

	[ -z "$pkgEnabled" ] && die "ERROR: Failed to verify package installation"

	if [ ! "$pkgEnabled" -eq 1 ]; then
	
		echo Enabling application...
		
		# Get the current max package order number
		orderList="$(cat /mnt/data/hmi/jmlauncher.xml | grep '<order>' | sed 's:.*<order>\([0-9]*\)</order>.*:\1:' | sort -r )"
		lastIndex="$(echo $orderList | cut -d' ' -f1)"
		
		# Considering we have just installed a package we should have a value
		[ -z "$lastIndex" ] && die "ERROR: Failed to enable the application"
		
		echo Application order: $(( $lastIndex + 1 ))

		# Enable application, add it in the last position
		dbus-send --system --print-reply --dest=com.exor.JMLauncher '/' com.exor.JMLauncher.add string:"$pkgName" int32:$(( $lastIndex + 1 )) || die "ERROR: Failed to enable the application"
	fi

	sync
	msg
	msg "Installation Succesfull !"
		
	dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:100; sleep 1
	dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:100; sleep 1
	dbus-send --system --print-reply --dest=com.exor.EPAD "/Buzzer" com.exor.EPAD.Buzzer.beep int32:440 int32:100; sleep 1

	# Wait until USB stick is unplugged
	while [ -d "$( pwd )" ]; do
		sleep 5
	done
	reboot -f

done < <(dbus-monitor --system type='signal',interface=com.exor.JMLauncher,member=installationSuccess)
