#Barry Kauler 2007 www.puppylinux.com
#2007 Lesser GPL licence v2 (http://www.fsf.org/licensing/licenses/lgpl.html)
#created for v3.01, oct 2007.
#v555 updated with DISTRO_FILE_PREFIX.
#w478 update.
#w482 use xorriso instead of cdrtools/cdrkit if installed,
#w482 variables CDRECORD and MKISOFS are exportedby rc.shutdown and savesessio-dvd.
#w482 replace -pad in cdrecord with padsize=300k.
#100820 relocate /var/local so it will get saved.
#100913 simplified puppy filenames.
#100916 no longer have DISTRO_DEVXSFS in /etc/DISTRO_SPECS.(it was only there briefly)
#120823 rerwin: multisession: screen out /.XLOADED when save.
#20201126 replace growisofs with xorriso, and zisofs compression.
#20201127 fix test X running. Change "CD/DVD" to "DVD" in messages.
#20201130 ask if want lockdown, once-only. see also "save" icon has checkbox.
#20201130 added strings in /usr/share/sss/script_strings/script_strings for translation.

KERNELVER="`uname -r`" #w478

##w478 compose name of 'zdrv', to fit 8+3 filename...
#PREFIX1CHAR="`echo -n "$DISTRO_FILE_PREFIX" | cut -c 1`"
#KERNEL3CHARS="`echo -n "$KERNELVER" | tr -d '.' | tr -d '\-' | tr -d '[a-z]' | rev | cut -c 1,2,3 | rev`"
#ZDRVSFS="z${PREFIX1CHAR}${DISTRO_VERSION}${KERNEL3CHARS}.sfs"

DEVCONSOLE="/dev/console" #when X not running
#PSINFO="`ps`"
#[ "`echo "$PSINFO" | grep 'X :0'`" != "" ] && DEVCONSOLE="/dev/tty" #running in rxvt.
#[ "`echo "$PSINFO" | grep 'Xorg :0'`" != "" ] && DEVCONSOLE="/dev/tty" #running in rxvt. 20201127 hmmm, maybe just test $DISPLAY
[ "$DISPLAY" ] && DEVCONSOLE="/dev/tty" #20201127

#waittrayclosedfunc is used by /etc/rc.d/rc.shutdown and /usr/sbin/savesession-dvd.
#v2.16...
waittrayclosed_func() {
 CDDRV="$1"
 #while [ "`dvd+rw-mediainfo $CDDRV 2>&1 | grep 'no media mounted'`" != "" ];do
 # clear
 # echo -e "\\033[1;31mThe media tray appears to be open, or media not inserted." >$DEVCONSOLE #31=red
 # echo -en "Please insert media and/or close tray then press ENTER key:\\033[0;39m " >$DEVCONSOLE
 # read waitaenter
 #done
 if [ "`cddetect -d${CDDRV} | grep '^tray open!'`" != "" ];then #v2.22
  echo -e "\\033[1;31mThe media tray appears to be open." >$DEVCONSOLE #31=red
  echo -en "Please close tray then press ENTER key:\\033[0;39m " >$DEVCONSOLE
  read waitaenter
 fi
 echo -e "\\033[1;34mIF STOPPED LONG TIME AT THIS MSG, MAKE SURE TRAY IS CLOSED THEN PRESS ENTER KEY:\\033[0;39m " >$DEVCONSOLE #34=blue
}


#multisavefunc is used by /etc/rc.d/rc.shutdown and /usr/sbin/savesession-dvd.
#these variables must be preset before calling...
#PUPSAVE=partition,filesystem,/${DISTRO_FILE_PREFIX}save.2fs where 1st 2 are the partition holding the file.
#SAVEPART=filesystem which is same as above filesystem.
#PUPPYVERSION=version example: 301.
multisavefunc() {
 #save session to folder on multisession CD/DVD.
 [ "$CDRECORD" = "" ] && CDRECORD='cdrecord' #w482 precaution.
 [ "$MKISOFS" = "" ] && MKISOFS='mkisofs' #w482 precaution.
 export MKISOFS
 touch -c /.badfolders #update modifytime, so will get saved. badlist, see init script.
 MSPATTERN="/dev/$SAVEPART " #v2.22
 if [ "`mount | grep "$MSPATTERN"`" != "" ];then
  echo "/dev/$SAVEPART mounted, must unmount it..."
  fuser -k -m /dev/$SAVEPART
  sync
  umount /dev/$SAVEPART 2> /dev/null
 fi
 CDR="/dev/$SAVEPART"

 if [ "`mount | grep "$CDR"`" != "" ];then #v3.01
  dialog --msgbox "The drive $CDR could not be unmounted, so current session cannot be saved to it.
This can happen if PC has insufficient RAM to copy all files off the CD, or an application is using the CD and cannot be killed.

Press ENTER key..." 0 0 >$DEVCONSOLE
  clear >$DEVCONSOLE
  return
 fi
  
 ##v3.01 have restored this... 
 #HDRCDR="ATAPI:$CDR" #v2.16
 #[ "`echo -n "$CDR" | grep '/dev/hd'`" = "" ] && HDRCDR="$CDR" #v2.16
 ##...no, sata cd (/dev/scd0) is still an atapi device? so don't implement this.
 HDRCDR="$CDR" #w482
  
 dialog --yes-label "SAVE" --no-label "NO SAVE" --yesno "Please insert the Puppy live-DVD media that you booted from, into the same DVD drive that you booted from -- this is /dev/$SAVEPART and it must be a burner drive!

Insert DVD media now, then press ENTER key to save session...
Or, press TAB then ENTER to not save session..." 0 0 >$DEVCONSOLE
 if [ ! $? -eq 0 ];then
  eject $CDR
  dialog --msgbox "Have not saved session to live-DVD.
Remove DVD media if you wish.
Do not press close button on drive.
Press ENTER key to close drive tray..." 0 0 >$DEVCONSOLE
  eject -t $CDR
  sleep 1
  clear >$DEVCONSOLE
  waittrayclosed_func $CDR #v2.16
  return
 fi
 
 if [ ! -f /root/.lockdown-ask.flg ];then
  dialog --yes-label "YES" --no-label "NO" --yesno "Do you want to reboot in lockdown mode?

If you answer YES, at next bootup all internal drives will be disabled. However, you will still be able to save sessions to the DVD, and access USB drives.

If you answer NO, next bootup will have normal access to the internal drives.

MOST IMPORTANT:
You are only asked this question once, when the first session is saved.
For YES, an empty file /root/.lockdown.flg will be created. For NO, /root/.lockdown.flg will not be created.
In the future, to change the choice, there is a checkbox via the save icon on the desktop, or you can manually create or delete this file." 0 0 >$DEVCONSOLE
  if [ $? -eq 0 ];then
   touch /root/.lockdown.flg
  else
   rm -f /root/.lockdown.flg 2>/dev/null
  fi
  touch /root/.lockdown-ask.flg
 fi
 
 clear >$DEVCONSOLE
 if [ "`LANG=C cddetect -d${CDR} | grep '^no disc!'`" != "" ];then #v2.22
  echo -e "\\033[1;31mIt seems that the media is not inserted." >$DEVCONSOLE #31=red
  echo -en "Please insert media then press ENTER key:\\033[0;39m " >$DEVCONSOLE
  read waitaenter
 fi
 
 MEDIATYPE="CD"
 waittrayclosed_func $CDR #v2.16
 DVDRWMEDIAINFO="`LANG=C dvd+rw-mediainfo $CDR 2>&1`"
 [ "`echo -n "$DVDRWMEDIAINFO" | grep --extended-regexp "non\\-DVD|not a DVD unit|Input/Output error|Input/output error|Invalid argument"`" = "" ] && MEDIATYPE="DVD"

 #if new version iso inserted, need to save all files, not just changed/new...
 MSPATTERN="$CDR "
 DVDMNTPT="`mount | grep "$MSPATTERN" | tr -s " " | cut -f 3 -d " "`" #in case not unmounted.
 if [ "$DVDMNTPT" = "" ];then
  mkdir -p /tmp/dvdmntpt
  mount -t iso9660 $CDR /tmp/dvdmntpt
  [ $? -eq 0 ] && DVDMNTPT="/tmp/dvdmntpt"
 fi
 if [ "$DVDMNTPT" != "" ];then
  if [ $ORIGPUPMODE -eq 77 ];then #bypass first boot, PUPMODE=5. v2.22
   [ "`find $DVDMNTPT -maxdepth 1 -type d -name 20[0-9][0-9]*`" = "" ] && NEWISO="yes"
  fi
  umount $CDR 2>/dev/null
 fi

 #want to copy contents of /initrd/pup_rw to a new folder on /dev/$SAVEPART...
 MYDATE="`date "+%Y-%m-%d-%H-%M"`" #this will become the folder name on cd.

 SAVEABORT="" #v3.01
 while [ 1 ];do #WHILELOOP1

  #if have new live-cd, need a 'full save', not just what is in pup_rw. Maybe easiest
  #way is to save two tracks, pup_ro1, which has all prior saved folders read from cd
  #at bootup, then save latest session, pup_rw...
  if [ "$NEWISO" = "yes" ];then
   echo "Burning data from previous $MEDIATYPE to first track..." >$DEVCONSOLE
   #use last folder name from previous cd, to avoid name conflict with next folder...
   FOLDEROLD="`echo -n "$PUPSAVE" | cut -f 2 -d '/'`"
   #minimal error checking here, errors reported when save current session (below)...
   if [ "$MEDIATYPE" = "CD" ];then
    waittrayclosed_func $CDR #v2.16 v3.01 now HDRCDR...
    SECT=`$CDRECORD -msinfo dev=${HDRCDR} 2>/tmp/cdrerr.txt | grep '^[0-9]*.[0-9]'` #v3.01
    if [ "$SECT" = "" ];then
     SAVEABORT="$CDR" #v3.01
     break
    else
     waittrayclosed_func $CDR #v2.16
     #v2.02 added -pad ...  v3.01 now HDRCDR...
     #v2.16 removed -pad from cdrecord as mkisofs has -pad by default... no, leave for now...
     $MKISOFS -D -R -C $SECT -M $CDR -quiet -new-dir-mode 0755 -graft-points ${FOLDEROLD}=/initrd/pup_ro1 | $CDRECORD -multi -data -tao -eject -v speed=4 gracetime=2 padsize=300k dev=${HDRCDR} -
    fi
   else #dvd
    waittrayclosed_func $CDR #v2.16
    #v2.16 removed '-speed=4' as got 'failed to change write speed' error on one drive...
    #growisofs -M $CDR -D -R -quiet -new-dir-mode 0755 -graft-points ${FOLDEROLD}=/initrd/pup_ro1 2> /tmp/dvderr.txt
    
    #20201127 use xorriso directly, with zisofs compression...
    xorriso \
    -report_about warning \
    -dev "${CDR}" \
    -compliance deep_paths:long_paths \
    -pathspecs as_mkisofs \
    -- \
    -add ${FOLDEROLD}=/initrd/pup_ro1 -- \
    -zisofs level=8:block_size=64k \
    -find / -type f -pending_data -exec set_filter --zisofs -- \
    -fs 32m \
    2> /tmp/dvderr.txt
    
   fi
  fi
  #v2.22 NEWISO=""

  #normal session save of new/changed files...
  #exclude .sfs files... v3.97 no, allow to save... 20201126 add xREMSFS...
  REMSFS=""; xREMSFS=""
  #for ONESFS in `ls -1 /initrd/pup_rw/*.sfs 2>/dev/null | tr "\n" " "`
  #do
  # REMSFS="$REMSFS -x $ONESFS"
  # xREMSFS="${xREMSFS} ${ONESFS}"
  #done
  
  #tack on this exclude as well... (samba network drives mount here)
  if [ -d /initrd/pup_rw/root/mnt ];then
   REMSFS="${REMSFS} -x /initrd/pup_rw/root/mnt"
   xREMSFS="${xREMSFS} /initrd/pup_rw/root/mnt" #20201126
  fi
  #if a new iso, do not want to save /.badfolders file...
  if [ "$NEWISO" = "yes" ];then
   if [ -f /initrd/pup_rw/.badfolders ];then
    REMSFS="${REMSFS} -x /initrd/pup_rw/.badfolders"
    xREMSFS="${xREMSFS} /initrd/pup_rw/.badfolders"
   fi
  fi
  #v2.02 removed, messes up some pkgs...
  ##move some files to /archive, they will not get reloaded...
  #MAXASIZE="99000k"
  #ARCHIVEFILES="`find /initrd/pup_rw -type f -mount -name "*.tar*" -or -name "*.tgz" -or -name "*.gz" -or -name "*.bz2" -or -name "*.tbz2" -or -name "*.zip" -or -size +$MAXASIZE | grep -v "/root/\.etc/" | grep -v "/root/\.usr/" | grep -v "/root/my\-roxapps/" | grep -v '\.sfs' | sed -e 's/\/initrd\/pup_rw//g'`"
  #if [ ! "$ARCHIVEFILES" = "" ];then
  # for ONEFILE in $ARCHIVEFILES
  # do
  #  echo "Moving $ONEFILE to $MYDATE/archive on CD, will not reload..."
  #  mv -f $ONEFILE /archive/ 2>/dev/null
  # done
  # sync
  #fi
  
  #100820 relocate /var/local so it will get saved (see 'init' script at bootup)...
  if [ -d /initrd/pup_rw/var/local ];then
   rm -rf /initrd/pup_rw/root/.var_saved #precaution.
   mkdir -p /initrd/pup_rw/root/.var_saved
   cp -a /initrd/pup_rw/var/local /initrd/pup_rw/root/.var_saved/
  fi

  if [ "$MEDIATYPE" = "CD" ];then
   waittrayclosed_func $CDR #v2.16 v3.01 now HDRCDR...
   SECT=`$CDRECORD -msinfo dev=${HDRCDR} 2>/tmp/cdrerr.txt | grep '^[0-9]*.[0-9]'`
   if [ "$SECT" = "" ];then
    SAVEABORT="$CDR" #v3.01
    break #v3.01
   else
    waittrayclosed_func $CDR #v2.16
    #TSIZE="`$MKISOFS -print-size -D -R -C $SECT -M $CDR -quiet -new-dir-mode 0755 -graft-points -x /initrd/pup_rw/tmp $REMSFS -x /initrd/pup_rw/proc -x /initrd/pup_rw/sys -x /initrd/pup_rw/var -x /initrd/pup_rw/initrd -x /initrd/pup_rw/mnt ${MYDATE}=/initrd/pup_rw`"
    TSIZE="`$MKISOFS -print-size -D -R -C $SECT -M $CDR -quiet -new-dir-mode 0755 -graft-points -x /initrd/pup_rw/tmp $REMSFS -x /initrd/pup_rw/proc -x /initrd/pup_rw/sys -x /initrd/pup_rw/var -x /initrd/pup_rw/initrd -x /initrd/pup_rw/mnt -x /initrd/pup_rw/root/.XLOADED ${MYDATE}=/initrd/pup_rw`" #120823
    #-J Joliet extension disabled, sometimes causes failure...
    #v2.02 added -pad ...
    waittrayclosed_func $CDR #v2.16 v3.01 now HDRCDR...
    #v2.16 removed -pad from cdrecord as mkisofs has -pad by default... no, leave for now...
    #$MKISOFS -D -R -C $SECT -M $CDR -quiet -new-dir-mode 0755 -graft-points -x /initrd/pup_rw/tmp $REMSFS -x /initrd/pup_rw/proc -x /initrd/pup_rw/sys -x /initrd/pup_rw/var -x /initrd/pup_rw/initrd -x /initrd/pup_rw/mnt ${MYDATE}=/initrd/pup_rw | $CDRECORD -multi -data -tao -eject -v speed=4 gracetime=2 padsize=300k tsize=${TSIZE}s dev=${HDRCDR} -
    #20201126 add "-x /initrd/pup_rw/run"...
    $MKISOFS -D -R -C $SECT -M $CDR -quiet -new-dir-mode 0755 -graft-points -x /initrd/pup_rw/tmp $REMSFS -x /initrd/pup_rw/proc -x /initrd/pup_rw/run -x /initrd/pup_rw/sys -x /initrd/pup_rw/var -x /initrd/pup_rw/initrd -x /initrd/pup_rw/mnt -x /initrd/pup_rw/root/.XLOADED ${MYDATE}=/initrd/pup_rw | $CDRECORD -multi -data -tao -eject -v speed=4 gracetime=2 padsize=300k tsize=${TSIZE}s dev=${HDRCDR} - #120823
    [ $? -eq 0 ] && break
   fi
   echo "Cannot write to CD" > /tmp/dvderr.txt
  else #dvd
    waittrayclosed_func $CDR #v2.16
    #-J Joliet extension disabled, sometimes causes failure...
    #v2.16 removed '-speed=4' as got 'failed to change write speed' error on one drive...
    #20201126 add "-x /initrd/pup_rw/run"...
    #growisofs -M $CDR -D -R -quiet -new-dir-mode 0755 -graft-points -x /initrd/pup_rw/tmp $REMSFS -x /initrd/pup_rw/proc -x /initrd/pup_rw/run -x /initrd/pup_rw/sys -x /initrd/pup_rw/var -x /initrd/pup_rw/initrd -x /initrd/pup_rw/mnt ${MYDATE}=/initrd/pup_rw 2> /tmp/dvderr.txt
    
    #20201126 replace growisofs with xorriso, thanks to thomas...
    xorriso \
    -report_about warning \
    -dev "${CDR}" \
    -compliance deep_paths:long_paths \
    -pathspecs as_mkisofs \
    -not_paths \
      /initrd/pup_rw/tmp /initrd/pup_rw/proc /initrd/pup_rw/sys \
      /initrd/pup_rw/var /initrd/pup_rw/initrd /initrd/pup_rw/mnt \
      /initrd/pup_rw/run ${xREMSFS} /initrd/pup_rw/root/.XLOADED \
      -- \
    -add ${MYDATE}=/initrd/pup_rw -- \
    -zisofs level=8:block_size=64k \
    -find / -type f -pending_data -exec set_filter --zisofs -- \
    -fs 32m \
    2> /tmp/dvderr.txt
    
    [ $? -eq 0 ] && break
  fi
  dialog --yes-label "BLANK ${MEDIATYPE}-R" --no-label "UPGRADE ${MEDIATYPE}-R" --yesno "ERROR MESSAGE:
`cat /tmp/dvderr.txt | head -n 1`

It seems to be time to migrate to a new live-${MEDIATYPE}.
You can migrate to a new blank ${MEDIATYPE}-R, or upgrade to a new Puppy version iso file that has been previously burnt in multisession mode to a ${MEDIATYPE}-R.

WARNING:
If the PC shuts down without allowing the migration, try rebooting the current live-$MEDIATYPE and shutdown again.

Have the new media ready, but do not insert it yet.
Just select the appropriate button..." 0 0 >$DEVCONSOLE
  if [ $? -eq 0 ];then #new blank cd/dvd.
   DVDMNTPT="`mount | grep "$CDR" | tr -s " " | cut -f 3 -d " "`" #in case not unmounted.
   if [ "$DVDMNTPT" = "" ];then
    mkdir /tmp/dvdmntpt
    mount -t iso9660 $CDR /tmp/dvdmntpt
    [ ! $? -eq 0 ] && break
    DVDMNTPT="/tmp/dvdmntpt"
   fi
   #get vmlinuz etc off current dvd...
   echo "Copying some files off $CDR..." >$DEVCONSOLE
   mkdir /tmp/livecd
   cp $DVDMNTPT/isolinux.bin /tmp/livecd/
   cp $DVDMNTPT/isolinux.cfg /tmp/livecd/
   cp $DVDMNTPT/vmlinuz /tmp/livecd/
   cp $DVDMNTPT/initrd.gz /tmp/livecd/
   cp $DVDMNTPT/boot.msg /tmp/livecd/ 2> /dev/null
   cp $DVDMNTPT/goofy.16 /tmp/livecd/ 2> /dev/null
   cp $DVDMNTPT/logo.16 /tmp/livecd/ 2> /dev/null #w478
   cp $DVDMNTPT/help.msg /tmp/livecd/ 2> /dev/null #w478
   #cp $DVDMNTPT/${DISTRO_PUPPYSFS} /tmp/livecd/ 2> /dev/null
   cp $DVDMNTPT/${DISTRO_ZDRVSFS} /tmp/livecd/ 2> /dev/null #100913
   sync
   umount $CDR
   [ ! $? -eq 0 ] && break
   eject $CDR
   dialog --msgbox "Take out the old media and write completion date on it.
NOTE: Do not press tray-close button on $MEDIATYPE drive.
Please insert new media in tray then press ENTER key..." 0 0 >$DEVCONSOLE
   eject -t $CDR
   
   ##echo "/$PUPSFS" > /tmp/dvdextras.txt
   echo -n "/initrd/mnt/tmpfs/" > /tmp/dvdextras.txt #v3.01
   [ -f /initrd/mnt/tmpfs/${DISTRO_PUPPYSFS} ] && echo "/initrd/mnt/tmpfs/${DISTRO_PUPPYSFS}" >> /tmp/dvdextras.txt #100913
   #ls -1 /initrd/mnt/tmpfs | grep "${DISTRO_FILE_PREFIX}r" >> /tmp/dvdextras.txt
   ls -1 /initrd/mnt/tmpfs | grep "${DISTRO_FILE_PREFIX}\-" >> /tmp/dvdextras.txt #100913 superfluous now.
   #[ -f /initrd/mnt/tmpfs/${DISTRO_DEVXSFS} ] && echo "/initrd/mnt/tmpfs/${DISTRO_DEVXSFS}" > /tmp/dvdextras.txt #100913
   
   waittrayclosed_func $CDR #v2.16
   if [ "$MEDIATYPE" = "DVD" ];then
    #v2.16 removed '-speed=4' as got 'failed to change write speed' error on one drive...
    growisofs -Z $CDR -R -D -quiet -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -path-list /tmp/dvdextras.txt /tmp/livecd
    [ ! $? -eq 0 ] && break
   else
    #v2.02 added -pad ...
    #v2.16 removed -pad from cdrecord as mkisofs has -pad by default... no, leave for now...
    $MKISOFS -D -R -quiet -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -path-list /tmp/dvdextras.txt /tmp/livecd | $CDRECORD -multi -tao -data -v speed=4 gracetime=2 padsize=300k dev=$HDRCDR  -
    [ ! $? -eq 0 ] && break
   fi
  fi
  #have new live-cd, and loops back up to save session, but need a 'full save', not just
  #what is in pup_rw. Maybe easiest way is to save two tracks, pup_ro1, which has all prior
  #saved folders read from cd at bootup, then save latest session, pup_rw...
  NEWISO="yes" #loop back up.
 done #end WHILELOOP1

 sync
 [ "`mount | grep "$CDR"`" != "" ] && STILLMNTD="yes" #v3.01
 if [ "$STILLMNTD" = "yes" ];then
  CLOSEMSG="Press ENTER key to complete the shutdown..."
 else
  CLOSEMSG="Remove $MEDIATYPE media if you wish.
Do not press close button on drive.
Press ENTER key to close drive tray
(laptop drive, have to manually close)"
  eject $CDR
 fi
 if [ "$SAVEABORT" = "" ];then #v3.01
  dialog --msgbox "Have saved session to live-$MEDIATYPE
(unless it has not, which is an error).

${CLOSEMSG}" 0 0 >$DEVCONSOLE
 else
  dialog --msgbox "A problem with the ${MEDIATYPE} drive ${SAVEABORT},
unable to save to save to it. Sorry.

${CLOSEMSG}" 0 0 >$DEVCONSOLE
 fi
 [ "$STILLMNTD" != "yes" ] && eject -t $CDR #close tray.
 sleep 1
 #waittrayclosed_func $CDR #v2.16
} #end multisavefunc


###END###
