#!/bin/bash
# Update utility for iEC4
# Place this script in place of 'project.exe' in the update export directory 
# that matches $RELEASE below. $RELEASE is autoupdated by generateUpdate.sh.

RELEASE=2R18_Update
MOUNT_POINT="/mnt/flashdrive"
UPDATE_PATH=$MOUNT_POINT/exports/$RELEASE
SERVER_PATH=$UPDATE_PATH/scripts/updateServer.py
BACKUP_PATH="./backup"
TMP_UPDATE="/tmp/update"
UPDATE_LOCAL=~/update

# Initialize timer
startTime=$(date +"%s" )

function addToPage {
	echo $1	
	LINE=$(cat $TMP_UPDATE/body.html | grep -n '/body' | cut -f1 -d: | tail -n 1)
        sed -i "$LINE i <br>$1" $TMP_UPDATE/body.html
}

function updatePageTime {
	while :
	do
		currentTime=$(date +"%s")
		diff=$(($currentTime-$startTime))
		timeText="$(($diff / 60))m$(($diff % 60))s"
		outputText="<br>Elapsed Time: $timeText<br>"
		sed -i "s/.*Elapsed.*/$outputText/" $TMP_UPDATE/body.html
		sleep 1
	done
}

function echoTimeStamp {
	date2=$(date +"%s")
	diff=$(($date2-$startTime))
	echo "$(($diff / 60))m$(($diff % 60))s elapsed."
}


# Start system port
sudo ifup usb0

# Connect to usb ---------------------------------------------------------------
USB_NAME="$(sudo blkid |grep 'TYPE=\"vfat\"' | grep -v 'mmc' | tail -1 | awk '{print $1}' | tr -d ':' | tr -d '\n')"
UUID="$(sudo udevadm info --query=property --name=$USB_NAME | grep 'ID_FS_UUID=' | sed 's/ID_FS_UUID=//' | tr -d '\n')"
if [ -z "$USB_NAME" ]
then

	echo "USB Flash Drive not detected"

	echo starting python server
	sudo chmod +x $UPDATE_LOCAL/scripts/usbServer.py
	python $UPDATE_LOCAL/scripts/usbServer.py &

	sleep infinity
	sudo shutdown -r now
	exit 1
fi

mkdir -p $MOUNT_POINT
sudo mount -t vfat -o rw,user,uid=$USER UUID=$UUID $MOUNT_POINT


# Verify update directory exists
UPDATE_PATH=$MOUNT_POINT/exports/$RELEASE
if [ ! -d $UPDATE_PATH ]
then
	echo "Directory $UPDATE_PATH does not exist"

	echo starting python server
	sudo chmod +x $UPDATE_LOCAL/scripts/directoryServer.py
	python $UPDATE_LOCAL/scripts/directoryServer.py &

	sleep infinity
	sudo shutdown -r now
	exit 1
else
	echo "$UPDATE_PATH exists, continuing..."
fi


# Start update message server -------------------------------------------------
# This script updates files in /tmp/html to provide status updates on web page
mkdir -p $UPDATE_LOCAL/scripts
mkdir -p $TMP_UPDATE
cp $SERVER_PATH $TMP_UPDATE
cp $UPDATE_PATH/scripts/*.html $TMP_UPDATE
cp $TMP_UPDATE/bodyBase.html $TMP_UPDATE/body.html
updatePageTime &
echo starting python server
sudo chmod +x $TMP_UPDATE/updateServer.py
python $TMP_UPDATE/updateServer.py > /dev/null &

# Create backup if it does not exist-------------------------------------------
if [ ! -d "$BACKUP_PATH" ]; then
		addToPage "Creating backup"
		mkdir -p ./backup
		cp -r ./database ./backup/database
fi

# Copy update files from usb to temp location---------------------------------
addToPage "Copying update files"

rm -rf $UPDATE_LOCAL
mkdir $UPDATE_LOCAL
UPDATE_PATH=$MOUNT_POINT/exports/$RELEASE
cp -r $UPDATE_PATH/* $UPDATE_LOCAL

echoTimeStamp

# Copy in new files ---------------------------------------------------------------
addToPage "Copying system files"

sudo chmod 777 /usr/bin/sqlite3
sudo chmod 777 $UPDATE_LOCAL/system/sqlite3
sudo cp $UPDATE_LOCAL/system/sqlite3 /usr/bin/sqlite3
sudo cp $UPDATE_LOCAL/system/uImage.var /boot/uboot/uImage.var
sudo cp $UPDATE_LOCAL/system/libsqlite3.so.0.8.6 /usr/lib/arm-linux-gnueabihf/libsqlite3.so.0.8.6
sudo cp $UPDATE_LOCAL/system/libboost_locale.so.1.49.0 /usr/local/lib/
sudo cp $UPDATE_LOCAL/system/libboost_locale.a /usr/local/lib/
sudo cp $UPDATE_LOCAL/system/e2fsck.conf /etc/
sudo ln -s /usr/local/lib/libboost_locale.so.1.49.0 /usr/local/lib/libboost_locale.so  
sudo ln -s /usr/local/lib/libboost_locale.so /usr/lib/libboost_locale.so

echoTimeStamp

# Swap in new resource files
addToPage "Updating resource files"

rm -rf ./firmware
cp -r $UPDATE_LOCAL/firmware ./firmware
rm -rf ./system
cp -r $UPDATE_LOCAL/system ./system
rm -rf ./css
cp -r $UPDATE_LOCAL/css ./css
rm -rf ./icons
cp -r $UPDATE_LOCAL/icons ./icons
rm -rf ./scripts
cp -r $UPDATE_LOCAL/scripts ./scripts
rm -rf ./locales
cp -r $UPDATE_LOCAL/locales ./locales

echoTimeStamp

# Add pre-GUI boot script.  Remove any previous mount or mountRearSD commands and put new cmd after last iptables command.
addToPage "Modifying rc.local"
cat /etc/rc.local | grep -v 'mount' | grep -v 'preGuiInit' > /tmp/rc.local
LINE=$(cat /tmp/rc.local | grep -n 'iptables' | cut -f1 -d: | tail -n 1)
sed -i "$LINE a /home/acradyne/scripts/preGuiInit.sh" /tmp/rc.local
sudo chmod 755 /tmp/rc.local
sudo cp /tmp/rc.local /etc/rc.local

addToPage "Modifying file system table"
sudo sed -i '/g4dev/d' /etc/fstab

addToPage "Updating sysctl.conf"
grep -q -F 'net.ipv4.conf.default.rp_filter=2' /etc/sysctl.conf
if [ $? -ne 0 ]; then
	# Changing rp filter because defaults prevent broadcast response from accessories from being read by controller
	echo '' | sudo tee -a /etc/sysctl.conf
	echo '#Change rp_filter to enable accessory scanning - 1R18' | sudo tee -a /etc/sysctl.conf
	grep -q -F 'net.ipv4.conf.default.rp_filter=2' /etc/sysctl.conf || echo 'net.ipv4.conf.default.rp_filter=2' | sudo tee -a /etc/sysctl.conf
	grep -q -F 'net.ipv4.conf.all.rp_filter=2' /etc/sysctl.conf || echo 'net.ipv4.conf.all.rp_filter=2' | sudo tee -a /etc/sysctl.conf
fi

# Copy into scripts directory
addToPage "Updating ~/scripts directory"
if [ ! -d ~/scripts ]; then
	mkdir ~/scripts
fi
cp $UPDATE_LOCAL/scripts/preGuiInit.sh ~/scripts/
cp $UPDATE_LOCAL/scripts/mountRearSD.sh ~/scripts/
sudo chmod +x ./scripts/*

echoTimeStamp

# Update locales
# Locale generation isn't fast so check each before generating
addToPage "Updating Locales"
LOCALEOUTPUT=$(locale -a)
echo $LOCALEOUTPUT | grep en_US
if [ $? -ne 0 ]; then
	sudo locale-gen en_US.UTF-8
fi
echo $LOCALEOUTPUT | grep es_MX
if [ $? -ne 0 ]; then
	sudo locale-gen es_MX.UTF-8
fi
echo $LOCALEOUTPUT | grep es_ES
if [ $? -ne 0 ]; then
	sudo locale-gen es_ES.UTF-8
fi
echo $LOCALEOUTPUT | grep ja_JP
if [ $? -ne 0 ]; then
	sudo locale-gen ja_JP.UTF-8
fi
echo $LOCALEOUTPUT | grep zh_CN
if [ $? -ne 0 ]; then
	sudo locale-gen zh_CN.UTF-8
fi
echo $LOCALEOUTPUT | grep de_DE
if [ $? -ne 0 ]; then
	sudo locale-gen de_DE.UTF-8
fi
echo $LOCALEOUTPUT | grep ko_KR
if [ $? -ne 0 ]; then
	sudo locale-gen ko_KR.UTF-8
fi
echo $LOCALEOUTPUT | grep hu_HU
if [ $? -ne 0 ]; then
	sudo locale-gen hu_HU.UTF-8
fi
echo $LOCALEOUTPUT | grep fr_FR
if [ $? -ne 0 ]; then
	sudo locale-gen fr_FR.UTF-8
fi
echo $LOCALEOUTPUT | grep it_IT
if [ $? -ne 0 ]; then
	sudo locale-gen it_IT.UTF-8
fi
echo $LOCALEOUTPUT | grep pt_BR
if [ $? -ne 0 ]; then
	sudo locale-gen pt_BR.UTF-8
fi
echo $LOCALEOUTPUT | grep pt_PT
if [ $? -ne 0 ]; then
	sudo locale-gen pt_PT.UTF-8
fi


echoTimeStamp

sudo ldconfig

# Convert databases ----------------------------------------------------------
#echo Converting databases
#./scripts/conversion_driver.sh
#cp ./database_conversion/converted_database/*.sqlite ./database/
#echoTimeStamp

# Unmount --------------------------------------------------------------------
addToPage "Unmounting USB"
sudo umount $MOUNT_POINT

# Stop the webpage from auto-updating
sed -i '/meta/d' $TMP_UPDATE/body.html
sleep 2

# Unlink running project.exe (update) and replace with new app exe
addToPage "Replacing executable"
rm ./bin/debug/project.exe
cp $UPDATE_LOCAL/bin/debug/project.update ./bin/debug/project.exe

addToPage "Restarting..." 

# Shut down python update server
BPID=$(ps -elf | grep updateServer.py | awk '{print $4}' | head -1) 
sudo kill $BPID

sudo shutdown -r now

# Failsafe in case shutdown doesn't happen in a timely manner
sleep 10
sudo reboot -f

