#!/bin/sh
#(c) Copyright Barry Kauler, 30 January 2017. Licence: GPL v3 (/usr/share/doc/legal).
#simple script in initramfs to boot Easy Linux.
#text colors: 34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black
#background colors: 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
#ansi escape codes ref: https://misc.flogisoft.com/bash/tip_colors_and_formatting
#190304 complete rewrite.
#190706 reintroduce support live-cd, and run in zram.
#190713 first bootup, password gui has a back-button to lang/kbd gui.
#190714 run in zram if working-partition not found.
#190716 search for persistent storage.
#190811 redesign to be able to drop capabilities when switch_root. 190812
#190817 copy session to ram, and disable partition mounting. 190818
#190820 fix determine BASELANG for non-english.
#190821 debian xorg fbdev does not work, have alternative from pyro.
#190828 verify cp of vmlinuz, initrd, easy.sfs to wkg partition.
#190901 cannot choose "Copy session to RAM & disable drives" at first bootup.
#190913 the inbuilt easy container has label pyro or buster, fix upgrading older versions easyos.
#190914 remove more desktop icons and menu entries. copying session to ram, also load extra sfs files.
#190915 fix 190913
#190923 rc.sysinit needs login pw to run and unlock gnome-keyring. 191005 removed (archived input536).
#191101 modify error msg if BOOT_DEV not found.
#191219 add  "lockdown=confidentiality" to boot menu.
#191224 if easy.sfs mounted on /tro (via loop0), rollback fails (easy.sfs seems to delete, but isn't), hence moved rollback below unmount /tnew
#200218 use hwclock to set system time.
#200301 optional chroot instead of switch_root ***NOT USING***
#200302 run fstrim on ssd that supports TRIM.
#200303 $DATE variable, read in fscheck.
#200319 busybox fdisk faulty with my 8TB hdd, using full fdisk.
#200621 ref 200302, now have full 'hdparm' utility, can check usb drives.
#200621 ext4 journal default commit interval is 5 seconds, change to 30.
#200623 change from static /dev to devtmpfs, due to awful nvme node assignments when 2+ drives.
#200623 log stuff to /root/.initrd-debug in main f.s.
#200624 fix 200621 if ext4 does not have a journal. 200715 fix again.
#200719 xWKG_DEV override for "Copy session to RAM & unmount working-partition".
#200720 pickup "qfix=NEW"
#200726 boot- and wkg-partition the same, fsck does not work, as fscheck script cannot unmount.
#200727 revert 200719. new "qfix=lock1" for "Copy session to RAM & unmount working-partition"
#200801 new exit_to_initrd(), qfix=dropout<n> to drop out to console.
#200802 new 'nnn' file manager. /.debug.flg written by /usr/sbin/debug-initrd
#200803 user-requested lockdown, file /.lockdown.flg
#200804 revert 191219.  200805 fixes for running in ram.
#200806 .lockdown.flg cannot be in .session folder, requires pw to unencrypt.
# nor can it be in wkg-partition as it is zram0 after bootup. put it in boot-part. ref: /usr/sbin/lockdown-ram
#200807 improve exit funcs, add shfm.
#200809 fix for "job control turned off". qfix=normal to remove permanent lockdown.
#200809 lockdown: new "save" icon on desktop, replace "update" icon.
#200820 mount securityfs. enable lockdown, no longer done as kernel boot param.
#200820 also want BOOT_UUID in /etc/rc.d/PUPSTATE. do not hard-code "save" coords.
#200822 save origWKG_DIR in PUPSTATE. 200823 save BOOT_LOCK in PUPSTATE. 200824 fixes.
#200826 running in ram, mimic sfs files to same path in zram. copy all sfs's. 200827 copy more.
#200828 nearly all cp need -a param.
#200830 remove globicons file when version update. xdg fix. cp fix.
#200830 run mknod here, in case lock#2.

mount -t proc none /proc
mount -t sysfs none /sys
mount -t rootfs -o remount,rw rootfs /
ln -s /proc/mounts /etc/mtab 2> /dev/null
export PATH="/bin:/sbin"
mount -t devtmpfs devtmpfs /dev #200623

exit_to_initrd() {
 [ ! "${1}" ] && set -- " Have exited from init script at this line number"
 echo -e '\033[1;31m' #bright red
 echo -n 'Line '
 grep -n -o "${1}" ${0}
 #echo -en '\033[0;39m' #reset foreground color to default.
 echo -en '\033[1;35m' #1;35 foreground bright magenta
 echo 'Note 1: Type "exit", the init script will attempt to continue.'
 echo 'Note 2: On some PCs the keyboard does not work at this stage of bootup.'
 echo 'Note 3: if "ctrl-alt-del" not work, hold down power button to poweroff.'
 echo 'Note 4: Console text editor "mp" is available.'
 echo 'Note 5: Console file manager "shfm": Navigate with arrow keys, "!" to spawn'
 echo '        a shell, "?" popup help, "q" to quit. Help file is "/shfm.txt"'
 if [ -f /bin/nnn ];then
  echo 'Note 6: Console file manager "nnn": Same keys. Help file "/nnn.txt"'
  if [ ! -f /bin/nnn.bin ];then
   mv -f /bin/nnn /bin/nnn.bin
   echo -e '#!/bin/sh\nexec nnn.bin -c -d' > /bin/nnn
   chmod 755 /bin/nnn
  fi
  export XDG_CONFIG_HOME=/etc/nnn
  #note, i think if append /etc/nnn/plugins to $PATH, then can just have "simple" here...
  export NNN_OPEN=/etc/nnn/plugins/simple
 fi
 echo -en '\033[0;39m' #reset foreground color to default.
 export EDITOR=mp
 export SHFM_OPENER=/sbin/xdg-open #200807 for shfm file manager.
 #/bin/sh
 setsid cttyhack sh #200809 fixes "job control turned off"
}

err_exit() { #200807 call exit_to_initrd()
 echo -en '\033[1;31m' #bright red
 echo -e "ERROR: ${1}" #red
 echo "Have now dropped into a shell in the initramfs."
 echo "Please hit key combination CTRL-ALT-DEL to reboot,"
 echo "or HOLD DOWN THE POWER BUTTON TO SHUTDOWN"
 echo
 echo -en '\033[1;35m' #1;35 foreground bright magenta
 echo "The following instructions are for developers only:"
 echo -en '\033[0;39m' #reset foreground color to default.
 exit_to_initrd "$1"
}

###preset locale and kbd-layout before run X###
BASELANG=""; XKEYMAP=""
set_country_x() {
 if [ "$KEYMAP" ];then
  case $KEYMAP in
   de*|be*|br*|dk*|es*|fi*|fr*|it*|no*|se*|sv*|pt*|sg*) #171015 added sg*
    CODEPAGE="850"
   ;;
   cz*|hu*|pl*|ro*|sk*|croat*|slovene*|sr*) #150302 added sr*
    CODEPAGE="852"
   ;;
   *)
    CODEPAGE=""
   ;;
  esac
  echo -n "${KEYMAP}" > tnew/etc/keymap
  echo -n "$CODEPAGE" > tnew/etc/codepage

   X_KM='tnew/etc/X11/xorg.conf'
   xCONSKEYMAP="`cat tnew/etc/keymap`"
   [ "$xCONSKEYMAP" = "" ] && xCONSKEYMAP="us"
   case $xCONSKEYMAP in
    srp*) XKEYMAP="srp" ;;   #serbia
    az*) XKEYMAP="fr" ;;     #azerty
    wa*) XKEYMAP="fr" ;;     #wangbe
    dv*) XKEYMAP="dvorak" ;; #dvorak
    cr*) XKEYMAP="cz" ;;     #croat
    sg*) XKEYMAP="ch" ;;     #swiss-german
    sl*) XKEYMAP="si" ;;     #slovene
    sv*) XKEYMAP="se" ;;     #sweden
    uk*) XKEYMAP="gb" ;;     #united kingdom
    la*) XKEYMAP="latam" ;;  #latin american
    *)  XKEYMAP="$(echo -n "$xCONSKEYMAP" | cut -c 1-2)" ;;
   esac
   #a problem is we may have 'xkb' folder in one of two places, also variation
   # different versions of xorg...
   XKBD_PATH="dunnowhere"
   [ -f tnew/etc/X11/xkb/symbols/pc/us ] && XKBD_PATH='tnew/etc/X11/xkb/symbols/pc'
   [ -f tnew/usr/share/X11/xkb/symbols/us ] && XKBD_PATH='tnew/usr/share/X11/xkb/symbols'
   [ ! -f ${XKBD_PATH}/${XKEYMAP} ] && XKEYMAP='us' #fallback.
   currXKEYMAP="`grep '#xkeymap0' ${X_KM} | tr '\t' ' ' | tr -s ' ' | cut -f 4 -d '"'`" #'geany fix
   if [ "$currXKEYMAP" != "$XKEYMAP" ];then
    skPATTERN="s%.*#xkeymap0%	Option      \"XkbLayout\" \"${XKEYMAP}\" #xkeymap0%"
    sed -i -e "${skPATTERN}" ${X_KM}
   fi
 fi
 
 if [ "$BASELANG" ];then
  #based on code in /usr/sbin/quicksetup...
  NEWLANG=${BASELANG}'.UTF-8'
  if [ -d tnew/usr/lib/locale/${BASELANG}.utf8 ];then #see ask-country-x
   if [ ! -d /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/${BASELANG}.utf8 ];then
    mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd #190706
    cp -a -f tnew/usr/lib/locale/${BASELANG}.utf8 /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/
   fi
  else
   if [ -d /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/${BASELANG}.utf8 ];then
    if [ ! -d tnew/usr/lib/locale/${BASELANG}.utf8 ];then
     cp -a -f /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/${BASELANG}.utf8 tnew/usr/lib/locale/
    fi
   fi
  fi
  if [ ! -d tnew/usr/lib/locale/${BASELANG}.utf8 ];then #precaution.
   BASELANG="en_US"
   NEWLANG="en_US.UTF-8"
  fi
  sed -i -e "s%^LANG=.*%LANG=${NEWLANG}%" tnew/etc/profile
  case $BASELANG in
   en*)
    #er, no, really want to unload all console fonts.
    echo -n "" > tnew/etc/fontmap #well, next boot, no font will be loaded.
   ;;
   ar*|he*|iw*) #L18L no Greek. arabic, hebrew,
    echo -n 'LatArCyrHeb-16.psfu' > tnew/etc/fontmap
   ;;
   *) #L18L All European languages; new default ?!
    echo -n 'LatGrkCyr-8x16.psfu' > tnew/etc/fontmap
   ;;
  esac
 fi
}

ask_kb() { #181010
 KEYMAP=us
 #try X GUI... 190307...
 if [ -e /dev/fb0 -a "$INITRD_X_GUI" == "yes" ];then
  chroot tnew /bin/busybox ash -c "/startx ask-country-x"
  touch tnew/RETASKCOUNTRY
  if grep '^EXIT="OK"' tnew/RETASKCOUNTRY >/dev/null; then
   KEYMAP="$(grep '^COMBO_KEYBOARD.*' tnew/RETASKCOUNTRY | cut -f 2 -d '"' | cut -f 1 -d ' ')" #ex: de
   BASELANG="$(grep '^COMBO_LOCALE.*' tnew/RETASKCOUNTRY | cut -f 2 -d '"' | cut -f 1 -d ' ')" #ex: de_DE
   BASELANG="${BASELANG/@euro/}" #@euro chopped.
   #set_country_x
   return 0
  fi
 fi
 #fallback...
 #190820 need to return BASELANG...
 CURRLANG="`grep '^LANG=' tnew/etc/profile 2>/dev/null | tr -d "'" | tr -d '"' | cut -f 2 -d '='`"
 [ ! "$CURRLANG" ] && CURRLANG="en_US.UTF-8" #precaution
 BASELANG="`basename $CURRLANG .utf8`"
 BASELANG="`basename $BASELANG .UTF-8`"
 BASELANG="${BASELANG/@euro/}" #@euro chopped.
 #now ask for KEYMAP...
 echo -e '\e[1;;45m 1 azerty 2 be-latin1  3 br-abnt2  4 br-abnt   5 br-latin1-abnt2 6 br-latin1-us
 7 by     8 cf         9 croat      10 cz       11 de             12 de-latin1 
 13 dk    14 dvorak    15 dvorak-l  16 dvorak-r 17 es             18 et        
 19 fi    20 fr        21 gr        22 hu101    23 hu             24 il        
 25 it    26 jp106     27 la-latin1 28 lt       29 mk             30 nl        
 31 no    32 pl        33 pt-latin1 34 ro       35 ru             36 se        
 37 sg    38 sk-qwerty 39 sk-qwertz 40 slovene  41 srp            42 sv-latin1 
 43 uk    44 us        45 wangbe                                               \e[0;;m'
 echo -e "\\e[1;;44m Please enter the number corresponding to your keyboard layout.      
 Choose the closest match, there will be an opportunity to fine-tune 
 the layout after the desktop has loaded. Press ENTER only for US.   \\e[0;;m"
 echo -e "\\e[1;30;43m Note: on some PCs the keyboard does not work at this stage of bootup. 
 In that case, wait 5 minutes for bootup.                              \\e[0;;m"
 echo -n " Keyboard layout: "
 read -r -t 300 KBnum
 [ $? -ne 0 ] && return 1 #timed out
 KBnum=$(echo -n "$KBnum" | sed -e 's%[^0-9]%%g')
 [ ! $KBnum ] && KBnum=44
 [ $KBnum -gt 45 ] && KBnum=44
 [ $KBnum -eq 0 ] && KBnum=44
 KEYMAP="$(ls -1 /lib/keymaps | head -n ${KBnum} | tail -n 1 | sed -e 's%\.gz%%')"
 echo " ...ok, ${KEYMAP} chosen"
 return 0
}

ask_pw() { #180604
 #try X GUI...
 if [ -e /dev/fb0 -a "$INITRD_X_GUI" == "yes" ];then
  set_country_x #sets up localization and kbd in tnew.
  chroot tnew /bin/busybox ash -c "LANG="${NEWLANG}" /startx ask-pw-x ${1}"
  touch tnew/RETASKPW
  cp -a -f tnew/var/log/Xorg.0.log /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/ #190821 for debugging.
  if grep '^EXIT="BAK"' tnew/RETASKPW >/dev/null; then #190713
   return 1
  fi
  if grep '^EXIT="OK"' tnew/RETASKPW >/dev/null; then
   PW="$(grep '^PW=' tnew/RETASKPW | cut -f 2 -d '"')"
   return 0
  fi
 fi
 #fallback...
 if [ "$1" == "0" ];then
  echo -e "\\e[1;;44m Please enter a password, any characters a-z, A-Z, 0-9, any length. 
 The password will encrypt parts of the working-partition, and must 
 be remembered, as it will have to be entered at every bootup.      
 Or, just press ENTER key for no password.                          \\e[0;;m"
  while [ 1 ];do #181109
   echo -n " Password: "
   read -r -t 300 PW
   [ $? -ne 0 ] && echo #timed out
   if [ "$PW" != "" ];then
    xPW="$(echo -n "$PW" | sed -e 's%[^a-zA-Z0-9]%%g')"
    if [ "$PW" != "$xPW" ];then
     echo "\\033[1;31m Sorry, only a-z, A-Z, 0-9 characters allowed, try again \\033[0;39m" #red text.
     continue
    fi
   fi
   break
  done
#  if [ ! "$PW" ];then
#   PW="$(< /dev/urandom tr -dc 'a-zA-Z0-9' | head -c10)"
#   echo " The auto-generated password is: ${PW}"
#   echo " Pausing for 60 seconds, please write it down now!!!!"
#   sleep 60
#  fi
 else
  echo -e "\\e[1;;44m Please enter password to decrypt the working-partition \\e[0;;m"
  echo -n " Password: "
  #read PW
  PW=''
  while [ 1 ];do #echo * for each char entered...
   read -r -s -n1 pw1
   if [[ -z $pw1 ]];then
    echo; break
   else
    echo -n '*'; PW="${PW}${pw1}"
   fi
  done
 fi
 #if [ "$PW" ];then
 # PWlen=$(echo -n "$PW" | wc -m)
 # [ $PWlen -lt 16 ] && PW=${PW}`seq -s '' ${PWlen} 16` #pad to 16 chars.
 #fi
 return 0 #190713
}

load_font() {
 #2-char keymap is passed in
 case "$1" in
  az|be|br|by|cr|de|dk|es|fi|fr|gr|hu|it|nl|no|pt|ro|ru|se|sk|sl) #all european languages
   loadfont < /lib/consolefonts/LatGrkCyr-8x16.psfu
  ;;
  il) #arabic, hebrew
   loadfont < /lib/consolefonts/LatArCyrHeb-16.psfu
  ;;
 esac 
}

###mount boot partition###
mount_boot() {
 if [ "$BOOT_DRV" != "rootfs" ];then #181203
  if [ "${BOOT_FS}" == "ext4" ];then #200621 change journal commit interval from 5 to 30...
   #rw,relatime,data=ordered are the defaults anyway...
   mount -t ${BOOT_FS} -o commit=30,rw,relatime,data=ordered /dev/$BOOT_DEV /mnt/$BOOT_DEV 2>/dev/null
   RET=$? #200715 it was going to err_exit, need this $RET...
   if [ $RET -ne 0 ];then
    mount -t ${BOOT_FS} /dev/$BOOT_DEV /mnt/$BOOT_DEV #200624 fallback if no journal.
    RET=$?
   fi
  else
   mount -t ${BOOT_FS} /dev/$BOOT_DEV /mnt/$BOOT_DEV
   RET=$?
  fi
  [ $RET -ne 0 ] && err_exit "Unable to mount boot-partition ${BOOT_DEV}"
 fi
 [ ! -f /mnt/$BOOT_DEV/${BOOT_DIR}easy.sfs ] && err_exit "Boot-partition does not have file easy.sfs"
}

###temporary mount easy.sfs###
mount_tnew() {
 mkdir tro trw tnew
 mount -t squashfs -o loop,noatime /mnt/$BOOT_DEV/${BOOT_DIR}easy.sfs tro
 [ $? -ne 0 ] && err_exit "FAILED: mount -t squashfs -o loop,noatime /mnt/$BOOT_DEV/${BOOT_DIR}easy.sfs tro"
 if [ "$LAYERFS" == "aufs" ];then
  mount -t aufs -o br=trw=rw:tro=ro aufs tnew
  [ $? -ne 0 ] && err_exit "FAILED: mount -t aufs -o br=trw=rw:sro=ro aufs tnew"
 else
  mkdir twork
  mount -t overlay -o lowerdir=tro,upperdir=trw,workdir=twork overlay tnew
  [ $? -ne 0 ] && err_exit "FAILED: mount -t overlay -o lowerdir=tro,upperdir=trw,workdir=twork overlay tnew"
 fi
 mount -o bind /dev tnew/dev
 mount -o bind /proc tnew/proc
 cp -a /etc/mtab tnew/etc/
 mkdir -p tnew/dev/pts
 mount -t devpts devpts tnew/dev/pts #need this to run xterm.
 #configure so can run X...
 cp -a -f tnew/etc/X11/xorg.conf.d/10-evdev-puppy.conf / #190706 coz need it later.
 rm -f tnew/etc/X11/xorg.conf.d/*
 rm -f tnew/usr/share/X11/xorg.conf.d/* 2>/dev/null #190821
 rm -f tnew/etc/X11/Xsession.d/*
 cp -f /xorg.conf tnew/etc/X11/
 cp -f ask-country-x tnew/
 cp -f ask-pw-x tnew/
 cp -f startx tnew/
 cp -f xinitrc tnew/
 if [ -d tnew/usr/lib/xorg-alt-fbdev ];then #190821 alternative xorg and fbdev that works in initrd.
  cp -a -f tnew/usr/lib/xorg-alt-fbdev/* tnew/usr/lib/xorg/
 fi
 sed -e 's%^DISTRO_%INIT_DISTRO_%' tnew/etc/DISTRO_SPECS > /INIT_DISTRO_SPECS
. /INIT_DISTRO_SPECS
}

#190828 try to recover if cp fails...
cp_verify_func() {
 #passed params: source destination
 fsync ${2}
 cmp -s ${1} ${2}
 if [ $? -ne 0 ];then
  echo -e "\\033[1;31mThis copy failed:\\033[0;39m" #red
  echo "  cp ${1} ${2}"
  echo "  It is possible that the drive is failing."
  echo "  Attempting to copy again..."
  rm -f ${2} 2>/dev/null
  cp -a -f ${1} ${2}
  fsync ${2}
  cmp -s ${1} ${2}
  if [ $? -ne 0 ];then
   if [ "$prevVER" ];then
    echo "  Second attempt failed. Attempt recovery by restoring"
    echo "  vmlinuz, initrd and easy.sfs of previous version."
   fi
   err_exit "Second attempt to copy file failed. Maybe drive is failing."
  else
   echo "  Second attempt succeeded, but warning drive might be failing."
  fi
 fi
}

#190313 have static /dev, so will have /dev/fb0 even if no framebuffer...
#190307 display logo, -f = reduces to fit screen, keeps proportions
if [ -e /dev/fb0 ];then
 idump -f logo1920x1440.png 2>/dev/null
 [ $? -ne 0 ] && rm -f /dev/fb0 #190313
 #well, the the uefi framebuffer dimensions do not know about widescreen...
 #VxH="$(fbset | grep -o 'geometry .*' | tr -s ' ' | cut -f 2,3 -d ' ')"
 #RATIO=$((${VxH/ */}00/${VxH/* /}))
 #if [ $RATIO -gt 150 ];then #widescreen
 # idump -f logo1920x1080.png
 #else
 # idump -f logo1920x1440.png
 #fi
fi

#190706 optional BOOT_DEV, WKG_DEV passed in as kernel boot param...
[ "$boot_dev" ] && BOOT_DEV="$boot_dev"
[ "$wkg_dev" ] && WKG_DEV="$wkg_dev" #ex: zram0
#also allow override BOOT_DIR and WKG_DIR...
[ "$boot_dir" ] && zBOOT_DIR="$boot_dir"
[ "$BOOT_DIR" ] && zBOOT_DIR="$BOOT_DIR"
[ "$wkg_dir" ] && zWKG_DIR="$wkg_dir"
[ "$WKG_DIR" ] && zWKG_DIR="$WKG_DIR"
#190710 also BOOT_UUID, WKG_UUID, BOOT_LABEL, WKG_LABEL...
[ "$boot_uuid" ] && zBOOT_UUID="$boot_uuid"
[ "$BOOT_UUID" ] && zBOOT_UUID="$BOOT_UUID"
[ "$wkg_uuid" ] && zWKG_UUID="$wkg_uuid"
[ "$WKG_UUID" ] && zWKG_UUID="$WKG_UUID"
[ "$boot_label" ] && zBOOT_LABEL="$boot_label"
[ "$BOOT_LABEL" ] && zBOOT_LABEL="$BOOT_LABEL"
[ "$wkg_label" ] && zWKG_LABEL="$wkg_label"
[ "$WKG_LABEL" ] && zWKG_LABEL="$WKG_LABEL"

##200719 override for "Copy session to RAM & unmount working-partition"... 200727 remove...
#[ "$xwkg_dev" ] && xWKG_DEV="$xwkg_dev" #ex: zram0

#190128 when build with initrd inside vmlinuz, no BOOT_SPECS...
[ ! -f ./BOOT_SPECS ] && /sbin/find-boot-specs
[ ! -f ./BOOT_SPECS ] && err_exit "cannot find BOOT_SPECS file"

. /BOOT_SPECS #has BOOT_UUID, BOOT_DIR, WKG_UUID, WKG_DIR 
#190706 ...optional/alternative BOOT_LABEL, WKG_LABEL
#190706 set to something if not defined...
[ ! "$BOOT_UUID" ] && BOOT_UUID='bootuuidunknown'
[ ! "$WKG_UUID" ] && WKG_UUID='wkguuidunknown'
[ ! "$BOOT_LABEL" ] && BOOT_LABEL='bootlabelunknown'
[ ! "$WKG_LABEL" ] && WKG_LABEL='wkglabelunknown'
#kernel boot parameter overrides...
[ "$zBOOT_DIR" ] && BOOT_DIR="$zBOOT_DIR"
[ "$zWKG_DIR" ] && WKG_DIR="$zWKG_DIR"
[ "$zBOOT_UUID" ] && BOOT_UUID="$zBOOT_UUID" && BOOT_DEV="" && BOOT_LABEL=""
[ "$zWKG_UUID" ] && WKG_UUID="$zWKG_UUID" && WKG_DEV="" && WKG_LABEL=""
[ "$zBOOT_LABEL" ] && BOOT_LABEL="$zBOOT_LABEL" && BOOT_DEV="" && BOOT_UUID=""
[ "$zWKG_LABEL" ] && WKG_LABEL="$zWKG_LABEL" && WKG_DEV="" && WKG_UUID=""

export LANG=C

#170206 reintroducing aufs in the kernel:
if grep -qw aufs /proc/filesystems; then
 LAYERFS='aufs'
 RO='=ro'
else
 LAYERFS='overlay'
 RO=''
fi

SESSIONSFSflag=0 #170525 see also /usr/sbin/easy_version_control. 170924 change 1 to 0.
export SESSIONSFSflag
SALT="aprilandvincent" #190308 previously used $WKG_DISKID

###find drives###
#find the drive we are booting on (has vmlinuz, initrd, easy.sfs), and working drv...
#180601 users may forget to put a trailing slash... a leading slash is not allowed...
[ "$BOOT_DIR" ] && [ "${BOOT_DIR##*/}" ] && BOOT_DIR="${BOOT_DIR}/"
[ "$WKG_DIR" ] && [ "${WKG_DIR##*/}" ] && WKG_DIR="${WKG_DIR}/"
[ "$BOOT_DIR" ] && [ "${BOOT_DIR:0:1}" == "/" ] && BOOT_DIR="${BOOT_DIR:1:99}"
[ "$WKG_DIR" ] && [ "${WKG_DIR:0:1}" == "/" ] && WKG_DIR="${WKG_DIR:1:99}"

echo -n -e "\\033[1;35mFinding drives\\033[0;39m\n " #purple
CNT=0; Pb=0; Pw=0
[ "$WKG_LABEL" == "EASYOSZRAM" ] && WKG_DEV="zram0" #190706 200822
[ -e /dev/scd0 ] && rm -f /dev/scd* #190706 static dev nodes, these duplicate sr* nodes.
while [ $CNT -lt 20 ];do #drives may take couple seconds to become available. 180415 increase 8 to 20.
 sleep 1
 echo -n '.'
 CNT=$(($CNT+1))
 #190718 iso written to usb-stick has (ex:) /dev/sdd and dev/sdd1 both LABEL="EASYOSOPTICAL", filter-out former...
 BLKIDS="$(blkid | grep -v '[a-z]: ')"
 #ex line: /dev/sda2: LABEL="intern1p2" UUID="cd5ef69b-883d-4744-bc1d-551154131db2" TYPE="ext4"
 #190706 support BOOT_LABEL and WKG_LABEL (see woof live-cd/create-live-cd)...
 [ ! "$BOOT_DEV" ] && BOOT_DEV="$(echo "${BLKIDS}" | grep -E "\"${BOOT_UUID}\"|\"${BOOT_LABEL}\"" | cut -f 1 -d ':' | cut -f 3 -d '/')"
 [ ! "$WKG_DEV" ] && WKG_DEV="$(echo "${BLKIDS}" | grep -E "\"${WKG_UUID}\"|\"${WKG_LABEL}\"" | cut -f 1 -d ':' | cut -f 3 -d '/')"
 [ "$BOOT_DEV" -a "$WKG_DEV" ] && break
done
[ ! "$BOOT_DEV" ] && err_exit "Boot partition not found"
#[ ! "$WKG_DEV" ] && err_exit "Working partition not found"
[ ! "$WKG_DEV" ] && WKG_DEV="zram0" #190714
#export BLKIDS #190716 read in find-file

Bdevs=$(echo -n "$BOOT_DEV" | tr '\n' ' ' | wc -w) #precaution.
#190706 note, must not have both *_UUID and *_LABEL in file BOOT_SPECS
[ $Bdevs -gt 1 ] && err_exit "${Bdevs} partitions have conflicting id ${BOOT_UUID} ${BOOT_LABEL}"
Wdevs=$(echo -n "$WKG_DEV" | tr '\n' ' ' | wc -w) #precaution.
[ $Wdevs -gt 1 ] && err_exit "${Wdevs} partitions have conflicting id ${WKG_UUID} ${WKG_LABEL}"

if [ "$WKG_DEV" == "zram0" ];then #190715 190716
 #booting from iso, then BOOT_SPECS has BOOT_LABEL='EASYOSOPTICAL' and WKG_LABEL='EASYOSZRAM'
 if [ "${WKG_LABEL}${WKG_UUID}" == "EASYOSZRAMwkguuidunknown" ];then
  if [ "${BOOT_LABEL}${BOOT_UUID}" == "EASYOSOPTICALbootuuidunknown" ];then
   /sbin/find-file "easyos-persistent-iso" 1
   if [ -s /found-dev ];then
    BLKIDS="$(blkid)" #190716 just in case.
    WKG_DEV="$(cat /found-dev)"
    WKG_DIR="$(cat /found-path)"
    echo -e "\\033[1;32m  NOTICE: File easyos-persistent-iso found in ${WKG_DEV}, path /${WKG_DIR}\\033[0;39m" #green
    echo -e "\\033[1;32m          This will be used for persistent storage\\033[0;39m" #green
   else
    echo -e "\\033[1;31m  NOTICE: Create a file named easyos-persistent-iso in a drive for persistence\\033[0;39m" #red 
   fi
  fi
 fi
fi

#190817 parsing QFIX moved up, also repeated further down...
#ref: http://man7.org/linux/man-pages/man7/capabilities.7.html
CAPS_DROP='' #190812
xWKG_DEV='' #190817 200719 comment-out. 200727 restore.
DROPOUT='' #200801
LOCKDOWN='' #200803
NORMAL=0 #200809
[ "$qfix" ] && QFIX=$qfix #kernel boot param
if [ "$QFIX" ];then
 for ONEFIX in `echo -n "$QFIX" | tr ',' ' '`
 do
  case $ONEFIX in
   #cap1|CAP1) CAPS_DROP='cap_sys_mount,cap_dac_override,cap_chown,cap_fowner,cap_mknod,cap_setfcap,cap_setpcap' ;; #190812
   #cap2|CAP2) CAPS_DROP='cap_sys_mount,cap_dac_override,cap_chown,cap_fowner,cap_mknod,cap_setfcap,cap_setpcap'; xWKG_DEV='zram0' ;; #190817 copy to ram
   #cap1|CAP1) CAPS_DROP='cap_sys_mount,cap_mknod' ;; #190812 190818
   #cap2|CAP2) CAPS_DROP='cap_sys_mount,cap_mknod'; xWKG_DEV='zram0' ;; #190817 copy to ram. 190818
   cap2|CAP2) CAPS_DROP='cap_mknod'; xWKG_DEV='zram0'; LOCKDOWN='2' ;; #190818 200803 deprecated.
   lock*|LOCK*) LOCKDOWN="${ONEFIX:4:1}" ;; #200803 extract the number. note, "cap2" is deprecated.
   dropout*|DROPOUT*) DROPOUT="${ONEFIX:7:1}" ;; #200801 extract the number
   normal) NORMAL=1 ;; #200809 to remove permanent lockdown.
  esac
 done
fi
case "$LOCKDOWN" in #200803 note, see also .lockdown.flg further down script.
 1) xWKG_DEV='zram0' ;;                        #"Copy session to RAM, unmount partitions"
 2) CAPS_DROP='cap_mknod'; xWKG_DEV='zram0' ;; #"Copy session to RAM, disable drives"
esac
if [ "$LOCKDOWN" ];then #190901 200803
 LOCKkeep='0' #200805 once-only
 #cannot do this at first bootup, as not yet a session to copy to ram.
 WKGSIZEflg="$(fdisk -l /dev/${WKG_DEV} | grep -oE ' 640 MB| 640 MiB')" #200319 full fdisk "640 MiB"
 if [ "$WKGSIZEflg" ];then
  echo -e "\\033[1;31mNOTICE: NO! You do not yet have a session, doing a normal bootup\\033[0;39m" #red
  CAPS_DROP=''
  xWKG_DEV=''
  LOCKDOWN='' #200803
 fi
fi

[ "$DROPOUT" == "0" ] && exit_to_initrd " Exited from init script early, nothing yet mounted." #200801

###check if user has requested lockdown###
#200803 ref: /usr/sbin/lockdown-ram
#200806 .lockdown.flg cannot be in .session folder, put into boot-part...
mkdir -p /mnt/${BOOT_DEV}
mkdir -p /mnt/${WKG_DEV}
BOOT_FS="$(echo "$BLKIDS" | grep "^/dev/${BOOT_DEV}:" | grep -o 'TYPE="[a-z0-9]*"' | cut -f 2 -d '"')"
if [ "$LOCKDOWN" == "" -o "$DROPOUT" == "" ];then
 #temporarily mount BOOT_DEV...
 mount -t ${BOOT_FS} /dev/${BOOT_DEV} /mnt/${BOOT_DEV}
 if [ $? -eq 0 ];then
  [ $NORMAL -eq 1 ] && rm -f /mnt/${BOOT_DEV}/${BOOT_DIR}.lockdown.flg 2>/dev/null #200809
  if [ "$LOCKDOWN" == "" ];then #that is, not done at kernel boot param.
   if [ -s /mnt/${BOOT_DEV}/${BOOT_DIR}.lockdown.flg ];then
    grep -q '^lock[0-9]:[0-9]' /mnt/${BOOT_DEV}/${BOOT_DIR}.lockdown.flg
    if [ $? -eq 0 ];then
     #.lockdown.flg has "lock[1|2]:[0|1]" -- :0 once-only, :1 permanent
     LOCKspecs="$(cat /mnt/${BOOT_DEV}/${BOOT_DIR}.lockdown.flg)"
     LOCKkeep="${LOCKspecs:6:1}"
     LOCKDOWN="${LOCKspecs:4:1}"
     case "$LOCKDOWN" in #200803 note, see above, kernel param "qfix=lock[1|2]"
      1) xWKG_DEV='zram0' ;;                        #"Copy session to RAM, unmount partitions"
      2) CAPS_DROP='cap_mknod'; xWKG_DEV='zram0' ;; #"Copy session to RAM, disable drives"
     esac
     if [ "$LOCKkeep" != "1" ];then
      rm -f /mnt/${BOOT_DEV}/${BOOT_DIR}.lockdown.flg
      sync
     fi
    fi
   fi
  fi
  if [ "$DROPOUT" == "" ];then #that is, not a kernel boot param
   #200802 ref: /usr/sbin/debug-initrd  200806 .debug.flg also in boot-part...
   if [ -s /mnt/${BOOT_DEV}/${BOOT_DIR}.debug.flg ];then
    grep -q '^dropout' /mnt/${BOOT_DEV}/${BOOT_DIR}.debug.flg
    if [ $? -eq 0 ];then
     DROPOUT="$(cat /mnt/${BOOT_DEV}/${BOOT_DIR}.debug.flg)"
     DROPOUT="${DROPOUT:7:1}"
     rm -f /mnt/${BOOT_DEV}/${BOOT_DIR}.debug.flg
     sync
    fi
   fi
  fi
  umount /mnt/${BOOT_DEV}
 fi
fi

if [ "$WKG_DEV" == "zram0" -o "$xWKG_DEV" == "zram0" ];then #190706 190817
 echo ''
 if [ "$WKG_DEV" == "zram0" ];then
  echo -e "\\033[1;31mNOTICE: EasyOS will run totally in RAM, no persistent storage\\033[0;39m" #red
  WKG_DRV='zram0'
  WKG_FS='ext2'
 else
  echo -e "\\033[1;31mNOTICE: The session will be copied to RAM and EasyOS will run in RAM\\033[0;39m" #red
 fi
 xWKG_FS='ext2'
 FREEK=`grep '^MemFree:' /proc/meminfo | tr -s ' ' | cut -f 2 -d ' '`
 #allocate 3/4 of free ram times 2 (as compression is approx 2:1)...
 HALFK=$(($FREEK/2))
 QTRK=$(($HALFK/2))
 USEK=$(($HALFK+$QTRK)) #3/4
 ALLOCK=$(($USEK*2))
 echo "  Creating compressed zram. RAM allocated: ${USEK}K"
 echo "${ALLOCK}K" > /sys/block/zram0/disksize
 echo "${USEK}K" > /sys/block/zram0/mem_limit
 busybox mke2fs -L "EASYOSZRAM" -m 0 /dev/zram0 > /dev/null
 #...has to be ext2, so won't ask for password etc.
fi
if [ "$WKG_DEV" != "zram0" ];then #190817
 WKG_PARTNUM="${WKG_DEV/*[a-z]/}"
 #WKG_DRV="${WKG_DEV%%[^a-z][0-9]*}"
 WKG_DRV="${WKG_DEV%[0-9]}"
 WKG_DRV="${WKG_DRV%[0-9]}"
 [ "${WKG_DRV:0:3}" == "mmc" ] && Pw=1
 [ "${WKG_DRV:0:3}" == "nvm" ] && Pw=1
 [ $Pw -eq 1 ] && WKG_DRV="${WKG_DRV%p}"
 WKG_FS="$(echo "$BLKIDS" | grep "^/dev/${WKG_DEV}:" | grep -o 'TYPE="[a-z0-9]*"' | cut -f 2 -d '"')" #200803 moved up.
fi
#coz later on, $WKG_DEV may get changed to zram0...
origWKG_DEV="$WKG_DEV"
origWKG_FS="$WKG_FS"
origWKG_UUID="$WKG_UUID" #200809
origWKG_DIR="$WKG_DIR"   #200822

#BOOT_DRV="${BOOT_DEV%%[^a-z][0-9]*}"
BOOT_DRV="${BOOT_DEV%[0-9]}"
BOOT_DRV="${BOOT_DRV%[0-9]}"
if [ "$BOOT_DRV" == "sr" ];then #190706
 BOOT_DRV="$BOOT_DEV" #ex: sr0
 BOOT_PARTNUM=""
 sleep 5 #maybe need more time for /sys/block/sr0 to be usable.
else
 BOOT_PARTNUM="${BOOT_DEV/*[a-z]/}"
 [ "${BOOT_DRV:0:3}" == "mmc" ] && Pb=1
 [ "${BOOT_DRV:0:3}" == "nvm" ] && Pb=1
 [ $Pb -eq 1 ] && BOOT_DRV="${BOOT_DRV%p}" #remove trailing "p".
fi

export BOOT_FS WKG_FS #190314

#sanity check...
Bfs="$(echo -n "${BOOT_FS}" | grep -E 'vfat|ext|reiser|f2fs|ntfs|exfat|iso9660')" #190706 add iso9660
[ ! "$Bfs" ] && err_exit "BOOT_FS='${BOOT_FS}' Boot filesystem is incorrect"
Wfs="$(echo -n "${WKG_FS}" | grep -E 'ext|reiser|f2fs')"
[ ! "$Wfs" ] && err_exit "WKG_FS='${WKG_FS}' Working filesystem is incorrect"

echo -e "\n  Boot-partition: ${BOOT_DEV}  Working-partition: ${WKG_DEV}"
#mkdir -p /mnt/${BOOT_DEV} #200803 moved up
#mkdir -p /mnt/${WKG_DEV}

###performance measurements###
FREEK=`grep '^MemFree:' /proc/meminfo | tr -s ' ' | cut -f 2 -d ' '` #free RAM
#echo 3 > /proc/sys/vm/drop_caches #clear memory caches. note, could use "hdparm -t ..." but it is slower.
if [ "$WKG_DEV" == "zram0" ];then #190706
 TIMEs="$(dd if=/dev/zram0 of=/dev/null bs=1024 count=64 iflag=skip_bytes skip=1048576 2>&1 | grep -o '[0-9.]* seconds,' | cut -f 1 -d ' ')" #read speed.
else
 TIMEs="$(dd if=/dev/${WKG_DRV} of=/dev/null bs=1024 count=64 iflag=skip_bytes skip=1048576 2>&1 | grep -o '[0-9.]* seconds,' | cut -f 1 -d ' ')" #read speed.
fi
TIME10k=$(dc -e"${TIMEs} 10000 * p" | cut -f 1 -d '.') #cheap flash stick: usb2=140 usb3=77, be usb3=41, sandisk-extreme usb3=42, internal eMMC: 
echo "Working drive read speed test (lower the better): ${TIME10k}"

###execute TRIM on ssd###
TRIMflg=''
if [ "$WKG_FS" == "ext4" ];then #200302  200621 now have full hdparm.
 HDDflg="$(cat /sys/block/${WKG_DRV}/queue/rotational)"
 if [ "$HDDflg" == "0" ];then #0 it is an SSD
  #unfortunately, busybox hdparm will only read ata drives, not usb...
  TRIMflg="$(hdparm -I /dev/${WKG_DRV} 2>/dev/null | grep -o 'TRIM' | head -n 1)"
  #run 'fstrim' after $WKG_DEV mounted, every 20th bootup...
 fi
fi
export TRIMflg #read in /sbin/fscheck

###setup and mount working partition###
PW=''; ALLOW_ASK_PW=''; Bmntd=0
if [ "$BOOT_DEV" != "$WKG_DEV" -o "$BOOT_DRV" != "$WKG_DRV" ];then
 #maybe resize working partition to fill drive... hmmm, /proc/partitions not working...
 #Wsize=$(grep ' ${WKG_DEV}$' /proc/partitions | tr -s ' ' | rev | cut -f 2 -d ' ' | rev)
 Wsize="$(fdisk -u -l /dev/${WKG_DRV} | grep "^/dev/${WKG_DEV} " | tr -s ' ' | rev | cut -f 3 -d ' ' | rev)"
 #be very paranoid, only resize if working part is this exact size...
 #if [ $Wsize -eq 655360 ];then #current skeleton, it is 655360 (640MB).
 if [ "$Wsize" == "640M" ];then #current skeleton, it is 655360 (640MB).
  #starting sector of wkg partition...
  Wstart="$(fdisk -u -l /dev/${WKG_DRV} | grep "^/dev/${WKG_DEV} " | tr -s ' ' | rev | cut -f 6 -d ' ' | rev)"
  #need to be paranoid here, to get this right, restrict to my two skeletons...
  if [ $Wstart -eq 1310720 -o $Wstart -eq 1343488 ];then #640MB or 656MB.
   #this has to be done with all partitons in WKG_DRV unmounted...
   echo -n -e "\\033[1;35mResizing working-partition to fill drive\\033[0;39m\n " #purple
   echo -e "d\n${WKG_PARTNUM}\nn\np\n${WKG_PARTNUM}\n${Wstart}\n\nw" | fdisk -u /dev/${WKG_DRV} > /dev/null 2>&1
   #fdisk should have informed kernel to rescan partition table, however precaution...
   partprobe /dev/${WKG_DRV}
   Wnewsize="$(fdisk -u -l /dev/${WKG_DRV} | grep "^/dev/${WKG_DEV} " | tr -s ' ' | rev | cut -f 3 -d ' ' | rev)"
   ###mount boot partition###
   mount_boot
   Bmntd=1
   ###temporary mount easy.sfs###
   mount_tnew
   if [ "$Wnewsize" == "640M" ];then
    echo -e "\\033[1;31m  WARNING: unable to resize working-partition\\033[0;39m" #red
   else
    Wbad=0
    echo "  Resizing ext4 filesystem to fill ${Wnewsize} working-partition"
    #190311 want dots, as this may take awhile... 190314
    #chroot tnew /bin/busybox ash -c "/sbin/resize2fs -f /dev/${WKG_DEV} > /resize2fs.log 2>&1"
    echo "#!/bin/ash
 /sbin/resize2fs -f /dev/${WKG_DEV} > /resize2fs.log 2>&1" > tnew/resizeX
    chmod 755 tnew/resizeX
    echo "#!/bin/ash
 /resizeX &
 echo -n '  '
 while /bin/busybox pidof resizeX >/dev/null;do
  sleep 1
  echo -n '.'
 done
 echo" > tnew/resize.sh
    chmod 755 tnew/resize.sh
    chroot tnew /bin/busybox ash -c "/resize.sh"
    if grep 'Nothing to do' tnew/resize2fs.log >/dev/null; then Wbad=1; fi
    if grep 'missing' tnew/resize2fs.log >/dev/null; then Wbad=1; fi
    if grep 'Error' tnew/resize2fs.log >/dev/null; then Wbad=1; fi
    [ ! -s tnew/resize2fs.log ] && Wbad=1
    [ $Wbad -eq 1 ] && echo -e "\\033[1;31m  WARNING: unable to resize ext4 filesystem to fill ${Wnewsize} working-partition\\033[0;39m" #red
   fi
  fi
 fi
 if [ "${WKG_FS}" == "ext4" ];then #200621 change journal commit interval from 5 to 30...
  #rw,relatime,data=ordered are the defaults anyway...
  mount -t ${WKG_FS} -o commit=30,rw,relatime,data=ordered /dev/${WKG_DEV} /mnt/${WKG_DEV} 2>/dev/null
  RET=$? #200715 it was going to err_exit, need this $RET...
  if [ $RET -ne 0 ];then
   mount -t ${WKG_FS} /dev/${WKG_DEV} /mnt/${WKG_DEV} #200624 fallback if no journal
   RET=$?
  fi
 else
  mount -t ${WKG_FS} /dev/${WKG_DEV} /mnt/${WKG_DEV}
  RET=$?
 fi
 [ $RET -ne 0 ] && err_exit "Unable to mount working-partition ${WKG_DEV}"
fi
INITRD_X_GUI="$(cat /skeleton/sfs/settings/initrd/INITRD_X_GUI)" #190310 yes or no
[ -f /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/INITRD_X_GUI ] && INITRD_X_GUI="$(cat "/mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/INITRD_X_GUI")"
if [ $Bmntd -eq 0 ];then
 ###mount boot partition###
 mount_boot
 ###temporary mount easy.sfs###
 mount_tnew
fi

[ "$DROPOUT" == "1" ] && exit_to_initrd " Exited from init script, boot & wkg partitions mounted." #200801

#create $WKG_DIR...
[ "${WKG_DIR}" ] && [ ! -d /mnt/${WKG_DEV}/${WKG_DIR%/} ] && mkdir -p /mnt/${WKG_DEV}/${WKG_DIR%/} #just in case path is missing.
if [ ! -d /mnt/${WKG_DEV}/${WKG_DIR}.session ];then
 for aDIR in containers releases home sfs .tempwork #sanity check
 do
  [ -e /mnt/${WKG_DEV}/${WKG_DIR}${aDIR} ] && err_exit "/mnt/${WKG_DEV}/${WKG_DIR}${aDIR} already exists"
 done
 mkdir /mnt/${WKG_DEV}/${WKG_DIR}containers
 mkdir /mnt/${WKG_DEV}/${WKG_DIR}releases
 mkdir /mnt/${WKG_DEV}/${WKG_DIR}home
 mkdir /mnt/${WKG_DEV}/${WKG_DIR}sfs
 mkdir /mnt/${WKG_DEV}/${WKG_DIR}.session
 mkdir /mnt/${WKG_DEV}/${WKG_DIR}.tempwork
 
 #190713...
 while [ 1 ];do
  ask_kb #sets $KEYMAP & $BASELANG
  if [ $? -eq 0 ];then
   if [ "$BASELANG" ];then
    load_font ${BASELANG:0:2}
   else
    load_font ${KEYMAP:0:2}
   fi
   gunzip -c /lib/keymaps/${KEYMAP}.gz | loadkmap
   if [ "$WKG_FS" == "ext4" ];then
    ask_pw 0 #sets $PW
    [ $? -eq 1 ] && continue #back button pressed.
   fi
  fi
  break
 done
 
 echo
 if [ "$PW" ];then
  POLICY="$(echo "$PW" | e4crypt add_key -S "s:${SALT}" | tail -n 1 | cut -f 2 -d '[' | cut -f 1 -d ']')" #190308
  #need to check that ext4 f.s. is able to have encrypted folders...
  e4crypt set_policy ${POLICY} /mnt/${WKG_DEV}/${WKG_DIR}.session > e4crypt.log 2>&1
  if ! grep '^Error ' e4crypt.log >/dev/null; then
   ALLOW_ASK_PW='yes'
   cat e4crypt.log
   e4crypt set_policy ${POLICY} /mnt/${WKG_DEV}/${WKG_DIR}containers
   e4crypt set_policy ${POLICY} /mnt/${WKG_DEV}/${WKG_DIR}releases
   e4crypt set_policy ${POLICY} /mnt/${WKG_DEV}/${WKG_DIR}home
  else
   echo "Sorry, the folders in the working partition cannot be encrypted. The password will only be set for root login."
  fi
 fi
 
 cp -a -f /skeleton/containers /mnt/${WKG_DEV}/${WKG_DIR}
 #populate .session folders...
 for aCONT in `ls -1 /skeleton/containers`
 do
  cp -a -f /skeleton/containers/${aCONT}/.sessionSKEL/* /mnt/${WKG_DEV}/${WKG_DIR}containers/${aCONT}/.session/
  [ -d /skeleton/containers/${aCONT}/.sessionSKEL/.control ] && cp -a -f /skeleton/containers/${aCONT}/.sessionSKEL/.control /mnt/${WKG_DEV}/${WKG_DIR}containers/${aCONT}/.session/ #181121
 done
 cp -a -f /skeleton/releases /mnt/${WKG_DEV}/${WKG_DIR}
 cp -a -f /skeleton/home /mnt/${WKG_DEV}/${WKG_DIR}
 cp -a -f /skeleton/sfs /mnt/${WKG_DEV}/${WKG_DIR}
 echo "KEYMAP='${KEYMAP}'" > /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
 echo "BASELANG='${BASELANG}'" >> /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
 echo "ALLOW_ASK_PW='${ALLOW_ASK_PW}'" >> /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
else
 POLICYflg="$(e4crypt get_policy /mnt/${WKG_DEV}/${WKG_DIR}home | grep -o '^Error')" #"Error" if no encryption.
 if [ "$POLICYflg" == "" ];then
  ###precaution stuff... upgrading from pre-1.0.12
  mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd
  [ -f /mnt/${WKG_DEV}/${WKG_DIR}sfs/CONFIG ] && mv -f /mnt/${WKG_DEV}/${WKG_DIR}sfs/CONFIG /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/
  touch /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
  ###...end precaution stuff
  . /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG #has KEYMAP, BASELANG, ALLOW_ASK_PW
  ###precaution stuff...
  if [ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/keymap ];then #just in case.
   zKEYMAP="$(cat /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/keymap)"
   if [ "$zKEYMAP" != "$KEYMAP" ];then
    KEYMAP="$zKEYMAP"
    sed -i '/KEYMAP/d' /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
    echo "KEYMAP='${KEYMAP}'" >> /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
   fi
  fi
  if [ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/profile ];then
   zBASELANG="$(grep '^LANG=.*' /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/profile | tr -d '"' | tr -d "'" | cut -f 2 -d '=' | cut -f 1 -d '.')"
   if [ "$zBASELANG" != "$BASELANG" ];then
    BASELANG="$zBASELANG"
    sed -i '/BASELANG/d' /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
    echo "BASELANG='${BASELANG}'" >> /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/CONFIG
   fi
  fi
  [ ! "$KEYMAP" ] && KEYMAP=us
  [ ! "$BASELANG" ] && BASELANG='en_US'
  if [ -d /mnt/${WKG_DEV}/${WKG_DIR}sfs/${BASELANG}.utf8 ];then #pre-1.0.12
   mv -f /mnt/${WKG_DEV}/${WKG_DIR}sfs/${BASELANG}.utf8 /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/
  fi
  if [ ! -d /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/${BASELANG}.utf8 ];then #precaution.
   if [ -d /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/lib/locale/${BASELANG}.utf8 ];then
    cp -a /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/lib/locale/${BASELANG}.utf8 /mnt/${WKG_DEV}/${WKG_DIR}sfs/settings/initrd/
   fi
  fi
  ###...end precaution stuff
  if [ "$BASELANG" ];then
   load_font ${BASELANG:0:2}
  else
   load_font ${KEYMAP:0:2}
  fi
  [ "$KEYMAP" != "us" ] && gunzip -c /lib/keymaps/${KEYMAP}.gz | loadkmap
  echo
  if [ "$ALLOW_ASK_PW" == "yes" ];then
   while [ 1 ];do
    ask_pw 1 #sets $PW
    #190308 problem, earlier releases used a different salt, $WKG_DISKID...
    POLICY="$(echo "$PW" | e4crypt add_key -S "s:${SALT}" | tail -n 1 | cut -f 2 -d '[' | cut -f 1 -d ']')"
    [  -d /mnt/${WKG_DEV}/${WKG_DIR}home/downloads ] && break
    chroot tnew /bin/busybox ash -c "/sbin/fdisk -l /dev/${WKG_DRV} > /fdisk.log 2>&1"
    WKG_DISKID="$(grep '^Disk identifier:' tnew/fdisk.log | cut -f 3 -d ' ')"
    POLICY="$(echo "$PW" | e4crypt add_key -S "s:${WKG_DISKID}" | tail -n 1 | cut -f 2 -d '[' | cut -f 1 -d ']')"
    [  -d /mnt/${WKG_DEV}/${WKG_DIR}home/downloads ] && break
    echo -e "\n\\e[1;30;43m Password incorrect. Try again \\e[0;;m"
   done
   echo
  fi
 fi
fi

###save BOOT_SPECS###
#/usr/sbin/edit-initramfs reads this, makes fixing initrd easier... 190706 sr* is read-only...
[ "$BOOT_DEV" != "sr0" -a "$BOOT_DEV" != "sr1" ] && cp -a -f /BOOT_SPECS /mnt/${BOOT_DEV}/${BOOT_DIR}.BOOT_SPECS

###preset country settings for after switch_root###
if [ "$KEYMAP" ];then
 if [ ! -s /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/keymap ];then
  mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/etc
  echo -n "$KEYMAP" > /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/keymap
 fi
fi
if [ "$XKEYMAP" ];then
 if [ ! -s /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/X11/xorg.conf.d/10-evdev-puppy.conf ];then
  mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/X11/xorg.conf.d
  if [ "$currXKEYMAP" != "$XKEYMAP" ];then #ref: set_country_x
   cp -f /10-evdev-puppy.conf /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/X11/xorg.conf.d/ #190706 file was saved earlier.
   skPATTERN="s%.*#xkeymap0%	Option      \"XkbLayout\" \"${XKEYMAP}\" #xkeymap0%"
   sed -i -e "${skPATTERN}" /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/X11/xorg.conf.d/10-evdev-puppy.conf
  fi
 fi
fi
if [ "$BASELANG" ];then
 if [ ! -d /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/lib/locale/${BASELANG}.utf8 ];then
  mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/lib/locale
  cp -a -f tnew/usr/lib/locale/${BASELANG}.utf8 /mnt/${WKG_DEV}/${WKG_DIR}.session/usr/lib/locale/
 fi
 if [ ! -f /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/profile ];then
  mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/etc
  cp -f tnew/etc/profile /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/
 fi
 if [ ! -f /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/fontmap ];then
  cp -f tnew/etc/fontmap /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/
 fi
fi

###set date and time###
#could read .session/etc/clock and run hwclock, but for now this probably good enough (refer: rc.shutdown)...
#200218 fixed /dev/rtc0 and symlink /dev/rtc for modern kernels, replacing old /dev/rtc
#       also have rtc drivers builtin to kernel >=5.4.20. can now use hwclock...
CLKflg=1
if [ -e /sys/class/rtc/rtc0 ];then
 if [ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/clock ];then
. /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/clock #has HWCLOCKTIME=localtime or utc
  case "$HWCLOCKTIME" in
   localtime) hwclock -s --localtime -f /dev/rtc0; CLKflg=$? ;;
   utc)       hwclock -s -u -f /dev/rtc0; CLKflg=$? ;;
  esac
 else #first bootup, assume hw clock is locatime...
  hwclock -s --localtime -f /dev/rtc0
 fi
fi
if [ $CLKflg -ne 0 ];then
 if [ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.var/local/shutdown_date_saved ];then
  date -s "`cat /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.var/local/shutdown_date_saved`" > /dev/null
 fi
fi
export DATE="$(date)" #ex: Tue Mar  3 07:09:34 +08 2020

###TRIM###
if [ "$TRIMflg" ];then #200302
 [ ! -f /mnt/${BOOT_DEV}/${BOOT_DIR}.easyos-bootcnt ] && echo -n '0' > /mnt/${BOOT_DEV}/${BOOT_DIR}.easyos-bootcnt
 BOOTCNT=$(cat /mnt/${BOOT_DEV}/${BOOT_DIR}.easyos-bootcnt)
 BOOTCNT=$(($BOOTCNT+1))
 if [ $BOOTCNT -gt 20 ];then
  BOOTCNT=0
  echo -e "\\033[1;35mExecuting fstrim on SSD working-partition...\\033[0;39m\n " #purple
  fstrim -v /mnt/${WKG_DEV}
 fi
 echo -n "$BOOTCNT" > /mnt/${BOOT_DEV}/${BOOT_DIR}.easyos-bootcnt
fi

[ "$DROPOUT" == "2" ] && exit_to_initrd " Exited from init script, before recovery & maintenance operations."

###recovery, maintenance###
KERNELNAME=vmlinuz
[ -f /mnt/$BOOT_DEV/${BOOT_DIR}kernel8.img ] && KERNELNAME=kernel8.img #rpi3
[ -f /mnt/$BOOT_DEV/${BOOT_DIR}Image ] && KERNELNAME=Image #rock64
export KERNELNAME
if [ "$QFIX" ];then #190817 see similar code above.
 for ONEFIX in `echo -n "$QFIX" | tr ',' ' '`
 do
  case $ONEFIX in
   fsck|FSCK) echo -n "${WKG_DEV},${WKG_FS},REQUEST" > /mnt/${WKG_DEV}/${WKG_DIR}.session/.fsckme.flg ;;
   back|bak|BACK|BAK) echo -n ",last" > /mnt/${WKG_DEV}/${WKG_DIR}.session/.rollback.flg ;;
   new|NEW) echo -n ",erase" > /mnt/${WKG_DEV}/${WKG_DIR}.session/.rollback.flg ;; #181009 200720
  esac
 done
fi

###umount temporary easy.sfs###
sync
umount tnew/dev/pts
umount tnew/proc
umount tnew/dev
umount tnew
umount tro

#191224 if easy.sfs mounted on /tro (via loop0), rollback fails (easy.sfs seems to delete, but isn't), hence moved rollback below unmount /tnew
[ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/.rollback.flg ] && rollback ${WKG_DRV} ${WKG_DEV} ${BOOT_DRV} ${BOOT_DEV} #180602

#200726 if boot- and wkg-partition the same, cannot unmount wkg-partition and fscheck
#fails, coz of temporary easy.sfs mounted on tro. moved down...
if [ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/.fsckme.flg ];then
 #200726 fscheck modified to not use e2fsck in easy.sfs...
 fscheck ${WKG_DRV} ${WKG_DEV} #ex: improper shutdown
 [ $? -ne 0 ] && err_exit "Fatal error when filesystem check"
fi

[ "$DROPOUT" == "3" ] && exit_to_initrd " Exited from init script, before version control."

###version control###
prevVER="" #170919
if [ ! -d /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION} ];then
 echo -e "\\033[1;35mOne-time only operation, creating a snapshot of EasyOS\\033[0;39m"
 echo "  This will allow future rollback with the Easy Version Control Manager"
 echo "  Populating: /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}"
 mkdir /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}
 
 #170816 there is a limit on history...
 if [ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.var/local/version-history-depth ];then
  DEPTH_MAX="$(cat /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.var/local/version-history-depth)"
  VERS="$(ls -l -d /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-* | rev | cut -f 1 -d '-' | rev)" #181218 fix.
  sortedVERS="$(echo "$VERS" | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n)" #lowest to highest.
  for ADEL in `echo "$sortedVERS" | head -n -${DEPTH_MAX} | tr '\n' ' '`
  do
   if [ -d /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${ADEL} ];then
    MSGdel="Warning, deleting old version:"
    echo -e "  \\033[1;31m${MSGdel} easy-${ADEL}\\033[0;39m" #red
    #181205 remove sfs files symlinked to sfs folder...
    for aSL in `realpath /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${ADEL}/*.sfs | tr '\n' ' '`
    do
     aMAIN="${aSL/.sfs/}"
     rm -f ${aSL}
     [ -f ${aMAIN}.specs ] && rm -f ${aMAIN}.specs
    done
    rm -rf /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${ADEL}
   fi
  done
 fi

 if [ -f /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/DISTRO_SPECS ];then
  prevVER="$(grep '^DISTRO_VERSION=' /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/DISTRO_SPECS | cut -f 2 -d '=' | cut -f 1 -d ' ')"
  touch /mnt/${WKG_DEV}/${WKG_DIR}.session/.delayedrun_version_upgrade #see /usr/sbin/delayedrun
 else
  prevVER=""
 fi
 if [ "$WKG_DEV" != "zram0" ];then #181203 200824
  if [ -f /mnt/${BOOT_DEV}/${BOOT_DIR}initrd ];then #190130
   echo -n '  initrd'
   cp -a -f /mnt/${BOOT_DEV}/${BOOT_DIR}initrd /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/ #181130 renamed initrd.q to initrd. 200828 -a
   #190828 verify...
   cp_verify_func /mnt/${BOOT_DEV}/${BOOT_DIR}initrd /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/initrd
  fi
  echo -n " ${KERNELNAME}"
  cp -a -f /mnt/${BOOT_DEV}/${BOOT_DIR}${KERNELNAME} /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/ #200828 -a
  #190828 verify...
  cp_verify_func /mnt/${BOOT_DEV}/${BOOT_DIR}${KERNELNAME} /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${KERNELNAME}
 fi
 #181029 all .sfs files are now in /mnt/wkg/sfs, with symlinks (to avoid being encrypted)...
 #echo -n ' easy.sfs'; cp -f /mnt/${BOOT_DEV}/${BOOT_DIR}easy.sfs /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/
 mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION} #ex: oe/pyro
 echo -n ' easy.sfs'
 cp -a -f /mnt/${BOOT_DEV}/${BOOT_DIR}easy.sfs /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs #200828 -a
 ln -s ../../sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/easy.sfs
 #190828 verify...
 cp_verify_func /mnt/${BOOT_DEV}/${BOOT_DIR}easy.sfs /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs
 
 #190123 need some meta-data for easy.sfs...
 #190913 change DB_install from 'terminal' to 'desk'...
 #also need easy.png here, done in 3buildeasydistro (see #190123)
 ESUM="$(sha256sum /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs | cut -f 1 -d ' ')"
 echo "#created in initrd, script init
DB_pkgname='easy_${INIT_DISTRO_VERSION}'
DB_nameonly='easy'
DB_version='${INIT_DISTRO_VERSION}'
DB_revision=''
DB_arch='${INIT_DISTRO_TARGETARCH}'
DB_categories='Utility'
DB_size='1537668'
DB_fullfilename='easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs'
DB_dependencies=''
DB_description='EasyOS base SFS'
DB_description_long='This is the complete EasyOS filesystem.'
DB_compileddistro='${INIT_DISTRO_BINARY_COMPAT}'
DB_compiledrelease='${INIT_DISTRO_COMPAT_VERSION}'
DB_path='easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}'
DB_apps='easy'
DB_icons='easy'
DB_install='desk'
DB_hash='${ESUM}'" > /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.specs
 
 rm -rf /mnt/${WKG_DEV}/${WKG_DIR}.session/.[a-z]* 2>/dev/null #precaution.
 ##170919 delete *all* whiteout files (see also /sbin/fixlayers)...
 #find /mnt/${WKG_DEV}/${WKG_DIR}.session -mindepth 1 -type f -name '.wh.*' -delete 2>/dev/null

 ###upgrade hacks###
 #190913 the inbuilt easy container has label pyro or buster, need to fix older versions of easyos...
 #old version has label "easy". this fix is for when do a version upgrade...
 #problem only for upgrading easy pyro <1.2.3 and buster <2.1.3
 if [ -f /mnt/${WKG_DEV}/${WKG_DIR}.session/root/Choices/ROX-Filer/PuppyPin ];then
  if grep '"easy"' /mnt/${WKG_DEV}/${WKG_DIR}.session/root/Choices/ROX-Filer/PuppyPin > /dev/null; then
   #there is a desktop icon labeled "easy"
   sed -i '/"easy"/d' /mnt/${WKG_DEV}/${WKG_DIR}.session/root/Choices/ROX-Filer/PuppyPin
   [ -f /mnt/${WKG_DEV}/${WKG_DIR}.session/root/Choices/ROX-Filer/PuppyPinBACKUP ] && sed -i '/"easy"/d' /mnt/${WKG_DEV}/${WKG_DIR}.session/root/Choices/ROX-Filer/PuppyPinBACKUP
   [ -d /mnt/${WKG_DEV}/${WKG_DIR}containers/easy ] && rm -rf /mnt/${WKG_DEV}/${WKG_DIR}containers/easy
   #190915 create pyro or buster container...
   for aCONT in `ls -1 /skeleton/containers`
   do
    [ -d /mnt/${WKG_DEV}/${WKG_DIR}containers/${aCONT} ] && continue
    cp -a /skeleton/containers/${aCONT} /mnt/${WKG_DEV}/${WKG_DIR}containers/
    cp -a -f /skeleton/containers/${aCONT}/.sessionSKEL/* /mnt/${WKG_DEV}/${WKG_DIR}containers/${aCONT}/.session/
    [ -d /skeleton/containers/${aCONT}/.sessionSKEL/.control ] && cp -a -f /skeleton/containers/${aCONT}/.sessionSKEL/.control /mnt/${WKG_DEV}/${WKG_DIR}containers/${aCONT}/.session/
   done
  fi
 fi
  
 mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/etc
 
 #200830 this may have invalid icons, delete it, will get copied from root/Choices/ROX-Filer/globicons ...
 [ -f /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.config/rox.sourceforge.net/ROX-Filer/globicons ] && rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/root/.config/rox.sourceforge.net/ROX-Filer/globicons
 #200830 this folder must always be pristine...
 [ -d /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/xdg ] && rm -rf /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/xdg
   
 if [ $SESSIONSFSflag -eq 1 ];then #170525
  if [ ! "$prevVER" ];then
   #.session folder (rw layer) is empty, but need a session.sfs anyway...
   echo -n ' session'; mksquashfs /mnt/${WKG_DEV}/${WKG_DIR}.session /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/session.sfs -comp gzip >/dev/null
  else
   #need to merge .session (rw layer) with easy-$prevVER/session.sfs, create new session.sfs...
   mkdir sro snew
   mount -t squashfs -o loop,noatime /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${prevVER}/session.sfs sro
   [ $? -ne 0 ] && err_exit "FAILED: mount -t squashfs -o loop,noatime /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${prevVER}/session.sfs sro"
   if [ "$LAYERFS" == "aufs" ];then
    mount -t aufs -o br=/mnt/${WKG_DEV}/${WKG_DIR}.session=rw:sro=ro aufs snew
    [ $? -ne 0 ] && err_exit "FAILED: mount -t aufs -o br=/mnt/${WKG_DEV}/${WKG_DIR}.session=rw:sro=ro aufs snew"
   else
    mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}swork
    mount -t overlay -o lowerdir=sro,upperdir=/mnt/${WKG_DEV}/${WKG_DIR}.session,workdir=/mnt/${WKG_DEV}/${WKG_DIR}swork overlay snew
    [ $? -ne 0 ] && err_exit "FAILED: mount -t overlay -o lowerdir=sro,upperdir=/mnt/${WKG_DEV}/${WKG_DIR}.session,workdir=/mnt/${WKG_DEV}/${WKG_DIR}swork overlay snew"
   fi
   #180606 need path root/.XLOADED  181121 exclude .control
   echo -e 'dev\nmnt\nproc\nrun\nsys\ntmp\nvar\nlost+found\nroot/.XLOADED\n.control' > exclusions1 #exclusions.
   mksquashfs snew /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/session.sfs -ef exclusions1 -comp gzip #>/dev/null
   echo -e "\\033[1;33mPlease wait, synchronizing...\\033[0;39m" #yellow
   sync
   umount snew
   umount sro
   [ -d /mnt/${WKG_DEV}/${WKG_DIR}swork ] && rm -rf /mnt/${WKG_DEV}/${WKG_DIR}swork
   rm -rf /mnt/${WKG_DEV}/${WKG_DIR}.session/*
   rm -f /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${prevVER}/session.sfs #remove session.sfs in prev. version.
  fi
 else
  #echo -n "rw-${INIT_DISTRO_VERSION}.sfs"; 
  mksquashfs /mnt/${WKG_DEV}/${WKG_DIR}.session /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/rw-${INIT_DISTRO_VERSION}.sfs -comp gzip #>/dev/null
 fi
 #also save any container sessions:
 for EXE in `ls -1 /mnt/${WKG_DEV}/${WKG_DIR}containers | tr '\n' ' '`
 do
  [ ! -d /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/.session ] && continue
  #echo -n " ec-${EXE}"; mksquashfs /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/.session /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/rw-${prevVER}.sfs -comp gzip >/dev/null
  cp -a -f /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/configuration /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/configuration-${INIT_DISTRO_VERSION} #200828 -a
 done
 echo
 touch /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/configuration
 touch /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/configuration-${INIT_DISTRO_VERSION}
 #180602 fix version number in syslinux.cfg and refind.conf...
 [ -f /mnt/${BOOT_DEV}/syslinux.cfg ] && sed -i -e "s%^menu title .*%menu title EasyOS ${INIT_DISTRO_VERSION}%" /mnt/${BOOT_DEV}/syslinux.cfg
 #190106 this may be translated, so EasyOS <version> normal bootup" will change...
 [ -f /mnt/${BOOT_DEV}/EFI/BOOT/refind.conf ] && sed -i -e "s%EasyOS [0-9.]* %EasyOS ${INIT_DISTRO_VERSION} %" /mnt/${BOOT_DEV}/EFI/BOOT/refind.conf

fi

###recompress easy.sfs### improve operating speed, recompress easy.sfs (refer quicksetup)
if [ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/.qsfs.flg ];then #181029 now in sfs folder...
 echo -e "\\033[1;35mRecompressing easy.sfs, xz to gz, please wait\\033[0;39m" #purple
 mkdir /mntsfs
 mount -r -t squashfs -o loop,noatime /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs /mntsfs
 mksquashfs /mntsfs /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy-gz.sfs -comp gzip #>/dev/null 180604
 sync
 umount /mntsfs
 mv -f /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy-gz.sfs /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs
 sync
 if [ -f /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.specs ];then #190314
  HASHnew="$(sha256sum /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.sfs | cut -f 1 -d ' ')"
  sed -i -e "s%^DB_hash=.*%DB_hash='${HASHnew}'%" /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/easy_${INIT_DISTRO_VERSION}_${INIT_DISTRO_TARGETARCH}.specs
  sync
 fi
 rm -f /mnt/${WKG_DEV}/${WKG_DIR}.session/.qsfs.flg
fi

[ "$DROPOUT" == "4" ] && exit_to_initrd " Exited from init script, before setting up SFS layers."

###setup bottom ro layer, with easy.sfs###
echo -e "\\033[1;35mMounting read-only layer of layered filesystem\\033[0;39m" #purple
QSFSbytes0=`stat -L -c %s /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/easy.sfs` #181029
if [ "$xWKG_DEV" ];then #190914 allocate more space in zram if extra sfss
 for eSFS in `grep '^EASY_LAYER_RO' /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/configuration | cut -f 2 -d '=' | tr '\n' ' '`
 do
  [ "$eSFS" == "devx.sfs" ] && continue
  [ "$eSFS" == "kernel.sfs" ] && continue
  eSFSbytes=`stat -L -c %s /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${eSFS}`
  QSFSbytes0=$(($QSFSbytes0+$eSFSbytes))
 done
fi
QSFSbytes1=$(($QSFSbytes0+500000))
mount -t tmpfs -o size=${QSFSbytes1} tmpfs /easy_ro
mkdir /easy_ro/easy_sfs
#decide whether to copy easy.sfs to RAM, or not...
CPYflg=0
[ $FREEK -gt 1100000 ] && CPYflg=1 #>1GB ram then copy
[ $TIME10k -lt 100 ] && CPYflg=0   #but fast drive so don't copy.
[ $FREEK -gt 3100000 ] && CPYflg=1 #but heaps of ram, so copy. 181120 restore.
[ $TIME10k -lt 10 ] && CPYflg=0    #181120 but super-fast drive so don't copy. 200827 was 30 now 10.
[ "$xWKG_DEV" ] && CPYflg=1        #190817 will be running totally in ram.
if [ $CPYflg -eq 0 ];then
 #do not copy easy.sfs into ram, mount where it is...
 echo "  Mounting squashfs file easy.sfs"
 QSFS_PATH="/mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/" #need this for setting up containers.
 mount -r -t squashfs -o noatime,loop /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/easy.sfs /easy_ro/easy_sfs
else
 echo "  Copying easy.sfs to RAM, then mounting"
 [ ! -f /easy_ro/easy.sfs ] && cp -L -p /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/easy.sfs /easy_ro/ #181029 200830 -p
 QSFS_PATH="/mnt/easy_ro/" #need this for setting up containers.
 mount -r -t squashfs -o noatime,loop /easy_ro/easy.sfs /easy_ro/easy_sfs
fi
[ $? -ne 0 ] && err_exit "Failed to mount easy.sfs"
mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}.session/etc #170927 missing if have erased session.
cp -a -f /easy_ro/easy_sfs/etc/DISTRO_SPECS /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/ #need to be sure correct one is on top. 200828 -a
EXTRASFS=""; sessionSFS=""; NEWEXTRASFSLIST=""
if [ $SESSIONSFSflag -eq 1 ];then #170525
 mkdir /easy_ro/session
 mount -r -t squashfs -o loop,noatime /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/session.sfs /easy_ro/session
 sessionSFS="/easy_ro/session${RO}:"
fi
#precaution...
. /easy_ro/easy_sfs/etc/DISTRO_SPECS
[ "$DISTRO_VERSION" != "$INIT_DISTRO_VERSION" ] && echo -e "\\033[1;31mWARNING, versions do not match. initrd: ${INIT_DISTRO_VERSION}, easy.sfs: ${DISTRO_VERSION}\\033[0;39m" #red

###load extra sfs on ro layer###
#the configuration file defines any more sfs files to load. easy.sfs is always loaded
# (on bottom), and session.sfs on top of ro layers.
. /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/configuration
#if [ "$xWKG_DEV" == "" ];then #190817 190914
 for NUM in 4 3 2 1
 do
  eval "ROsfs=\$EASY_LAYER_RO${NUM}" #implements indirection. EASY_LAYER_RO1='devx*.sfs' in configuration file, will assign 'devx*.sfs' to ROsfs. 170320 170523
  if [ "$ROsfs" ];then
   #170523 check file exists. note, may have a glob wildcard...
   #181029 no longer have wildcard. ex: devx.sfs which is a symlink into 'sfs' folder...
   FNDSFSS="$(ls -1 /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${ROsfs} | tr '\n' ' ')"
   for FNDSFS in $FNDSFSS
   do
    ANAME="$(basename $FNDSFS .sfs)" #ex: devx
    NAMEONLY="${ANAME/_*/}" #181029 precaution.
    #181029 all .sfs files must be under sfs folder, to avoid encryption (except for rw-*.sfs)...
    # this is a precaution, should already be done...
    if [ "$ANAME" != "$NAMEONLY" ];then
     mv -f /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${ANAME}.sfs /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/
     ln -snf ../../sfs/easyos/${INIT_DISTRO_BINARY_COMPAT}/${INIT_DISTRO_COMPAT_VERSION}/${ANAME}.sfs /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${NAMEONLY}.sfs
     ANAME="$NAMEONLY"
    fi
    mkdir /easy_ro/$ANAME
    if [ "$xWKG_DEV" ];then #190914 copying session to ram.
     [ "$ANAME" == "devx" ] && continue
     [ "$ANAME" == "kernel" ] && continue
     echo "  Copying to RAM and mounting extra squashfs file: ${ANAME}.sfs"
     cp -L -p -f /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${ANAME}.sfs /easy_ro/ #200830 -p
     mount -r -t squashfs -o noatime,loop /easy_ro/${ANAME}.sfs /easy_ro/${ANAME}
    else
     echo "  Mounting extra squashfs file: ${ANAME}.sfs"
     mount -r -t squashfs -o noatime,loop /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${ANAME}.sfs /easy_ro/${ANAME}
    fi
    EXTRASFS="/easy_ro/${ANAME}${RO}:${EXTRASFS}" #170206
    NEWEXTRASFSLIST="${ANAME}:${NEWEXTRASFSLIST}" #170919
   done
  fi
 done
#fi

sync
if [ "$BOOT_DEV" != "$WKG_DEV" ];then
 if [ "$BOOT_DRV" != "rootfs" ];then #181203
  umount /dev/${BOOT_DEV}
 fi
fi

if [ "$PW" ];then
 #180612 set password for zeus... 180811 also root...
 if [ ! -f /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/shadow ];then
  echo -e "\\033[1;35mFirst-bootup security setup...\\033[0;39m" #purple
  echo "  Setting same password for users zeus and root"
  ePW="$(cryptpw -m SHA512 ${PW})" #note: busybox mkpasswd is an alias for cryptpw
  grep -v '^zeus' /easy_ro/easy_sfs/etc/shadow > /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/shadow
  echo "zeus:${ePW}:17693:0:99999:7:::" >> /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/shadow
  grep -v '^root' /easy_ro/easy_sfs/etc/shadow > /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/shadow
  echo "root:${ePW}:17693:0:99999:7:::" >> /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/shadow
  for aCONT in `ls -1 /mnt/${WKG_DEV}/${WKG_DIR}containers` #desk console ssh0 www
  do
   cp -a -f /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/shadow /mnt/${WKG_DEV}/${WKG_DIR}containers/${aCONT}/.session/etc/
  done
 fi
fi

###fix layers change###
OLDEXTRASFSLIST="$(grep '^EXTRASFSLIST=' /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/rc.d/PUPSTATE 2>/dev/null | cut -f 2 -d "'")"
[ -s /mnt/${WKG_DEV}/${WKG_DIR}.session/etc/rc.d/PUPSTATE ] && [ "$NEWEXTRASFSLIST" != "$OLDEXTRASFSLIST" -o "$prevVER" != "" ] && /sbin/fixlayers ${WKG_DRV} ${WKG_DEV} "${NEWEXTRASFSLIST}" "${prevVER}" #170919

###maybe copy session to zram###
#190817 see qfix=lock2 boot param.
if [ "$xWKG_DEV" ];then
 echo -e "\\033[1;35mCopying last working session to RAM\\033[0;39m"
 #note: won't work for overlayfs, need somewhere for the workingdir.
 mkdir -p /xram
 mount -t $xWKG_FS /dev/zram0 /xram
 #now copy stuff...
 cp -a /skeleton/* /xram/
 mkdir /xram/.session
 cp -a /mnt/${WKG_DEV}/${WKG_DIR}.session/* /xram/.session/
 cp -a /mnt/${WKG_DEV}/${WKG_DIR}.session/.wh..wh* /xram/.session/ 2>/dev/null #? 191211
 #we cannot have containers, maybe...
 #if [ "$CAPS_DROP" ];then #190818 see also further down. 200824 remove if
  rm -rf /xram/containers/*
 #fi
 #200824 copy files that are outside .session. 200827 INIT_DISTRO_VERSION instead of DISTRO_VERSION...
 mkdir -p /xram/home
 cp -a /mnt/${WKG_DEV}/${WKG_DIR}home/* /xram/home/
 mkdir -p /xram/releases/easy-${INIT_DISTRO_VERSION}
 cp -a /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/configuration /xram/releases/easy-${INIT_DISTRO_VERSION}/
 cp -a /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/configuration-${INIT_DISTRO_VERSION} /xram/releases/easy-${INIT_DISTRO_VERSION}/
 mkdir -p /xram/sfs/easyos/${DISTRO_BINARY_COMPAT}/${DISTRO_COMPAT_VERSION} #note, sfss already copied into ram if loaded.
 #200826 mimic same path in zram for sfs files, with link (cannot have hard link)...
 yEXTRASFSS="$(echo "$NEWEXTRASFSLIST" | tr ':' ' ')"
 for aSFS in easy $yEXTRASFSS
 do
  aFULL="$(readlink -n /mnt/${WKG_DEV}/${WKG_DIR}releases/easy-${INIT_DISTRO_VERSION}/${aSFS}.sfs | rev | cut -f 1 -d '/' | rev)" #ex: easy_2.4_amd64.sfs.sfs
  #links will be valid after bootup...
  ln -s /mnt/easy_ro/${aSFS}.sfs /xram/sfs/easyos/${DISTRO_BINARY_COMPAT}/${DISTRO_COMPAT_VERSION}/${aFULL}
  ln -s ../../sfs/easyos/${DISTRO_BINARY_COMPAT}/${DISTRO_COMPAT_VERSION}/${aFULL} /xram/releases/easy-${INIT_DISTRO_VERSION}/${aSFS}.sfs
 done
 #200827 also copy the .png and .specs files...
 cp -a -u /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${DISTRO_BINARY_COMPAT}/${DISTRO_COMPAT_VERSION}/*.specs /xram/sfs/easyos/${DISTRO_BINARY_COMPAT}/${DISTRO_COMPAT_VERSION}/
 cp -a -u /mnt/${WKG_DEV}/${WKG_DIR}sfs/easyos/${DISTRO_BINARY_COMPAT}/${DISTRO_COMPAT_VERSION}/*.png /xram/sfs/easyos/${DISTRO_BINARY_COMPAT}/${DISTRO_COMPAT_VERSION}/
 sync
 WKG_DEV='zram0'
 WKG_FS="$xWKG_FS"
 WKG_DIR=''
 SESSIONHOME="/xram/.session"
else
 SESSIONHOME="/mnt/${WKG_DEV}/${WKG_DIR}.session"
fi

###the big moment, create layered f.s.###
#echo -e "\\033[1;35mCreating layered filesystem, with read-write folder: /mnt/${WKG_DEV}/.session\\033[0;39m"
sync
echo -e "\\033[1;35mCreating layered filesystem, type: ${LAYERFS}\\033[0;39m"
if [ "$LAYERFS" == "aufs" ];then #170525
 mount -t aufs -o br=${SESSIONHOME}=rw:${sessionSFS}${EXTRASFS}/easy_ro/easy_sfs=ro aufs /easy_new
else
 mount -t overlay -o lowerdir=${sessionSFS}${EXTRASFS}/easy_ro/easy_sfs,upperdir=${SESSIONHOME},workdir=/mnt/${WKG_DEV}/${WKG_DIR}.tempwork overlay /easy_new
fi
[ $? -ne 0 ] && err_exit "Failed to create layered filesystem"

###setup PUPSTATE###
#/etc/rc.d/rc.sysinit will append to PUPSTATE, get the ball rolling here...
#PUPMODE, bit-1 (partition has session), bit-2 (bottom layer is sfs) --rough equiv to puppy
#200823 also want WKG_UUID...
echo -e "PUPMODE=6\nBOOT_UUID='${BOOT_UUID}'\nBOOT_DEV='${BOOT_DEV}'\nBOOT_FS='${BOOT_FS}'\nBOOT_DIR='${BOOT_DIR}'\nWKG_UUID='${WKG_UUID}'\nWKG_DEV='${WKG_DEV}'\nWKG_FS='${WKG_FS}'\nWKG_DIR='${WKG_DIR}'\nQSFS_PATH='${QSFS_PATH}'" > /easy_new/etc/rc.d/PUPSTATE
if [ "$origWKG_DEV" != "$WKG_DEV" ];then #200808 200822
 echo -e "origWKG_DEV='${origWKG_DEV}'\norigWKG_FS='${origWKG_FS}'\norigWKG_UUID='${origWKG_UUID}'\norigWKG_DIR='${origWKG_DIR}'" >> /easy_new/etc/rc.d/PUPSTATE
fi
echo -e "EXTRASFSLIST='${NEWEXTRASFSLIST}'\nSESSIONSFSflag=${SESSIONSFSflag}" >> /easy_new/etc/rc.d/PUPSTATE #170919 170924
#echo "BOOT_PW_FLG='${PW//[a-zA-Z0-9]/X}'" >> /easy_new/etc/rc.d/PUPSTATE #180811 a flag so main f.s. will know if a pw was entered.
echo "BOOT_PW_FLG='${PW/*/X}'" >> /easy_new/etc/rc.d/PUPSTATE #180811 set to "X" if $PW has something in it. note, used in /usr/local/EasyShare
echo "BOOT_CAPS_DROPPED='${CAPS_DROP}'" >> /easy_new/etc/rc.d/PUPSTATE #190812 comma-delimited
#200820 also want BOOT_UUID. 200823 want BOOT_LOCK ...
[ "$LOCKDOWN" ] && echo "BOOT_LOCK='${LOCKDOWN}:${LOCKkeep}'" >> /easy_new/etc/rc.d/PUPSTATE

#200623 log stuff for debugging...
mkdir -p /easy_new/root/.initrd-debug
echo "$BLKIDS" > /easy_new/root/.initrd-debug/BLKIDS
ls -l /dev > /easy_new/root/.initrd-debug/ls-dev

[ "$DROPOUT" == "5" ] && exit_to_initrd " Exited from init script, before moving mount points to wkg f.s."

###relocate mount-points prior to switch_root###
echo -e "\\033[1;35mPerforming a switch_root onto the layered filesystem\\033[0;39m" #purple
#move the mount points...
[ ! -d /easy_new/mnt/easy_ro ] && mkdir /easy_new/mnt/easy_ro
[ ! -d /easy_new/mnt/${WKG_DEV} ] && mkdir /easy_new/mnt/${WKG_DEV}
[ ! -d /easy_new/mnt/${BOOT_DEV} ] && mkdir /easy_new/mnt/${BOOT_DEV}
mount -o move /easy_ro /easy_new/mnt/easy_ro
#200623 previously had static /dev, then here mounted devtmpfs at /easy_new/dev
# but now have mounted devtmpfs at start of init script. so just move..
mount -o move /dev /easy_new/dev

#200830 however, in lockdown #2 cannot create device nodes, so make them here...
[ ! -e /easy_new/dev/ppp ] && mknod /easy_new/dev/ppp c 108 0 #jafadmin: gpptp needs /dev/ppp (moved from rc.sysinit 200522)
#[ ! -e /easy_new/dev/rfcomm0 ] && mknod /easy_new/dev/rfcomm0 c 216 0 #ref: /usr/sbin/get_bluetooth_connection

if [ "$xWKG_DEV" ];then #190817 200809 note, in future could test for $LOCKDOWN instead of $xWKG_DEV
 mount -o move /xram /easy_new/mnt/${WKG_DEV} #WKG_DEV has been changed to zram0 earlier.
 ln -snf ${WKG_DEV} /easy_new/mnt/wkg
 #200809 new "save" icon on desktop, replace "update" icon... 200820 do not hard-code coords...
 #PTN1='s%.*easy\-update.*%  <icon x="544" y="32" label="save">/usr/sbin/lockdown-save</icon>%'
 PTN1='s%label="update">/usr/sbin/easy-update%label="save">/usr/sbin/lockdown-save%'
 sed -i -e "$PTN1" /easy_new/root/Choices/ROX-Filer/PuppyPin
 #200823 do these for both lockdown modes...
 #take out the pre-created "www", "console", "desk" container desktop icons...
 sed -i '/ec\-chroot\-/d' /easy_new/root/Choices/ROX-Filer/PuppyPin
 #sed -i '/sfsget/d' /easy_new/root/Choices/ROX-Filer/PuppyPin #"sfsget" 200824 keep
 if [ -f /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP ];then
  sed -i '/ec\-chroot\-/d' /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP
  #sed -i '/sfsget/d' /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP #"sfsget" 200824 keep
 fi
 for aAPP in easy-update easy-bootmanager easy-containers easy-version-control #190914 200805
 do
  [ ! -f /easy_new/usr/share/applications/${aAPP}.desktop ] && continue
  aLABEL="$(grep '^Name=' /easy_new/usr/share/applications/${aAPP}.desktop | cut -f 2 -d '=')"
  rm -f /easy_new/usr/share/applications/${aAPP}.desktop
  sed -i "/${aLABEL}/d" /easy_new/root/.jwmrc #200827 however, .jwmrc gets reconstructed by rc.sysinit
  [ -f /easy_new/root/.jwmrc3 ] && sed -i "/${aLABEL}/d" /easy_new/root/.jwmrc3
 done
 rm -f /easy_new/usr/share/applications/ec-*.desktop 2>/dev/null
 rm -f /easy_new/usr/sbin/ec-chroot-* 2>/dev/null
 sed -i '/ec\-chroot\-/d' /easy_new/root/.jwmrc #200827 ditto, don't need to do this. etc...
 [ -f /easy_new/root/.jwmrc3 ] && sed -i '/ec\-chroot\-/d' /easy_new/root/.jwmrc3 #190914
 #200806 200826 these not appropriate for booting to zram...
 sed -i '/wmreboot rollback/d' /easy_new/root/.jwmrc
 sed -i '/lockdown-ram/d' /easy_new/root/.jwmrc
 sed -i '/wmreboot fscheck/d' /easy_new/root/.jwmrc
 sed -i '/debug-initrd/d' /easy_new/root/.jwmrc
 #20026 ditto...
 sed -i '/wmreboot rollback/d' /easy_new/etc/xdg/templates/_root_.jwmrc
 sed -i '/lockdown-ram/d' /easy_new/etc/xdg/templates/_root_.jwmrc
 sed -i '/wmreboot fscheck/d' /easy_new/etc/xdg/templates/_root_.jwmrc
 sed -i '/debug-initrd/d' /easy_new/etc/xdg/templates/_root_.jwmrc
 #rm -f /easy_new/usr/local/easy_containers/ec-fix-desktop
 #200823 so less to do here...
 if [ "$CAPS_DROP" ];then #190818
  #190914 also remove "petget" and "sfsget" desktop icons, and from menu...
  #200805 have to handle translated PuppyPin... 200824 keep...
  #sed -i '/dotpup/d' /easy_new/root/Choices/ROX-Filer/PuppyPin #"petget"
  #sed -i '/wizardwizard/d' /easy_new/root/Choices/ROX-Filer/PuppyPin #"setup"
  #sed -i '/easy\-update/d' /easy_new/root/Choices/ROX-Filer/PuppyPin #200805 "update"
  ##move "edit" and "console" left to fill gap...
  #sed -i 's%x="416" y="32"%x="224" y="32"%' /easy_new/root/Choices/ROX-Filer/PuppyPin
  #sed -i 's%x="480" y="32"%x="288" y="32"%' /easy_new/root/Choices/ROX-Filer/PuppyPin
  #if [ -f /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP ];then
  # sed -i '/dotpup/d' /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP #"petget"
  # sed -i '/wizardwizard/d' /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP #"setup"
  # sed -i '/easy\-update/d' /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP #200805 "update"
   #sed -i 's%x="416" y="32"%x="224" y="32"%' /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP
   #sed -i 's%x="480" y="32"%x="288" y="32"%' /easy_new/root/Choices/ROX-Filer/PuppyPinBACKUP
  #fi
  for aAPP in PETget-package-manager PupControl #190914 200805
  do
   [ ! -f /easy_new/usr/share/applications/${aAPP}.desktop ] && continue
   aLABEL="$(grep '^Name=' /easy_new/usr/share/applications/${aAPP}.desktop | cut -f 2 -d '=')"
   rm -f /easy_new/usr/share/applications/${aAPP}.desktop
   sed -i "/${aLABEL}/d" /easy_new/root/.jwmrc
   [ -f /easy_new/root/.jwmrc3 ] && sed -i "/${aLABEL}/d" /easy_new/root/.jwmrc3
  done
  rm -rf /easy_new/root/.pup_event/* 2>/dev/null #190818
  #190818 requires that cap_mknod be dropped...
  rm -f /easy_new/dev/mm* 2>/dev/null
  rm -f /easy_new/dev/nv* 2>/dev/null
  rm -f /easy_new/dev/sd* 2>/dev/null
 fi
else
 mount -o move /mnt/${WKG_DEV} /easy_new/mnt/${WKG_DEV}
fi

#200301 ***CURRENTLY NOT USING***
CHROOT='' #'1'
[ "$WKG_DEV" == "zram0" ] && CHROOT=''

#190811 redesign so can drop linux-capabilities (also changed /etc/rc.d/rc.sysinit)...
#sync
#umount /sys
#umount /proc
cp -a -f /bin/capsh /easy_new/sbin/ #200828 -a
if [ "$CHROOT" ];then
 mount -o move /sys /easy_new/sys
 mount -t proc none /easy_new/proc
 #keep /proc mounted in initrd.
else
 mount -o move /sys /easy_new/sys
 mount -o move /proc /easy_new/proc
fi
mount -t securityfs securityfs /easy_new/sys/kernel/security #200820
mkdir -p /easy_new/dev/pts
mount -t devpts devpts /easy_new/dev/pts
HALFK=$(($FREEK/2))
QTRK=$(($FREEK/4))
mkdir -p /easy_new/dev/shm
mount -t tmpfs -o size=${QTRK}k shmfs /easy_new/dev/shm
if [ "$WKG_DEV" != "zram0" ];then #don't bother if will be running in zram.
 mount -t tmpfs -o size=${HALFK}k tmpfs /easy_new/tmp
fi

[ "$DROPOUT" == "6" ] && exit_to_initrd " Exited from init script, just before switch_root."

sync
[ -f /easy_new/.shutdown-req ] && rm -f /easy_new/.shutdown-req #200301
if [ "$CAPS_DROP" == "" ];then #190812
 if [ "$CHROOT" ];then #200301
#  mkdir -p /easy_new/mnt/initrd
#  cd /easy_new
#  pivot_root . mnt/initrd
#  exec chroot . /sbin/init <dev/console >dev/console 2>&1
  #when /easy_new/.shutdown-req modified, /initrd-shutdown is called...
  touch /easy_new/.shutdown-req
  inotifyd /initrd-shutdown /easy_new/.shutdown-req:c &
  exec chroot /easy_new /sbin/init
 else
  exec switch_root /easy_new /sbin/init
 fi
else
 echo confidentiality > /easy_new/sys/kernel/security/lockdown #200820 instead of "lockdown=confidentiality" boot param.
 #190811 drop capbilities when switch_root...
 #capsh --drop=cap_sys_mount -- -c "exec switch_root /easy_new /sbin/init"
 #this is another way of doing it...
 exec switch_root /easy_new /sbin/capsh --drop=${CAPS_DROP} -- -c "exec /sbin/init"
fi

###END###
