#!/bin/ash
#(c) Copyright Barry Kauler, Feb 12, 2015. License GPL v3 (/usr/share/doc/legal).
#convert Quirky to Puppy Linux, and create a live-CD.
#151105 first release.
#200123 update for EasyOS.
#200125 choose language.
#200126 rc.sysinit needs elspci. remove /etc/init.d/ec-net. add "install" to PuppyPin
#200126 symlinks to puppy logos. fix rox launch in PuppyPin. fix menu.
#200128 usr/bin/seamonkeyQNEW name changed.
#200128 syslinux v6 is crap, revert to v4.07
#200131 /usr/share/doc/puppy has help, welcome and home html files.
#200203 new wallpaper. remove /home, /mnt/wkg, /home/downloads open/save defaults.
#200203 change text on splash screen from "Puppy Buster64" to "EasyPup". do not translate usr/share/doc/puppy
#200208 rootfs-complete/home symlink to root, for easyos compatibility. remove more easyos stuff.
#200209 get rid of /home, that is purely an easyos thing, confuses puppy people, as have /mnt/home symlink to partition with save-file.
#200210 log files that have "EasyOS" and "Easy" changed to "Puppy".
#200216 translate early-boot splash screens.
#200216 translate root/Choices/ROX-Filer/PuppyPin
#200219 usr/share/doc/puppy no longer exists, it is now puppy/rootfs-skeleton/.../easy
#200508 refine 200210, preppend "pup_" to $TEXTDOMAIN.
#200530 fix seamonkey prefs.js path.

export LANG=C
err_exit() {
 echo
 echo "$1"
 exit 1
}

sed -e 's%Easy%Puppy%' ../DISTRO_SPECS > ./DISTRO_SPECS
. ./DISTRO_SPECS
RIGHTVER="$DISTRO_VERSION"
. ../build-choices #has BUILD_CHOICE_LANG
. ../WOOFMERGEVARS #200126

#200125 choose language... (code from create-live-cd)
LANGSavail="$(find ../sandbox3 -mindepth 1 -maxdepth 1 -type d -name 'export-sfs-*' | rev | cut -f 1 -d '-' | rev | tr '\n' ' ')"
echo "Available: ${LANGSavail}"
echo -n "Type the two-letter code for language to build: "
read DEFAULTLANG1
if [ ! -d ../sandbox3/export-sfs-${DEFAULTLANG1} ];then
 echo "Error: folder ../sandbox3/export-sfs-${DEFAULTLANG1} does not exist, aborting."
 exit 1
fi

#200125...
echo
echo 'Please wait, copying to sandbox4/rootfs-complete...'
rm -rf sandbox4 2>/dev/null
mkdir sandbox4
sync
EASYSFS="$(find ../sandbox3/export-sfs-${DEFAULTLANG1} -type f -name 'easy_*.sfs' | head -n 1)"
[ ! "$EASYSFS" ] && exit 1
cp -f ${EASYSFS} ./sandbox4/easy.sfs
mkdir sandbox4/temp1
mount -t squashfs sandbox4/easy.sfs sandbox4/temp1
mkdir sandbox4/rootfs-complete
cp -a sandbox4/temp1/* sandbox4/rootfs-complete/
sync
umount sandbox4/temp1

#use xorriso if it is installed (see also functions4puppy)...
CDRECORD='cdrecord'
MKISOFS='mkisofs'
if [ "`which xorriso`" != "" ];then
 CDRECORD='xorrecord'
 MKISOFS='xorrisofs' #growisofs reads this variable.
fi
export CDRECORD MKISOFS

#what kernel was chosen?...
KERNVER="$(find sandbox4/rootfs-complete/lib/modules -maxdepth 1 -type d -name '[2345]*' | head -n 1 | rev | cut -f 1 -d '/' | rev)"

DOTCONFIG="$(find sandbox4/rootfs-complete/etc/modules -maxdepth 1 -type f -name 'DOTconfig*' | head -n 1)"

PREBUILD='yes'
[ "$DOTCONFIG" = "" ] && PREBUILD='no'
if [ "$PREBUILD" = "no" ];then
 echo "The needed files are missing from ../sandbox3/build"
 echo 'The previous scripts 0* - 3* have to be run first.'
 echo "Quiting script..."
 exit
fi

if [ ! -e /usr/bin/gcc ];then
 echo
 echo "The 'devx' SFS file must be loaded. Quiting script..."
 exit
fi

echo "This script will build Puppy Linux and create a live-CD"
cd sandbox4

#change all occurrences of "EasyOS" and "Easy" to "Puppy"... 200210 log changed files...
echo "replacing Easy with Puppy in rootfs-skeleton scripts..."
mkdir -p temp1
echo -n '' > Easy-2-Puppy-files.log
for aFILE in `find ../../rootfs-skeleton/usr -type f`
do
 [ ! "$aFILE" ] && continue
 file ${aFILE} > /tmp/7build-puppy-cd-temp1
 if grep -q 'shell script' /tmp/7build-puppy-cd-temp1;then
  if ! grep -q '^export TEXTDOMAIN' "$aFILE"; then continue; fi #200508
  BASEPATH="$(echo -n "$aFILE" | sed -e 's%\.\./\.\./rootfs-skeleton/%%')"
  BASEDIR="$(dirname "$BASEPATH")"
  [ -e ../rootfs-skeleton/"$BASEPATH" ] && continue #200508
  [ "$BASEDIR" == "usr/share/doc/easy" ] && continue #200203 already done for EasyPup. 200219
  if [ -f rootfs-complete/${BASEPATH} ];then #200128 usr/bin/seamonkeyQNEW got changed.
   echo -n '.'
   BASENAME="$(basename ${BASEPATH})"
   cp -a -f rootfs-complete/${BASEPATH} temp1/
   #200508 refine replacement...
   #sed -i -e 's%EasyOS%Puppy%g' rootfs-complete/${BASEPATH}
   #sed -i -e 's%Easy%Puppy%g' rootfs-complete/${BASEPATH}
   sed -i -e 's%\(gettext [^)]*\)EasyOS%\1Puppy%g' rootfs-complete/${BASEPATH}
   sed -i -e 's%\(gettext [^)]*\)Easy\([. ]\)%\1Puppy\2%g' rootfs-complete/${BASEPATH}
   cmp -s temp1/${BASENAME} rootfs-complete/${BASEPATH}
   if [ $? -ne 0 ];then
    echo "rootfs-complete/${BASEPATH}" >> Easy-2-Puppy-files.log
    #200508 ...see further down, some files get removed from this log.
    #200508 change the TEXTDOMAIN name, preppend "pup_"...
    echo -n "${BASENAME}"
    if ! grep -q '^export TEXTDOMAIN=pup_' rootfs-complete/${BASEPATH}; then
     sed -i -e 's%^export TEXTDOMAIN=\([^ ]*\)%export TEXTDOMAIN=pup_\1%' rootfs-complete/${BASEPATH}
    fi
   fi
   rm -f temp1/${BASENAME}
  fi
 fi
done
echo
sync

#now overwrite with original puppy scripts...
echo "Overwriting rootfs-complete with original Puppy scripts..."
cp -a -f --remove-destination ../rootfs-skeleton/* rootfs-complete/
sync
mv -f rootfs-complete/sbin/initNEW rootfs-complete/sbin/init

#
cp -a -f ../exe/${DISTRO_TARGETARCH}/welcome1stboot rootfs-complete/usr/sbin/
cp -a -f ../DISTRO_SPECS rootfs-complete/etc/

#note, current dir is puppy/sandbox4
DEFAULTLANG="$(grep '^LANG=' rootfs-complete/etc/profile | cut -f 2 -d '=')"
DEFAULTLANG1="${DEFAULTLANG%_*}"
DEFAULTLANG12="${DEFAULTLANG%.*}" #ex: de_DE 200216

#200126 some docs... 200219...
#rm -rf rootfs-complete/usr/share/doc/easy
##200131 htm docs are now in the 'puppy' folder...
#mv -f rootfs-complete/usr/share/doc/puppy rootfs-complete/usr/share/doc/easy
rm -f rootfs-complete/usr/share/doc/easy/images/desktop1.png
rm -f rootfs-complete/usr/share/doc/easy/images/easy96.png
rm -f rootfs-complete/usr/share/doc/easy/images/top-of-layers.png
rm -f rootfs-complete/usr/share/doc/easy/images/working-partition.png
#code from 3builddistro, modified...
 echo "Translating home.htm, welcome.htm, help.htm..."
 if [ "$WOOF_HOSTARCH" = "$WOOF_TARGETARCH" ];then
  LANG=${DEFAULTLANG} chroot rootfs-complete /usr/share/doc/easy/help.sh
  LANG=${DEFAULTLANG} chroot rootfs-complete /usr/share/doc/easy/home.sh
  LANG=${DEFAULTLANG} chroot rootfs-complete /usr/share/doc/easy/welcome.sh
 else
  #have to do it in the host...
  cp -a -f /usr/share/doc/home.htm /usr/share/doc/home.htmBAK
  LANG=${DEFAULTLANG} rootfs-complete/usr/share/doc/easy/help.sh
  LANG=${DEFAULTLANG} rootfs-complete/usr/share/doc/easy/home.sh
  LANG=${DEFAULTLANG} rootfs-complete/usr/share/doc/easy/welcome.sh
  cp -a -f --remove-destination /usr/share/doc/easy/help.htm rootfs-complete/usr/share/doc/easy/
  cp -a -f --remove-destination /usr/share/doc/easy/home.htm rootfs-complete/usr/share/doc/easy/
  cp -a -f --remove-destination /usr/share/doc/easy/welcome.htm rootfs-complete/usr/share/doc/easy/
  cp -a -f /usr/share/doc/home.htm rootfs-complete/usr/share/doc/
  mv -f /usr/share/doc/home.htmBAK /usr/share/doc/home.htm
  ln -snf home_${LANG%_*}.htm /usr/share/doc/easy/home.htm  #restore host links.
  ln -snf home_${LANG%_*}.htm /usr/share/doc/easy/help.htm
  ln -snf home_${LANG%_*}.htm /usr/share/doc/easy/welcome.htm
 fi 

#200126 symlinks to puppy logos...
ln -snf puppylogo48.png rootfs-complete/usr/share/doc/logo48.png
ln -snf puppylogo96.png rootfs-complete/usr/share/doc/logo96.png


#remove some .desktop files...
for aDESK in easy-bootmanager easy-containers easydd easy-installer easy-remaster easy-version-control ec-console ec-desk ec-www
do
 [ -f rootfs-complete/usr/share/applications/${aDESK}.desktop ] && rm -f rootfs-complete/usr/share/applications/${aDESK}.desktop
done
if [ "$WOOF_HOSTARCH" = "$WOOF_TARGETARCH" ];then
 chroot rootfs-complete /usr/sbin/fixmenus
fi

#any more to change...
#note, etc/issue gets fixed at first bootup, in rc.sysinit
for AFILE in etc/issue
do
 sed -i -e 's%Easy%Puppy%' rootfs-complete/${AFILE}
done

#200126 remove some container scripts...
rm -f rootfs-complete/etc/init.d/ec-net
sed -i -e 's%:ec-net%%' rootfs-complete/etc/eventmanager

#200216 translate root/Choices/ROX-Filer/PuppyPin
#usr/share/sss/desk_strings has the translation for EasyOS, however as we have a
#different PuppyPin for EasyPup, let's do it this way...
if [ -f rootfs-complete/root/Choices/ROX-Filer/PuppyPin.${DEFAULTLANG1} ];then
 cp -a -f rootfs-complete/root/Choices/ROX-Filer/PuppyPin.${DEFAULTLANG1} rootfs-complete/root/Choices/ROX-Filer/PuppyPin
 rm -f rootfs-complete/root/Choices/ROX-Filer/PuppyPin.*
fi

#remove containers from desktop... 200126 no, using ready-made files...
#grep -v 'ec\-chroot' rootfs-complete/root/Choices/ROX-Filer/PuppyPin > /tmp/7build-puppy-cd-pp
#mv -f /tmp/7build-puppy-cd-pp rootfs-complete/root/Choices/ROX-Filer/PuppyPin
##200126 add "install" to PuppyPin...
#grep -v '^</pinboard>' rootfs-complete/root/Choices/ROX-Filer/PuppyPin > /tmp/build-puppy-cd-install
#echo '  <icon x="672" y="32" label="install">/usr/sbin/dotpup</icon>
#</pinboard>' >> /tmp/build-puppy-cd-install
#mv -f /tmp/build-puppy-cd-install rootfs-complete/root/Choices/ROX-Filer/PuppyPin
##there is no /home folder...
#sed -i -e 's%dir=/home%dir=/root%' rootfs-complete/root/Choices/ROX-Filer/PuppyPin
##also, change the rox label...
#sed -i -e 's%"home"%"file"%' rootfs-complete/root/Choices/ROX-Filer/PuppyPin
#change to a puppy wallaper...
if [ -f rootfs-complete/usr/share/backgrounds/default.png ];then
 IEXE='png'
else #default.jpg
 IEXE='jpg'
fi
mv -f rootfs-complete/usr/share/backgrounds/default.${IEXE} rootfs-complete/usr/share/backgrounds/default2.${IEXE}
#mv -f rootfs-complete/usr/share/backgrounds/puppy_lights_gray2_dejan555.jpg rootfs-complete/usr/share/backgrounds/default.jpg
mv -f rootfs-complete/usr/share/backgrounds/puppy-black-blue-streaks.jpg rootfs-complete/usr/share/backgrounds/default.jpg #200203
sed -i -e "s%/usr/share/backgrounds/default\.[pj][np]g%/usr/share/backgrounds/default.jpg%" rootfs-complete/root/Choices/ROX-Filer/PuppyPin

#200126 rc.sysinit needs elspci...
cp -a ../exe-static/${DISTRO_TARGETARCH}/elspci rootfs-complete/sbin/

#200203 easyos has /home, /mnt/wkg, /home/downloads default open/save dkgs...
#sed -i -e 's%/home/downloads%/root/Downloads%' rootfs-complete/root/.mozilla/seamonkey/3o1ptd5r.default/prefs.js
sed -i -e 's%/home/downloads%/root/Downloads%' rootfs-complete/root/.mozilla/seamonkey/*.default/prefs.js #200530
rm -rf rootfs-complete/root/.config/libreoffice
rm -rf rootfs-complete/root/.config/inkscape
rm -rf rootfs-complete/root/.config/grisbi
sed -i -e 's%^cd /home%cd /root #easypup fix%' rootfs-complete/usr/bin/xwin
sed -i -e 's%path = /home%path = /root%' rootfs-complete/etc/samba/smb.conf
sed -i -e 's%/home/media/images%/root/media%' rootfs-complete/etc/mtpaint/mtpaintrc

#200208 for easyos compatibility...
[ -d rootfs-complete/home ] && [ ! -h rootfs-complete/home ] && rm -rf rootfs-complete/home
#ln -snf root rootfs-complete/home
#200209 no, get rid of /home, that is purely an easyos thing, confuses puppy people, as have /mnt/home symlink to partition with save-file.
[ -h rootfs-complete/home ] && rm -f rootfs-complete/home

#200208 remove...
rm -f rootfs-complete/usr/sbin/ec-chroot*
rm -f rootfs-complete/usr/sbin/easy-*
rm -rf rootfs-complete/usr/local/easy_containers
rm -rf rootfs-complete/usr/local/sfsget #have /usr/sbin/sfsget for easypup.

#200508 remove from this log...
sed -i '/sbin\/ec-chroot/d' Easy-2-Puppy-files.log
sed -i '/sbin\/easy-/d' Easy-2-Puppy-files.log
sed -i '/local\/easy_/d' Easy-2-Puppy-files.log
sed -i '/local\/sfsget/d' Easy-2-Puppy-files.log
sed -i '/NOTUSED/d' Easy-2-Puppy-files.log
sed -i '/TEST/d' Easy-2-Puppy-files.log

echo "Creating 'build' folder..."
mkdir build
ln -s build build-${DEFAULTLANG1}
cp -a ../boot/boot-dialog/* build/
cp -a ../../sandbox3/vmlinuz build/

#code from live-cd/create-live-cd...
if ! which openssl ;then exit 1 ; fi
RANDHEX8="$(openssl rand -hex 4)" #want this for disk identifier.
[ "$RANDHEX8" == "12345678" ] && RANDHEX8="$(openssl rand -hex 4)" #181205 reserved, try again.
echo "Random hex number: ${RANDHEX8}"

#also from create-live-cd. get some files...
#isolinux.bin ...
ISOLINUXPATH=''
[ -f /usr/lib/syslinux/isolinux.bin ] && ISOLINUXPATH='/usr/lib/syslinux'
[ -f /usr/share/syslinux/isolinux.bin ] && ISOLINUXPATH='/usr/share/syslinux' #my pet.
[ -f /usr/lib/ISOLINUX/isolinux.bin ] && ISOLINUXPATH='/usr/lib/ISOLINUX' #debian/ubuntu.
[ ! "$ISOLINUXPATH" ] && err_exit 'isolinux.bin missing. Aborting.'
cp -f ${ISOLINUXPATH}/isolinux.bin ./
cp -f ${ISOLINUXPATH}/isolinux.bin ./build-${DEFAULTLANG1}/
#isohdpfx.bin ...
ISOLINUXPATH=''
[ -f /usr/lib/syslinux/isohdpfx.bin ] && ISOLINUXPATH='/usr/lib/syslinux'
[ -f /usr/share/syslinux/isohdpfx.bin ] && ISOLINUXPATH='/usr/share/syslinux' #my pet.
[ -f /usr/lib/ISOLINUX/isohdpfx.bin ] && ISOLINUXPATH='/usr/lib/ISOLINUX' #debian/ubuntu.
[ ! "$ISOLINUXPATH" ] && err_exit 'isohdpfx.bin missing. Aborting.'
cp -f ${ISOLINUXPATH}/isohdpfx.bin ./
SYSLINUXC32PATH=''
[ -f /usr/lib/syslinux/modules/bios/ldlinux.c32 ] && SYSLINUXC32PATH='/usr/lib/syslinux/modules/bios' #in syslinux-common, debian/ubuntu
[ ! "$SYSLINUXC32PATH" ] && [ -f /usr/share/syslinux/ldlinux.c32 ] && SYSLINUXC32PATH='/usr/share/syslinux'
cp -f ${SYSLINUXC32PATH}/ldlinux.c32 build-${DEFAULTLANG1}/
[ ! -f build-${DEFAULTLANG1}/ldlinux.c32 ] && err_exit 'ldlinux.c32 not found. Aborting.'
#gptmbr.bin ...
GPTMBRPATH=''
[ -f /usr/lib/syslinux/gptmbr.bin ] && GPTMBRPATH='/usr/lib/syslinux'
[ -f /usr/share/syslinux/gptmbr.bin ] && GPTMBRPATH='/usr/share/syslinux'
[ -f /usr/lib/SYSLINUX/gptmbr.bin ] && GPTMBRPATH='/usr/lib/SYSLINUX'
[ ! "$GPTMBRPATH" ] && err_exit 'gptmbr.bin not found. Aborting'
cp -f ${GPTMBRPATH}/gptmbr.bin ./
#ldlinux.e64 ...
 EFI64PATH=''
 [ -f /usr/share/syslinux/efi64/ldlinux.e64 ] && EFI64PATH='/usr/share/syslinux/efi64' #my pet
 [ -f /usr/lib/syslinux/modules/efi64/ldlinux.e64 ] && EFI64PATH='/usr/lib/syslinux/modules/efi64' #debian/ubuntu
 [ ! "$EFI64PATH" ] && err_exit 'efi64/ldlinux.e64 missing. Aborting.'
 cp -f ${EFI64PATH}/ldlinux.e64 ./
#syslinux.efi ...
 EFI64PATH=''
 [ -f /usr/share/syslinux/efi64/syslinux.efi ] && EFI64PATH='/usr/share/syslinux/efi64' #my pet
 [ -f /usr/lib/SYSLINUX.EFI/efi64/syslinux.efi ] && EFI64PATH='/usr/lib/SYSLINUX.EFI/efi64' #debian/ubuntu. 170710 fix path.
 [ ! "$EFI64PATH" ] && err_exit 'efi64/syslinux.efi missing. Aborting.'
 cp -f ${EFI64PATH}/syslinux.efi ./

#build initrd.cpio...
echo
echo "Preparing to create initrd.gz cpio archive..."
sync
#puppy files...
mkdir initrd-tree
cp -a -f ../boot/initrd-tree0/* initrd-tree/
cp ../DISTRO_SPECS initrd-tree/
sync

echo " copying puppy static executables into initrd-tree..."
cp -a ../exe-static/${DISTRO_TARGETARCH}/* initrd-tree/bin/
sync

#fix busybox symlinks...
for ABB in `initrd-tree/bin/busybox --list | tr '\n' ' ' | tr -d '['`
do
 [ ! -e initrd-tree/bin/${ABB} ] && ln -s busybox initrd-tree/bin/${ABB}
done
ln -s busybox 'initrd-tree/bin/['
ln -s busybox 'initrd-tree/bin/[['
sync

#populate initrd-tree with some kernel modules...
echo " populating initrd-tree with kernel modules..."
MEMXTRAMODS='tifm_core.ko tifm_7xx1.ko mmc_core.ko mmc_block.ko tifm_sd.ko led-class.ko sdhci.ko sdhci-pci.ko'
HIDXTRAMODS='hid-a4tech.ko hid-apple.ko hid-belkin.ko hid-cherry.ko hid-chicony.ko hid-cypress.ko hid-ezkey.ko hid-logitech.ko hid-microsoft.ko hid-monterey.ko hid-samsung.ko'
zNEEDEDINITRDMODS=" aufs.ko cdrom.ko fuse.ko ide-cd.ko ide-floppy.ko nls_cp437.ko nls_cp850.ko nls_cp852.ko nls_iso8859-1.ko nls_iso8859-2.ko nls_utf8.ko nls_cp850.ko sqlzma.ko squashfs.ko sr_mod.ko unionfs.ko unlzma.ko aes.ko aes_generic.ko blkcipher.ko crypto_blkcipher.ko cbc.ko cryptoloop.ko rsrc_nonstatic.ko yenta_socket.ko ehci-hcd.ko ohci-hcd.ko uhci-hcd.ko usb-storage.ko usbcore.ko usbhid.ko scsi_wait_scan.ko ssb.ko ${HIDXTRAMODS} ${DISTRO_MODULES} ${MEMXTRAMODS} floppy.ko psmouse.ko btrfs.ko libcrc32c.ko zlib_deflate.ko ext2.ko ext3.ko ext4.ko fat.ko msdos.ko vfat.ko ntfs.ko reiserfs.ko udf.ko jbd.ko mbcache.ko jbd2.ko "
NEEDEDINITRDMODS="`echo -n "$zNEEDEDINITRDMODS" | tr -s ' ' | tr ' ' '\n' | sort -u | tr '\n' ' '`"
for ONENEEDED in $NEEDEDINITRDMODS
do
 FNDONE="`find rootfs-complete/lib/modules -type f -name $ONENEEDED | sed -e 's/rootfs\-complete//'`"
 if [ "$FNDONE" != "" ];then
  echo -n "$ONENEEDED "
  FNDDIR="`dirname $FNDONE`"
  mkdir -p initrd-tree$FNDDIR
  cp -a rootfs-complete${FNDONE} initrd-tree${FNDONE}
  #gzip initrd-tree${FNDONE}
 fi
done
#we do not use kmod in initrd (as unable to compile statically)...
#the latest busybox depmod generates relative paths in modules.dep (it is a config option)
#but this breaks the older modprobe in the initrd, so use older depmod...
cp -f ../exe/${DISTRO_TARGETARCH}/depmod ./
./depmod -b initrd-tree -F ../../sandbox3/System.map $KERNVER
sync

echo " copying keyboard layouts into initrd-tree..."
cp -a -f rootfs-complete/lib/keymaps initrd-tree/lib/
cp -a -f rootfs-complete/lib/consolefonts initrd-tree/lib/

#need 32-byte id-string...
IDDATE="`date +%y%m%d%H%M%S`" #12 bytes, ex: 100911153319
IDPREFIX="`echo -n "$DISTRO_FILE_PREFIX" | cut -b 1`"
IDSTRING="${IDPREFIX}${IDDATE}ZZZZ${DISTRO_VERSION}"
#...ZZZZ reserved space for future use.
LEN1=`echo -n "$IDSTRING" | wc -c`
LEN2=`expr 32 - $LEN1`
EXTX=''
while [ $LEN2 -gt 0 ];do
 LEN2=`expr $LEN2 - 1`
 EXTX="${EXTX}X"
done
IDSTRING="${IDSTRING}${EXTX}" #32 bytes ex: w110423092024ZZZZ5.1.2XXXXXXXXXX

echo " append puppy variables to file 'DISTRO_SPECS'..."
PUPPYSFS='puppy.sfs'
ZDRVSFS='zdrv.sfs'
DEVXSFS='devx.sfs'
NEWVARIABLES="#32-byte alpha-numeric ID-string appended to vmlinuz and ${PUPPYSFS}:
DISTRO_IDSTRING='${IDSTRING}'
#Puppy default filenames...
#Note, the SFS file below is what the 'init' script in initrd.gz searches for,
#for the partition, path and actual file loaded, see PUPSFS in /etc/rc.d/PUPSTATE
DISTRO_PUPPYSFS='${PUPPYSFS}'
DISTRO_ZDRVSFS='${ZDRVSFS}'"
#151105 ...note, need DISTRO_ZDRVSFS in init script in initrd, even if not using it.
echo "$NEWVARIABLES" >> initrd-tree/DISTRO_SPECS
echo "$NEWVARIABLES" >> rootfs-complete/etc/DISTRO_SPECS
sync

#120215 language translations for init script...
INITRDTRANSFILES="`find rootfs-complete/usr/share/sss/initrd_strings -mindepth 1 -maxdepth 1 -type f -name 'initrd_strings.*'`"
if [ "$INITRDTRANSFILES" ];then
 for ATRANS in $INITRDTRANSFILES
 do
  ENDBIT="`echo -n "$ATRANS" | rev | cut -f 1 -d '.' | rev`" #ex: de (from initrd_strings.de)
  mkdir -p initrd-tree/locale/${ENDBIT}
  #only supporting translating the init script for now...
  sPTN="/^\[init\]/,/^$/p" #this is a multi-line block find expression.
  CODEBLOCK="`sed -n "$sPTN" ${ATRANS} | sed -e '/^#/d' -e '/%%/d' -e '/^$/d' -e '/^\[/d'`" #extracts just the relevant block of lines.
  [ ! "$CODEBLOCK" ] && continue #precaution.
  echo "$CODEBLOCK" > initrd-tree/locale/${ENDBIT}/init #translation file, read by /init script in initrd.
 done
fi

#BUILD_CHOICE_LANG has chosen default LANG, however get it from /etc/profile...
if [ "$DEFAULTLANG1" != "en" ];then
 echo -n "$DEFAULTLANG" > initrd-tree/PUPPYLANG
 echo
 echo "These are the available keyboard layout values (in /lib/keymaps):
azerty be-latin1 br-abnt2 br-abnt br-latin1-abnt2 br-latin1-us by cf croat cz de de-latin1 dk dvorak dvorak-l dvorak-r es et fi fr gr hu101 hu il it jp106 lt mk nl no pl pt-latin1 ro ru se sg sk-qwerty sk-qwertz slovene sv-latin1 uk us wangbe"
 echo "You don't have to choose a default, as Puppy will try and guess at bootup. Whatever, after bootup the user will have the opportunity to change it, in the QuickSetup window."
 echo -n "Enter only for 'us', else type one of the above: "
 read DEFAULTKMAP
 [ "$DEFAULTKMAP" != "" ] && [ "$DEFAULTKMAP" != "us" ] && echo -n "$DEFAULTKMAP" > initrd-tree/PUPPYKEYMAP
 [ "$DEFAULTKMAP" = "" ] && DEFAULTKMAP="us"
 echo "...ok, set to ${DEFAULTKMAP}"
fi

#200216 got this out of old 3builddistro...
if [ "$DEFAULTLANG1" != "en" ];then
 #translate early-boot splash screens...
 SPLASHFILE=""
 [ -f rootfs-complete/usr/share/sss/initrd_strings/initrd_strings.${DEFAULTLANG12} ] && SPLASHFILE="rootfs-complete/usr/share/sss/initrd_strings/initrd_strings.${DEFAULTLANG12}"
 [ ! "$SPLASHFILE" ] && [ -f rootfs-complete/usr/share/sss/initrd_strings/initrd_strings.${DEFAULTLANG1} ] && SPLASHFILE="rootfs-complete/usr/share/sss/initrd_strings/initrd_strings.${DEFAULTLANG1}"
 if [ "$SPLASHFILE" ];then
  #translate boot.msg...
  sPTN="/^\[boot.msg\]/,/^$/p" #this is a multi-line block find expression.
  CODEBLOCK="`sed -n "$sPTN" ${SPLASHFILE} | sed -e '/^#/d' -e '/%%/d' -e '/^$/d' -e '/^\[/d'`" #extracts just the relevant block of lines.
  if [ "$CODEBLOCK" ];then
   echo "$CODEBLOCK" > /tmp/3builddistro-boot-splash-translation
   sed -i -f /tmp/3builddistro-boot-splash-translation build/boot.msg
  fi
  #translate help.msg...
  sPTN="/^\[help.msg\]/,/^$/p" #this is a multi-line block find expression.
  CODEBLOCK="`sed -n "$sPTN" ${SPLASHFILE} | sed -e '/^#/d' -e '/%%/d' -e '/^$/d' -e '/^\[/d'`" #extracts just the relevant block of lines.
  if [ "$CODEBLOCK" ];then
   echo "$CODEBLOCK" > /tmp/3builddistro-boot-splash-translation
   sed -i -f /tmp/3builddistro-boot-splash-translation build/help.msg
  fi
 fi
fi

#build build/initrd.gz...
echo "Creating gzipped cpio archive initrd.gz..."
cp -f ../../boot/cpio ./
sync
cd initrd-tree
find . | ../cpio -o -H newc | gzip -9 > ../build/initrd.gz
sync
cd ..

#convert all of rootfs-complete into a sfs file...
echo "Converting folder 'rootfs-complete' to 'puppy.sfs'..."
../../support/mksquashfs4.2 rootfs-complete ./build/puppy.sfs -comp xz -processors 1
sync

echo -n "$IDSTRING" >> build/vmlinuz #32-byte id-string appended. init can determine boot partition.
echo -n "$IDSTRING" >> build/${PUPPYSFS} #
sync

#create the splash image...
echo "Creating boot splash image 'logo.16'..."
BOOTLOGO="puppy"
#VERPREFIX="$DISTRO_NAME"
VERPREFIX="EasyPup " #200203
export RGBDEF=/usr/share/X11/rgb.txt
../exe/textongif.sh ../boot/boot-dialog/${BOOTLOGO}.gif "${VERPREFIX}${RIGHTVER}" > logo.gif
../exe/${DISTRO_TARGETARCH}/gif2lss logo.gif > build/logo.16
#fix text in help file...
prefixPATTERN="s/DISTRO_FILE_PREFIX/${DISTRO_FILE_PREFIX}/"
sed -i -e "$prefixPATTERN" build/help.msg

#from create-live-cd...
 echo 'Plug in any old flash stick, 16MB or greater, right now: '
 echo -n 'Type in the drive name [sde]: '
 read OLDFLASHDRV
 [ "$OLDFLASHDRV" == "" ] && OLDFLASHDRV='sde'
 echo "...ok, it is ${OLDFLASHDRV}"
 echo -n 'Press ENTER if OK: '
 read itisok
 echo "Creating new GUID Partition Table on ${OLDFLASHDRV}..."
 echo "  zeroizing first 20MB of drive"
 dd if=/dev/zero of=/dev/${OLDFLASHDRV} bs=4M count=5 #zeroize first 20MB of drive.
 sync
 
 #an old secondary gpt can stuff things up...
 echo "  zeroizing last 20MB of drive"
 FDISKINFO="$(fdisk -l /dev/${OLDFLASHDRV} 2>/dev/null)" #no need to use gdisk.
 SIZEBYTES=`echo "$FDISKINFO" | grep '^Disk /dev' | cut -f 5 -d ' '`
 SIZEKB=`expr $SIZEBYTES \/ 1024`
 SIZEM=`expr $SIZEKB \/ 1024`
 SHORT20M=`expr $SIZEM - 20`
 SHORT5BLOCKS=`expr $SHORT20M \/ 4`
 dd if=/dev/zero of=/dev/${OLDFLASHDRV} bs=4M seek=${SHORT5BLOCKS} 2> /dev/null

 echo "  writing new gpt"
 busybox echo -e 'o\nY\nw\nY\n' | gdisk /dev/${OLDFLASHDRV}
 sync
 echo 'Writing gptmbr.bin to drive...'
 dd bs=440 conv=notrunc count=1 if=gptmbr.bin of=/dev/${OLDFLASHDRV}
 sync
 #echo "Creating FAT-32 8MB ESP first partition on ${OLDFLASHDRV}..."
 echo "Creating FAT-12 12MB ESP first partition on ${OLDFLASHDRV}..."
 busybox echo -e 'n\n1\n2048\n+12M\nef00\nw\nY\n' | gdisk /dev/${OLDFLASHDRV}
 sync
 echo 'Setting legacy boot flag on partition...'
 busybox echo -e 'x\na\n2\n\nw\nY' | gdisk /dev/${OLDFLASHDRV}
 sync
 echo "Creating fat12 filesystem..."
 #mkdosfs -F 32 -n quirky1 /dev/${OLDFLASHDRV}1 #FAT32.
 mkdosfs -F 12 -n easy1 /dev/${OLDFLASHDRV}1 #FAT12.
 sync
 echo 'Populating partition...'
 mkdir -p /mnt/${OLDFLASHDRV}1
 busybox mount -t vfat /dev/${OLDFLASHDRV}1 /mnt/${OLDFLASHDRV}1
 mkdir -p /mnt/${OLDFLASHDRV}1/EFI/BOOT
 cp -a build-${DEFAULTLANG1}/boot.msg /mnt/${OLDFLASHDRV}1/EFI/BOOT/
 cp -a build-${DEFAULTLANG1}/help.msg /mnt/${OLDFLASHDRV}1/EFI/BOOT/
 cp -a build-${DEFAULTLANG1}/initrd.gz /mnt/${OLDFLASHDRV}1/EFI/BOOT/
 cp -a build-${DEFAULTLANG1}/isolinux.cfg /mnt/${OLDFLASHDRV}1/EFI/BOOT/syslinux.cfg
 cp -a build-${DEFAULTLANG1}/logo.16 /mnt/${OLDFLASHDRV}1/EFI/BOOT/
 cp -a build-${DEFAULTLANG1}/vmlinuz /mnt/${OLDFLASHDRV}1/EFI/BOOT/
 cp ldlinux.e64 /mnt/${OLDFLASHDRV}1/EFI/BOOT/
 cp syslinux.efi /mnt/${OLDFLASHDRV}1/EFI/BOOT/BOOTX64.EFI
 sync
 #160419 syslinux not working, booting uefi iso. use gummiboot...
 gummiboot install --path=/mnt/${OLDFLASHDRV}1 --no-variables
 sync
 #wait zero seconds!...
 echo 'timeout 0
default easy' > /mnt/${OLDFLASHDRV}1/loader/loader.conf
 echo 'title EasyOS
linux /EFI/BOOT/vmlinuz
initrd /EFI/BOOT/initrd.gz
options rootwait rw' > /mnt/${OLDFLASHDRV}1/loader/entries/easy.conf
 
 sync
 busybox umount /mnt/${OLDFLASHDRV}1
 syslinux --install /dev/${OLDFLASHDRV}1 #strange, but this is still needed. absolutely essential!
 sync
 echo "Copying /dev/${OLDFLASHDRV}1 to efiboot.img..."
 dd if=/dev/${OLDFLASHDRV}1 of=efiboot.img bs=1M
 sync
 cp -f efiboot.img build-${DEFAULTLANG1}/ #190710 change mv to cp.
 echo "Finished with ${OLDFLASHDRV}, remove it now."

#more code from create-live-cd...
#190716 old bios boot, turn on framebuffer...
sed -i -e 's% rw$% rw vga=792%' ./build-${DEFAULTLANG1}/isolinux.cfg

#200128 syslinux v6 is crap, DISPLAY variable does not work, typed-in parameters ex "puppy pfix=nox", do not get passed thru.
cp -a -f ../exe/${DISTRO_TARGETARCH}/syslinux-4.07/isolinux.bin build/
rm -f build/ldlinux.c32

sync
echo -n 'Press ENTER to continue: '
read godoit

###################################
#now create the iso...
echo
echo "Now building live-CD ISO file..."
ISONAME="easypup-${DISTRO_VERSION}-${DEFAULTLANG1}.iso"
sync
#assign label "PUPPYOPTICAL" to iso...
 xorriso -as mkisofs -volid "EASYPUPOPTICAL" -o ${ISONAME} -isohybrid-mbr isohdpfx.bin \
   -c boot.cat -b isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table \
   -eltorito-alt-boot -e efiboot.img -no-emul-boot -isohybrid-gpt-basdat ./build/
sync
echo
echo "${ISONAME} has been created."

##################################
#change the disk identifier...
echo
echo "Changing the disk identifier in iso..."
echo -e "x\ni\n0x${RANDHEX8}\nr\nw" | fdisk ${ISONAME}
sync
md5sum ${ISONAME} > ${ISONAME}.md5.txt

####################################
#burn to cd...
echo
echo "Would you like to burn it to a CD or DVD? "
echo -n "ENTER only for yes, or any printable char then ENTER not to: "
read writeitnow
if [ "$writeitnow" = "" ];then
 CDR=""
 [ -f /etc/cdburnerdevice ] && CDR="/dev/`cat /etc/cdburnerdevice`"
 [ "$CDR" = "" ] && CDR='/dev/sr0'
 CDDESCR="`probedisk | grep '|optical|' | grep "$CDR" | cut -f 3 -d '|'`"
 BURNMULTI="-dao"
 echo "Please insert CD or DVD into ${CDR}
(which is described as: ${CDDESCR})
-- also be sure that it is unmounted.
NOTE1: Blank CD-R required, CD-RW not supported.
NOTE2: DVD-RW with prior content will be automatically blanked."
 echo -n "Then hit ENTER key: "
 read yayburn
 
 CDTYPE='cd'
 dvd+rw-mediainfo ${CDR} > /tmp/7buildlivecd-probe-log 2>&1
 [ $? -eq 0 ] && CDTYPE='dvd'
 if [ "$CDTYPE" == "dvd" ];then
  if [ "$(grep ' Disc status: *blank' /tmp/7buildlivecd-probe-log)" == "" ];then
   echo "Fast erasing DVD-RW on ${CDR}..."
   dvd+rw-format -force ${CDR}
   sync
  fi
  echo "Burning ${ISONAME} to DVD..."
  growisofs -speed=1 -Z ${CDR}="${ISONAME}"
 else
  echo "Burning ${ISONAME} to CD-R..."
  $CDRECORD $BURNMULTI -data -eject -v speed=4 padsize=300k dev=$CDR ${ISONAME}
 fi
 sync
 echo
 echo -n 'Close tray, then press ENTER to verify burn: ' #151205
 read verifyburn
 if [ "$verifyburn" == "" ];then
  echo "Verifying the burn..."
  sleep 15 #190716
  SUM2="$(dd if=${CDR} | head -c `stat --format=%s ${ISONAME}` | md5sum | cut -f 1 -d ' ')"
  SUM1="$(md5sum ${ISONAME} | cut -f 1 -d ' ')"
  if [ "$SUM1" == "$SUM2" ];then
   echo ' ...verified OK'
  else
   echo ' ...failed verify, BAD BURN'
  fi
 fi
 
 eject $CDR
 echo "...done"
fi

md5sum ${ISONAME} > ${ISONAME}.md5.txt
###end###
