#!/bin/sh
#(c) Copyright Barry Kauler, 19 September 2017. Licence: GPL v3 (/usr/share/doc/legal).
#called from /init, passed params are $WKG_DRV, $WKG_DEV, "$NEWEXTRASFSLIST" "$prevVER"
#comes here if the sfs layers have changed.
#this can happen if extra sfs layers change, or a version upgrade.

WKG_DRV=$1 #ex: sda
WKG_DEV=$2 #ex: sda2
prevVER=$4
. /BOOT_SPECS #has BOOT_DISKID, BOOT_PARTNUM, BOOT_FS, BOOT_DIR, WKG_DISKID, WKG_PARTNUM, WKG_FS, WKG_DIR

sessionlayer=''
[ $SESSIONSFSflag -eq 1 ] && sessionlayer='/q_ro/session'

EXTRASFSDIRS="$(echo "$3" | sed -e 's%:%\n%g' | sed -e 's%^%/q_ro/%' | tr '\n' ' ')" #tricky, need two sed's
#these are the layers:
# /mnt/${WKG_DEV}/${WKG_DIR}.session
# if SESSIONSFSflag=1: /q_ro/session (session.sfs)
# $EXTRASFSDIRS
# /q_ro/q_sfs (q.sfs)

echo -e "\\033[1;35m$(LANG=${wkgLANG} gettext 'Fixing changed SFS layers')\\033[0;39m" #purple

#puppy linux init script in initrd, does a lot of checking for files/folders deleted
#at rw layer, but exist at a lower layer. say that a ro layer has /opt, gets deleted
#at rw layer (.wh.opt). if sfs layers change, might regret that whiteout.
#it might seem radical, but why not just delete all the whiteout files in .session?
#note, if a version upgrade, this is already done in init script.
[ ! "$prevVER" ] && find /mnt/${WKG_DEV}/${WKG_DIR}.session -mindepth 1 -type f -name '.wh.*' -delete 2>/dev/null

rm -rf /mnt/${WKG_DEV}/${WKG_DIR}.session/.wh..wh* 2>/dev/null #some whiteout folders.

#make sure that the "official" boot scripts are on top...
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/rc.d #will exist, precaution.
for onefile in functions functions4puppy functions4puppy4 rc.country rc.network_basic rc.network_eth rc.services rc.shutdown rc.sysinit rc.update
do
 [ -e /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/rc.d/${onefile} ] && rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/rc.d/${onefile}
 #however, if on a ro layer (not q.sfs), copy it up from q.sfs to top...
 for onelayer in ${sessionlayer} ${EXTRASFSDIRS}
 do
  #note, recent busybox cp supports --remove-destination (even though not in --help)
  [ -e ${onelayer}/etc/rc.d/${onefile} ] && cp -a --remove-destination /q_ro/q_sfs/etc/rc.d/${onefile} /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/rc.d/ 2>/dev/null
 done
done

#ditto, go thru more system scripts. /usr/sbin...
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/sbin
for onefile in alsaconf alsawizard app-dev-setup-readme.sh askpass background_reshape bcrypt_gui bcrypt_gui_help bootmanager burniso2cd burniso2cdTEST calcfreespace.sh cdburner-wizard check_internet childproof childproofDOT chooselocale chooselocale-OLD connectwizard connectwizard_2nd countrywizard countrywizard-OLD cups_shell delayedrun deskshortcut.sh dhcpcd_dropwait_option dotpup dotpuprox.sh download_file e2ore3.sh edit-initramfs eventmanager exploderpm filemnt firewallinstallshell firewall_ng fitimage2root fixdesk fixmenus fixPuppyPin fixscripts floppy-format.sh framebufferwizard freememappletshell gaim-autosetup.sh gaimshell gen_modem_init_string get_bluetooth_connection get_modem_alternate_device getwoof hackfontsize hostname-set icon_switcher icon_switcher_cli importfrompuppy1 indexgen.sh input-wizard installquirky ipinfo keymap-set lang2initrd legacy_grub_2013 loginmanager mailto.sh modemdisconnect modemprobe modemprobe_erase modemprobe_help modemtest momanager momanager0 mousecheck mousecheck.pupdev network_default_connect networkdisconnect partview partviewOLD pcur pdict Pdisk petget pgprs pgprs-connect pgprs-shell pmodemdiag pmonitork.sh pmonitorx.sh pmount pmovie pngoverlay.bac pngoverlay.sh popadd popup.pupdev pppconnect pppdisconnect pppsetup Pudd pup-advert-blocker pupautodetect pupcamera pupdial pupdial_init_hotpluggable pupdial_wizard_helper puppyhelp puppyinstaller puppypdf pupscan qsync quickcountry quicksetup quicksetup.pupdev qwallpaper remove_builtin report-video root2user run-as-spot save2image savesession scannerwizard.sh screeny securetelnetshell set_bg set_hwclock_type set-time-for-puppy set-xftdpi sfsget sns spacereplace systemvalues t12s t12s_msgfmt t12s_msgunfmt t12s_xgettext take-reference-snapshot timezone-set timezone-set-OLD tkgamma updategpumoduleslist.sh updatenetmoduleslist.sh upgrade-manager usb_modem_special_status usb_modeswitch_status user2root video_upgrade_wizard video-wizard wakepup2 wirelesswizard wizardwizard woofwoof xdelta_gui xf86svga336wizard xgamma-gui xinitrc_test xkbconfigmanager xorgwizard xorgwizard-automatic xorgwizard-cli xrandrshell xrandrshell-OLD xserverwizard
do
 [ -e /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/sbin/${onefile} ] && rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/sbin/${onefile}
 #however, if on a ro layer (not q.sfs), copy it up from q.sfs to top...
 for onelayer in ${sessionlayer} ${EXTRASFSDIRS}
 do
  [ -e ${onelayer}/usr/sbin/${onefile} ] && cp -a --remove-destination /q_ro/q_sfs/usr/sbin/${onefile} /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/sbin/ 2>/dev/null
 done
done
#/usr/bin...
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/bin
for onefile in cmptree dir2pet dirs2pets gtkdialog-splash lprshell lsb_release man new2dir pet2dir pet2tgz petspec pman po2mo pup2pet pupdialog pupmessage restartwm simpleosc simplevp startx tgz2pet undeb wmexit wmpoweroff wmreboot wvdialshell xterm xwin yaf-splash
do
 [ -e /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/bin/${onefile} ] && rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/bin/${onefile}
 #however, if on a ro layer (not q.sfs), copy it up from q.sfs to top...
 for onelayer in ${sessionlayer} ${EXTRASFSDIRS}
 do
  [ -e ${onelayer}/usr/bin/${onefile} ] && cp -a --remove-destination /q_ro/q_sfs/usr/bin/${onefile} /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/bin/ 2>/dev/null
 done
done
#/sbin...
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/sbin
for onefile in clean_desk_icons dir2sfs dir2tgz gtklogfileviewer init load_consolefont poweroff probedisk probedisk2 probepart pup_event_backend_firmware pup_event_backend_modprobe pup_event_backend_modprobe_protect pup_event_frontend_d reboot runlevel test-eide test-scsi
do
 [ -e /mnt/${WKG_DEV}/${WKG_DIR}.session/sbin/${onefile} ] && rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/sbin/${onefile}
 #however, if on a ro layer (not q.sfs), copy it up from q.sfs to top...
 for onelayer in ${sessionlayer} ${EXTRASFSDIRS}
 do
  [ -e ${onelayer}/sbin/${onefile} ] && cp -a --remove-destination /q_ro/q_sfs/sbin/${onefile} /mnt/${WKG_DEV}/${WKG_DIR}.session/sbin/ 2>/dev/null
 done
done
#/bin...
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/bin
for onefile in df mount ps pupkill umount
do
 [ -e /mnt/${WKG_DEV}/${WKG_DIR}.session/bin/${onefile} ] && rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/bin/${onefile}
 #however, if on a ro layer (not q.sfs), copy it up from q.sfs to top...
 for onelayer in ${sessionlayer} ${EXTRASFSDIRS}
 do
  [ -e ${onelayer}/bin/${onefile} ] && cp -a --remove-destination /q_ro/q_sfs/bin/${onefile} /mnt/${WKG_DEV}/${WKG_DIR}.session/bin/ 2>/dev/null
 done
done
#/root...
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/root
#170924 .bash_profile, .bash_login do not exist in q.sfs, delete if user-created. ref: http://murga-linux.com/puppy/viewtopic.php?p=968499#968499
for onefile in .bashrc .profile .xinitrc .bash_profile .bash_login #.Xresources .gtkrc-2.0 .Xdefaults
do
 [ -e /mnt/${WKG_DEV}/${WKG_DIR}.session/root/${onefile} ] && rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/root/${onefile}
 #however, if on a ro layer (not q.sfs), copy it up from q.sfs to top...
 for onelayer in ${sessionlayer} ${EXTRASFSDIRS}
 do
  [ -e ${onelayer}/root/${onefile} ] && cp -a --remove-destination /q_ro/q_sfs/root/${onefile} /mnt/${WKG_DEV}/${WKG_DIR}.session/root/ 2>/dev/null
 done
done

#puppy fixes rox PuppyPin and globicons in rc.update, see if we can do similar here...
#fix PuppyPin...
cntbak=0
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/root/Choices/ROX-Filer
echo '<?xml version="1.0"?>
<pinboard>' > newPuppyPin
xxsfsdirs="$(echo -n "${EXTRASFSDIRS}" | tr ' ' '\n')"
for onelayer in /mnt/${WKG_DEV}/${WKG_DIR}.session ${sessionlayer} ${EXTRASFSDIRS} /q_ro/q_sfs
do
 [ ! -f ${onelayer}/root/Choices/ROX-Filer/PuppyPin ] && continue
 while read oneline
 do
  case "$oneline" in
   *<backdrop*)
    [ $cntbak -ne 0 ] && continue
    pathspec="$(echo -n "${oneline}" | cut -f 2 -d '>' | cut -f 1 -d '<')" #ex: /usr/share/backgrounds/default.jpg
    xxspecs="$(echo -n "$xxsfsdirs" | sed -e "s%$%${pathspec}%" | tr '\n' ' ')"
    fndfile="$(ls -1 /mnt/${WKG_DEV}/${WKG_DIR}.session${pathspec} ${sessionlayer}${pathspec} ${xxspecs} /q_ro/q_sfs${pathspec} 2>/dev/null)"
    [ ! "$fndfile" ] && continue
    [ "$(grep "${pathspec}" newPuppyPin)" == "" ] && echo "$oneline" >> newPuppyPin
    cntbak=1
   ;;
   *<icon*)
    pathspec="$(echo -n "${oneline}" | cut -f 2 -d '>' | cut -f 1 -d '<')" #ex: /usr/sbin/sfsget
    xxspecs="$(echo -n "$xxsfsdirs" | sed -e "s%$%${pathspec}%" | tr '\n' ' ')"
    fndfile="$(ls -1 /mnt/${WKG_DEV}/${WKG_DIR}.session${pathspec} ${sessionlayer}${pathspec} ${xxspecs} /q_ro/q_sfs${pathspec} 2>/dev/null)"
    [ ! "$fndfile" ] && continue
    [ "$(grep "${pathspec}" newPuppyPin)" == "" ] && echo "$oneline" >> newPuppyPin
   ;;
  esac
 done <<_EOF
$(cat ${onelayer}/root/Choices/ROX-Filer/PuppyPin)
_EOF
done
echo '</pinboard>' >> newPuppyPin
cp -a -f newPuppyPin /mnt/${WKG_DEV}/${WKG_DIR}.session/root/Choices/ROX-Filer/PuppyPin
#fix globicons...
#an inconstency, user-mod to desktop, PuppyPin gets changed in
#/root/Choices/ROX-Filer/, but globicons gets copied and updated in
#/root/.config/rox.sourceforge.net/ROX-Filer/...
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.config/rox.sourceforge.net/ROX-Filer
echo '<?xml version="1.0"?>
<special-files>' > newglobicons
for onelayer in /mnt/${WKG_DEV}/${WKG_DIR}.session ${sessionlayer} ${EXTRASFSDIRS} /q_ro/q_sfs
do
 globspec=""
 [ -f ${onelayer}/root/Choices/ROX-Filer/globicons ] && globspec="${onelayer}/root/Choices/ROX-Filer/globicons"
 [ -f ${onelayer}/root/.config/rox.sourceforge.net/ROX-Filer/globicons ] && globspec="${onelayer}/root/.config/rox.sourceforge.net/ROX-Filer/globicons"
 [ ! "$globspec" ] && continue
 while read oneline
 do
  case "$oneline" in
   *<rule*)
    read oneicon #ex: <icon>/usr/local/lib/X11/pixmaps/chat48.png</icon>
    read oneend  #</rule>
    pathspec="$(echo -n "${oneline}" | cut -f 2 -d '"')" #ex: /usr/local/bin/defaultchat
    [ "$(grep "${pathspec}" newglobicons)" != "" ] && continue
    echo "${oneline}" >> newglobicons
    echo "${oneicon}" >> newglobicons
    echo "${oneend}" >> newglobicons
   ;;
  esac
 done <<_EOF
$(cat ${globspec})
_EOF
done
echo '</special-files>' >> newglobicons
cp -a -f newglobicons /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.config/rox.sourceforge.net/ROX-Filer/globicons

#some fixes have to be done after switch_root (in rc.sysinit). set a flag...
#if upgrading, this will have the previous version...
echo -n "$prevVER" /mnt/${WKG_DEV}/${WKG_DIR}.session/.sfschg.flg

#note: puppy rc.update also has language translation for PuppyPin, need to implement that.
###END###
