#!/bin/bash

# this is the RCP update script
# it's called from the UpdateConfirm GUI app
# when the user confirms the installation of an update

# test whether we're logging by existence of the logfile
logfile=/home/pi/rcplog.txt
logging=$(test -e $logfile && echo 1)

# update file and folder names
updatefolder=/home/pi/updatefolder
updateprefix=IURCP
updateext=tar
installscript=install
RCP=RCP3


# remove any previous update folders and create new
[ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "updater clearing folder" >> $logfile
sudo rm -rf $updatefolder
sudo mkdir $updatefolder

# download update file with most recent modification date and unpack
[ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "updater getting files" >> $logfile
latestupdate=`find /media/pi -name $updateprefix*.$updateext -print0 | xargs -0 ls --full-time | sort -k1,1 -k2,2 | tail -1 | awk '{print $NF}'`
cp $latestupdate $updatefolder
cd $updatefolder
updatefile=`echo $latestupdate | awk -F\/ '{print $NF}'`
tar -xvf $updatefile

# run the install script that came with the update
[ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "updater running installer" >> $logfile
sudo chmod a+x $updatefolder/$installscript
sudo /bin/bash $updatefolder/$installscript

