#!/usr/bin/env bash

# NB: The shebang above is not #!/bin/bash that's used
#     in the other scripts; I inherited this using the
#     "env trick" above and changed it to the hard-coded
#     path, but the pkill below never worked. As soon as
#     I changed it back to this path-based shebang, pkill
#     worked again. I don't understand why but I'm going
#     with what works.

# this is an RCP update install script
# it's called from the updater script
# to perform all steps needed to install a particular update
# (needed steps may vary depending on nature of update,
# but script will always have same name and be distributed
# in the update package file).

# 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
RCP=RCP3


# install any updated scripts
for f in bootscript keepalive launcher updatemonitor updater; do
    if [ -e $updatefolder/$f ]; then
        [ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "install is updating $f" >> $logfile
        sudo cp -pf $updatefolder/$f /home/pi/bin
        sudo chmod a+x /home/pi/bin/$f
    fi
done

# install any updated RCP config folders/files
for f in Profiles Autosave; do
    if [ -e $updatefolder/$f ]; then
        [ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "install is updating $f" >> $logfile
        sudo cp -pf -R $updatefolder/$f /home/pi
    fi
done

# install any updated GUI apps
for f in UpdateConfirm $RCP; do
    if [ -e $updatefolder/$f ]; then
        [ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "install is updating $f" >> $logfile
        sudo cp -pf $updatefolder/$f /home/pi &&
        sudo chmod a+x /home/pi/$f
    fi
done

# install any new/updated rc, profile, windows mgr, or similar config files (e.g., .xscreensaver)
# (to be clear, it copies *all* files/folders from dotcfg to /home/pi, not just hidden ones)
if [ -e $updatefolder/dotcfg ]; then
    pushd $updatefolder/dotcfg
    for f in `ls -A`; do
        [ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "install is updating $f" >> $logfile
        sudo cp -pf -R $f /home/pi
    done
    popd
fi

# kill any running version -- launcher will restart new version
[ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "install is killing RCP" >> $logfile
sudo pkill $RCP

# remove all autosave files -- format has changed w/ this release
#sudo rm /home/pi/Autosave/*

# or, if a complete reboot is needed (e.g., b/c of important
# changes to scripts which need to be immediately put into play)
#[ $logging ] && sudo echo `date +"%Y-%m-%d %H:%M:%S"` "rebooting" >> $logfile
#sudo reboot

