#!/bin/sh
#(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.

#TODO: 64-bit welcome1stboot

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

#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 ../sandbox3/rootfs-complete/lib/modules -maxdepth 1 -type d -name '[23]*' | head -n 1 | rev | cut -f 1 -d '/' | rev)"

DOTCONFIG="$(find ../sandbox3/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"

echo
echo 'Please wait, copying ../sandbox3/rootfs-complete...'
rm -rf sandbox4 2>/dev/null
mkdir sandbox4
cd sandbox4
cp -a ../../sandbox3/rootfs-complete ./
sync

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

#change "Quirky" to "Puppy", wherever...
cp -a -f ../exe/${DISTRO_TARGETARCH}/welcome1stboot rootfs-complete/usr/sbin/
cp -a -f ../DISTRO_SPECS rootfs-complete/etc/
rm -f rootfs-complete/usr/share/applications/quirky-installer.desktop
rm -f rootfs-complete/usr/share/applications/snapshot-manager.desktop
rm -f rootfs-complete/usr/share/applications/upgrade-manager.desktop
for AFILE in etc/issue
do
 sed -i -e 's%Quirky%Puppy%' rootfs-complete/${AFILE}
done

#create iso build folder...
echo "Creating 'build' folder..."
mkdir build
cp -a ../../sandbox3/build/* build/
#puppy files...
cp -a -f ../boot/boot-dialog/isolinux.cfg build/
cp -a -f ../boot/boot-dialog/*.msg build/
rm -f build/syslinux.cfg
if [ -f /usr/lib/syslinux/isolinux.bin ];then #150211
 cp -f /usr/lib/syslinux/isolinux.bin build/
else
 cp -f /usr/share/syslinux/isolinux.bin build/
fi

#build initrd.cpio...
echo
echo "Preparing to create initrd.gz cpio archive..."
cp -a ../../boot/initrd-tree ./
sync
#puppy files...
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
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
 echo -n "$ONENEEDED "
 FNDONE="`find rootfs-complete/lib/modules -type f -name $ONENEEDED | sed -e 's/rootfs\-complete//'`"
 if [ "$FNDONE" != "" ];then
  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 ../../boot/depmod ./
./depmod -b initrd-tree -F ../../sandbox3/System.map $KERNELVER
sync

echo " copying keyboard layouts into intrd-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...
DEFAULTLANG="$(grep '^LANG=' rootfs-complete/etc/profile | cut -f 2 -d '=')"
 DEFAULTLANG1="${DEFAULTLANG%_*}"
 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

#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"
export RGBDEF=/usr/share/X11/rgb.txt
../../boot/boot-dialog/textongif.sh ../../boot/boot-dialog/${BOOTLOGO}.gif "${VERPREFIX}${RIGHTVER}" > logo.gif
../../boot/boot-dialog/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

echo
echo "Now building live-CD ISO file..."
ISONAME="puppy-${DISTRO_FILE_PREFIX}-${DISTRO_VERSION}.iso"
rm -f puppy-${DISTRO_FILE_PREFIX}-${DISTRO_VERSION}.iso 2> /dev/null
$MKISOFS -D -R -o ${ISONAME} -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table ./build/
sync
md5sum ${ISONAME} > ${ISONAME}.md5.txt

echo
echo "${ISONAME} has been created."
echo
echo "Would you like to burn it to a CD? "
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 '|'`"
 echo -n 'Type "y" for multisession, else just ENTER: '
 read BURNMULTI
 if [ "$BURNMULTI" = "y" ];then
  BURNMULTI="-multi -tao -pad"
 else
  BURNMULTI="-dao"
 fi
 echo "Please insert blank CD into $CDR
(which is described as: ${CDDESCR})
-- also be sure that it is unmounted."
 echo -n "Then hit ENTER key: "
 read yayburn
# $CDRECORD $BURNMULTI -data -eject -v speed=4 padsize=300k dev=ATAPI:$CDR ${DISTRO_FILE_PREFIX}-${DISTRO_VERSION}${SCSIFLAG}.iso
 $CDRECORD $BURNMULTI -data -eject -v speed=4 padsize=300k dev=$CDR ${ISONAME}
 sync
 eject $CDR
 echo "...done"
fi

###END###
