#!/bin/bash
#131218 install quirky image file to an entire drive, with syslinux boot manager.
#131227 no longer put image-file into target.
#131227 offer ext4 without journal.
#131228 zeroize empty space in drive partitions before making an image file.
#131231 vfat is ok as working partition.
#140108 version sort.
#140111 mount ro.
#140120 work in new quirky build system.
#140212 install .sfs of deployed .usfs.xz, to /audit/reference
#140213 record date of creation of reference .sfs
#140213 merged install-quirky-to-drive.sh into 4install-quirky-to-drive
#141021 code was in wrong place.
#141102 support using syslinux 6.03.
#141103 ubuntu dash builtin echo does not support -e option.
#141103 use gdisk instead of fdisk, to boot on a win8 pc, with uefi. 141104
#150324 support boot bios and uefi. need mix of syslinux 4.07 and 6.0x, not going to work on other distros!!!
#150325 not necessary to have bios-install-of-syslinux in EFI/BOOT.
#150326 sleep at end, as drive led keeps flashing.
#150326 have removed "video=640x480" from built-in kernel, put into syslinux.cfg
#150918 revert 150326. using my 64-bit kernel with 32-bit software booting on bios laptop, this causes problem.
#151213 no longer hardcode DEV1FS. see also /sbin/initNEW, /etc/rc.d/rc.sysinit, /usr/local/install_quirky/install-quirky-to-*
#160424 set INSTALLED_MODE=full in /etc/rc.d/install.log
#170107 make f2fs optional.
#170623 remove test gdisk, as may require user input if faulty drive.
#170723 rewrite with mbr, not gpt. still has efi/esp first partition.
#171108 uefi bootup, use refind instead of syslinux.
#171109 non-english fdisk breaks script. 
#171124 fix refind. 171125 fix.

if [ -d rootfs-skeleton -a -f 3builddistro ];then #140213
 #running in quirky build system.
 if [ ! -d sandbox3 ];then
  echo "You need to run 3builddistro first, to build sandbox3/*.usfs.xz"
  exit
 fi
 #171125...
. ./WOOFMERGEVARS #171125
 cp -f ./DISTRO_SPECS /tmp/DISTRO_SPECSCOPY1
 if [ "$WOOF_VARIANT" == "easy" ];then #see file WOOFMERGEVARS
  sed -i '/#QUIRKY/d' /tmp/DISTRO_SPECSCOPY1
 else
  sed -i '/#EASY/d' /tmp/DISTRO_SPECSCOPY1
 fi
. /tmp/DISTRO_SPECSCOPY1
 RUNNING="build"
 cd sandbox3
else
. /etc/rc.d/WOOFMERGEVARS #171125
 RUNNING="user"
fi


###preamble###
echo
echo "This script will install Quirky to an entire drive, and make it bootable with the Syslinux boot manager, for any desktop PC or laptop."
echo "That is, a computer with x86 CPU, with any version of Windows on it, from Windows XP to 7 with BIOS firmware, to a modern computer running Windows 8.x, with UEFI firmware."
echo "The intention is to install to pluggable memory drives such as USB Flash sticks and SD-cards, or even a USB SSD drive. The entire drive is erased, so take off any files that you want to keep."
echo "The script will ask questions at each step, and will offer a choice of drives to install to, but of course it comes down to you to make an intelligent choice and not erase your PCs internal hard drive!"
echo "This script should work when running any Linux distribution, however, it works best when running a Puppy Linux or Puppy Linux-derivative, as Puppy has, in my opinion, many superior utilities. However, this script will check for existence or otherwise of those utilities and downgrade appropriately, or abort if a missing utility is essential."
echo
echo -n "Press ENTER key to continue (CTRL-C to abort): "
read goforit

###check sanity###
if [ "`whoami`" != "root" ];then
 echo
 echo "Sorry, you need to run this script as root (administrator). Aborting."
 exit
fi
if [ $1 ];then
 echo
 echo "Nothing required on commandline, this script will ask."
fi

#170107 removed  mkfs.f2fs
FLGx=0
for AUTILITY in cp dd fdisk mkdosfs mkfs.ext2 mkfs.ext4 mount sed stat syslinux xz
do
 if [ "`which ${AUTILITY}`" = "" ];then
  echo
  echo "Sorry, the '${AUTILITY}' utility is missing. Aborting."
  case ${AUTILITY} in
   mkfs.f2fs) echo "...it looks like the 'f2fs-tools' package needs to be installed" ;;
   syslinux)  echo "...it looks like the 'syslinux' package (and in some cases 'mtools') missing" ;;
   mkfs.ext2) echo "...it looks like the 'e2fsprogs' package needs to be installed" ;;
   mkdosfs)   echo "...it looks like the 'dosfstools' package needs to be installed" ;;
  esac
  FLGx=1
 fi
done
[ $FLGx -eq 1 ] && exit
IMGLIST="$(ls -1 ./ | grep '\.usfs\.xz$' | sort --key=2 --field-separator='-' --version-sort)" #140108 version sort. 140213
if [ "$IMGLIST" = "" ];then
 echo "The Quirky compressed image file should have been downloaded"
 echo "to the same folder in which you are running this script."
 echo "It will be named something like '*.usfs.xz'"
 echo "Please download it from distro.ibiblio.org/quirky/quirky6/${DISTRO_TARGETARCH}"
 exit
fi
#need linux f.s.... 131231 no, vfat ok... 140213 $0 is name of script...
touch tempfile1 #140213 no, create a file.
WKGFS="$(stat -f tempfile1 | grep -o 'Type: .*' | grep -E 'ext2|ext3|ext4|reiserfs|f2fs')"
rm -f tempfile1
#if [ "$WKGFS" = "" ];then
# echo
# echo "Sorry, but you must be running this script in a partition with a Linux
#filesystem. The 'stat' utility was used to check for ext2, ext3, ext4, reiserfs
#or f2fs filesystem, however some versions of stat do not recognise f2fs.
#If you are running in a f2fs filesystem, or some other Linux filesystem
#(but definitely NOT a ntfs, msdos or vfat f.s.!!!), then press any printable
#character on the keyboard, then ENTER key, to continue."
# echo -n "To abort, press ENTER key only: "
# read tostop
# [ "$tostop" = "" ] && exit
#fi

#150324 need mix of syslinux 4.07 and 6.0x, not going to work on other distros!!!
##141104
#SYSOK=''
#SYSOK="$(syslinux -v 2>&1 | grep -i '^syslinux 6\.0[3-9]')"
#[ "$SYSOK" == "" ] && SYSOK="$(syslinux -v 2>&1 | grep -i '^syslinux 6\.[1-9]')"
#[ "$SYSOK" == "" ] && SYSOK="$(syslinux -v 2>&1 | grep -i '^syslinux [7-9]')"
#if [ "$SYSOK" == "" ];then
# echo
# echo 'Sorry, but you need to have Syslinux version 6.03 or later installed.'
# exit
#fi

#171108
if [ ! -d /usr/share/refind/quirky/ ];then
 echo
 echo "Sorry, refind must be installed. The PET is available here:"
 echo "http://distro.ibiblio.org/quirky/quirky6/amd64/packages/pet_packages-pyro/refind-20171008-32bit-64bit-x86.pet"
 exit
fi

SLPATH=""
[ -f /usr/lib/syslinux/mbr.bin ] && SLPATH="/usr/lib/syslinux"
[ "$SLPATH" = "" ] && [ -f /usr/lib/SYSLINUX/mbr.bin ] && SLPATH="/usr/lib/SYSLINUX" #141102 ubuntu utopic unicorn.
[ "$SLPATH" = "" ] && [ -f /usr/share/syslinux/mbr.bin ] && SLPATH="/usr/share/syslinux"
if [ "$SLPATH" = "" ];then
 echo
 echo "Sorry, cannot find file 'mbr.bin'. Looked in /usr/lib/syslinux. /usr/lib/SYSLINUX,
/usr/share/syslinux. You have an abnormal installation of Syslinux. Aborting"
 exit
fi
MBRBIN="${SLPATH}/mbr.bin"

if [ ! -d ${SLPATH}/efi64 ];then #150324
 echo
 echo "Sorry, syslinux version 6.x is required. Or at least these folders from 6.x:
 ${SLPATH}/efi64
 ${SLPATH}/efi32"
 exit
fi


###choose .usfs.xz file###
echo
CNT=1
echo -n "" > /tmp/quirkyimgs
for AIMG in `echo -n "$IMGLIST" | tr '\n' ' '`
do
 echo "${CNT} ${AIMG}" >> /tmp/quirkyimgs
 CNT=`expr $CNT + 1`
done
cat /tmp/quirkyimgs
echo
echo -n "Type a number from the left column: "
read numimg
[ "$numimg" = "" ] && exit
IMGFILEXZ="$(cat /tmp/quirkyimgs | head -n ${numimg} | tail -n 1 | cut -f 2 -d ' ')"
echo "...ok, have chosen ${IMGFILEXZ}"
if [ ! -f $IMGFILEXZ ];then
 echo "sorry, file ${IMGFILEXZ} does not exist"
 exit
fi
EXT="$(echo -n $IMGFILEXZ | rev | cut -f 1 -d '.' | rev)"
if [ "$EXT" != "xz" ];then
 echo "sorry, file ${IMGFILEXZ} is not xz-compressed"
 exit
fi
echo
echo "Testing integrity of compressed file, please wait..."
xz --test $IMGFILEXZ
if [ $? -ne 0 ];then
 echo
 echo "Sorry, file appears to be corrupted. Try downloading again."
 exit
fi

if [ "$RUNNING" = "build" ];then #140213 running in quirky build system.
 FILEPREFIX="$DISTRO_FILE_PREFIX"
else
 FILEPREFIX="$(echo -n "$IMGFILEXZ" | cut -f 1 -d '-')" #140130
fi

###choose target drive###
echo
echo "Plug in a USB Flash drive, 4GB size, or greater, right now."
echo "Also, please be sure that it is unmounted."
echo "Note, 4GB is sufficient, however for a satisfactory ongoing experience
using Quirky, it is recommended to use a 8GB or greater drive."
echo
echo "WARNING: Many Linux distros will auto-mount a drive when it is plugged
         in. You will have to unmount it BEFORE CONTINUING!!!
         (if you are unsure about this, don't worry, the script will
          check again later, after you have chosen the drive)"
echo
echo -n "Have you plugged in the drive? Then press ENTER key: "
read gogogo
if [ "`which probedisk`" != "" ];then
 echo
 echo "These are all of the drives found in your PC:"
 INFODRIVES="$(probedisk -m | sed -e 's%/dev/%%')"
 echo "$INFODRIVES"
 ALLDRIVES="$(echo "$INFODRIVES" | cut -f 1 -d '|' | tr '\n' ' ')"
else
 echo
 echo "As you are not using a Puppy-derivative, you do not have the excellent
'probedisk' utility, which reports all drives. So, falling back to giving you
a simple list:"
 echo
 echo "These are all of the drives found in your PC:"
 ALLDRIVES="$(ls -1 /sys/block | grep -E 'sd|hd|mm' | tr '\n' ' ')"
 echo "$ALLDRIVES"
fi
echo
echo "Choose the drive to install to..."
CNT=1
echo -n "" > /tmp/quirkytargetdrives
for AIMG in $ALLDRIVES
do
 echo "${CNT} ${AIMG}" >> /tmp/quirkytargetdrives
 CNT=`expr $CNT + 1`
done
cat /tmp/quirkytargetdrives
echo
echo -n "Type a number from left column: "
read numimg
[ "$numimg" = "" ] && exit
TARGETDRIVE="$(cat /tmp/quirkytargetdrives | head -n ${numimg} | tail -n 1 | cut -f 2 -d ' ')" #ex: sdb
echo "...ok, have chosen ${TARGETDRIVE}"
[ "$TARGETDRIVE" = "" ] && exit #precaution
CHECKDRIVE="$(echo "$ALLDRIVES" | tr ' ' '\n' | grep "${TARGETDRIVE}"'$')"
if [ ! "$CHECKDRIVE" ];then
 echo
 echo "Error making choice, aborting."
 exit
fi
if [ "$TARGETDRIVE" = "sda" ];then
 echo
 echo "Are you absolutely sure? ${TARGETDRIVE} is usually the main hard drive."
 echo "The operation will completely wipe ${TARGETDRIVE}."
 echo -n "ENTER only to continue (CTRL-C to abort): "
 read aazzxx
fi

###write to target drive###
TRYAGAIN=""
tPTN="^/dev/${TARGETDRIVE}"
MNTDPART="$(mount | grep "$tPTN" | cut -f 1 -d ' ' | sed -e 's%/dev/%%' | tr '\n' ',')"
echo
PP=''
[ "`echo -n "TARGETDRIVE" | grep 'mm'`" != "" ] && PP='p'
while [ "$MNTDPART" != "" -a "$MNTDPART" != "," ];do
 ${TRYAGAIN}
 echo "Partition ${MNTDPART} in drive ${TARGETDRIVE} is mounted."
 echo "Unmount it right now. If you are running one of those Linux distros where
it is not obvious how to unmount a drive, try running this in a terminal:
# umount /dev/${TARGETDRIVE}${PP}1
# umount /dev/${TARGETDRIVE}${PP}2
Note, the 'mount' command will verify whether unmounted."
 echo -n "Unmount it right now, then press ENTER (CTRL-C to abort): "
 read goforit
 [ "$goforit" != "" ] && exit
 TRYAGAIN="
Sorry, still mounted, try again..."
 MNTDPART="$(mount | grep "$tPTN" | cut -f 1 -d ' ' | sed -e 's%/dev/%%' | tr '\n' ',')"
done
echo
IMGFILE="$(basename ${IMGFILEXZ} .xz)"
echo "Uncompressing ${IMGFILEXZ} to ${IMGFILE}..."
rm -f ${IMGFILE} 2>/dev/null
xz --decompress --stdout ${IMGFILEXZ} > ${IMGFILE}
sync

echo
echo -n "Final sanity check: '${TARGETDRIVE}' is correct? (ENTER if OK, CTRL-C abort): "
read abcdef

###preliminary###
echo
echo "Some preliminaries on the ${TARGETDRIVE}..."
FDISKINFO="$(LANG=C fdisk -l /dev/${TARGETDRIVE} 2>/dev/null)" #141104 leave as fdisk. 171109
SIZEBYTES=`echo "$FDISKINFO" | grep '^Disk /dev' | cut -f 5 -d ' '` #141104
SIZEKB=`expr $SIZEBYTES \/ 1024`
SIZEM=`expr $SIZEKB \/ 1024`
SHORT20M=`expr $SIZEM - 20`
SHORT5BLOCKS=`expr $SHORT20M \/ 4`
echo "Size of drive=${SIZEM}MB"

echo
echo "Would you like to zeroize the entire drive before installation?"
echo "You should answer 'yes' to this if you choose to make a image-file
of the drive immediately after installation (this script will later offer
to do that) -- an image-file is useful for writing to other drives, or
to give to others. Zeroizing beforehand will make the image-file smaller."
echo "NOTE: zeroizing may take over 30 minutes, depending on size of drive."
echo "NOTE: Do not do this with a USB1 interface or via a USB-hub (too slow)."
echo "NOTE: Unless you really need to do this, recommend press ENTER to decline."
echo -n "ENTER only to decline, (any other char to zeroize drive): "
read zerome
if [ "$zerome" != "" ];then
 echo
 echo "Zeroizing entire drive, this will take awhile..."
 QTRM=`expr $SIZEM \/ 4`
 dd if=/dev/zero of=/dev/${TARGETDRIVE} bs=4M #no, make sure writes right to end. count=${QTRM}
 sync
else
 echo
 echo "It is necessary to zeroize a small part of the drive, the beginning
and the end. The end, because if the drive previously had a GPT secondary
partition on it, this has to be wiped."
 echo "Zeroizing only first 20MB and last 20MB of drive..."
 dd if=/dev/zero of=/dev/${TARGETDRIVE} bs=4M count=5
 sync
 dd if=/dev/zero of=/dev/${TARGETDRIVE} bs=4M seek=${SHORT5BLOCKS} 2> /dev/null
 #...reason is if drive has previously had a GPT on it, the secondary-GPT at end of drive confuses fdisk.
 sync
fi
echo "...done"

PARTNUM1="1"
PARTNUM2="2"
if [ "`echo -n "$TARGETDRIVE" | grep 'mm'`" != "" ];then
 PARTNUM1="p1"
 PARTNUM2="p2"
fi

###create 512MB FAT-32 first partition###
echo
echo "Creating 512MB FAT-32 first partition..."

echo "Creating dos partition table in /dev/${TARGETDRIVE}"
echo "Creating dos partition table in /dev/${TARGETDRIVE}" > /tmp/installquirkyfdisk.log
#o=create new dos partition table... 141103...
busybox echo -e 'o\nw\n' | fdisk /dev/${TARGETDRIVE} >> /tmp/installquirkyfdisk.log 2>&1
#write mbr...
sync #150104
echo "Writing ${MBRBIN}"
echo "Writing ${MBRBIN}" >> /tmp/installquirkyfdisk.log
dd bs=440 conv=notrunc count=1 if=${MBRBIN} of=/dev/${TARGETDRIVE}
sync #150104

#create a partition... 2048=first sector, size 512MB...
busybox echo -e 'n\np\n1\n2048\n+512M\nw\n' | fdisk /dev/${TARGETDRIVE} >> /tmp/installquirkyfdisk.log 2>&1
#set partition-id to efi...
busybox echo -e 't\nef\nw' | fdisk /dev/${TARGETDRIVE} >> /tmp/installquirkyfdisk.log 2>&1 #will default to 1st partition, as that all exists.
#set the boot flag...
busybox echo -e 'a\nw' | fdisk /dev/${TARGETDRIVE} >> /tmp/installquirkyfdisk.log 2>&1 #defaults to partition 1, as that all exists.
sync

#create a fat32 f.s....
echo "Creating fat32 filesystem..."
mkdosfs -F 32 -n quirky1 /dev/${TARGETDRIVE}${PARTNUM1}
sync


echo
echo "Installing syslinux in 1st partition, ${TARGETDRIVE}${PARTNUM1}..."
#syslinux efi files, for uefi booting, have to be copied in:
mkdir -p /mnt/${TARGETDRIVE}${PARTNUM1}
busybox mount -t vfat /dev/${TARGETDRIVE}${PARTNUM1} /mnt/${TARGETDRIVE}${PARTNUM1}
mkdir -p /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT

#171108 now using refind...
##cp ${SLPATH}/efi32/ldlinux.e32 /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/
##cp ${SLPATH}/efi32/syslinux.efi /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/BOOTIA32.EFI
#cp ${SLPATH}/efi64/ldlinux.e64 /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/
#cp ${SLPATH}/efi64/syslinux.efi /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/BOOTX64.EFI
if [ "$WOOF_VARIANT" == "easy" ];then #see file WOOFMERGEVARS
 cp -a /usr/share/refind/easy/refind_ia32.efi /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/BOOTIA32.EFI
 cp -a /usr/share/refind/easy/refind_x64.efi /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/BOOTX64.EFI
else
 cp -a /usr/share/refind/quirky/refind_ia32.efi /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/BOOTIA32.EFI
 cp -a /usr/share/refind/quirky/refind_x64.efi /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/BOOTX64.EFI
fi

sync
busybox umount /mnt/${TARGETDRIVE}${PARTNUM1}
#despite where we are installing, this is for bios booting: 150325 no, put into / ...
#syslinux --directory EFI/BOOT --install /dev/${TARGETDRIVE}${PARTNUM1} #need --install for 4.05+.
syslinux --install /dev/${TARGETDRIVE}${PARTNUM1}
sync

###create 2nd partition###
#calculate a suitable size for 2nd partition...
#this free space at end is to allow us to create a flash-drive-image from the drive, for others to use. other drives may have slightly different actual sizes.
SPACEM=10240; NOMINALG='256'
if [ $SIZEM -lt 131072 ];then
 SPACEM=5120
 NOMINALG='128'
fi
if [ $SIZEM -lt 65536 ];then
 SPACEM=2560 #under 64GB
 NOMINALG='64'
fi
if [ $SIZEM -lt 32768 ];then
 SPACEM=1280 #under 32GB
 NOMINALG='32'
fi
if [ $SIZEM -lt 16384 ];then
 SPACEM=640 #under 16GB
 NOMINALG='16'
fi
if [ $SIZEM -lt 8192 ];then
 SPACEM=320 #under 8GB ex: an "8GB" drive will be here
 NOMINALG='8'
fi
if [ $SIZEM -lt 4096 ];then
 SPACEM=160 #under 4GB
 NOMINALG='4'
fi
if [ $SIZEM -lt 2048 ];then
 SPACEM=80 #under 2GB
 NOMINALG='2'
fi
if [ $SIZEM -lt 1500 ];then
 echo
 echo "Error, ${SIZEM}MB drive is too small, aborting."
 exit
fi

SMALLER0M=`expr $SIZEM - $SPACEM` #some empty space at end of drive.
SMALLERM=`expr $SMALLER0M - 520` #take off size of 1st partition plus gaps 512+8
ONE8TH=`expr $SMALLERM \/ 8`
FINALM=`expr $ONE8TH \* 8`
#create a partition, 49152=start sector, +${FINALM}M size
#141104 1st partition now 512MB (was 16) (starts sector 2048 (1MB), next free is sector 1050624),
#       leave 7MB gap, second partition starts sector 1064960...
#       8300 (gdisk), 83 (fdisk), is Linux filesystem...
echo
echo "Creating 2nd partition, size ${FINALM}MB..."
busybox echo -e "n\np\n2\n1064960\n+${FINALM}M\nw\n" | fdisk /dev/${TARGETDRIVE} >> /tmp/installquirkyfdisk.log 2>&1
#set partition-id to Linux...
busybox echo -e 't\n2\n83\nw' | fdisk /dev/${TARGETDRIVE} >> /tmp/installquirkyfdisk.log 2>&1
sync

echo
echo "Please choose whether to create a ext2, ext4, or ext4-without-journal filesystem in the
second partition."
echo
echo '1 ext4-without-journal (best choice for Flash)
2 ext2
3 ext4 with journal (recommended for hard drives)' > /tmp/quirky2ndfss
cat /tmp/quirky2ndfss
echo
echo -n "Type a number from left column: "
read numimg
[ "$numimg" = "" ] && numimg="1"
TARGETFS="$(cat /tmp/quirky2ndfss | head -n ${numimg} | tail -n 1 | cut -f 2 -d ' ')" #ex: f2fs
[ "$TARGETFS" = "" ] && TARGETFS="ext4-without-journal"
echo "...ok, have chosen ${TARGETFS}"
echo
echo "Creating ${TARGETFS} in 2nd partition..."
case $TARGETFS in
 ext2) mkfs.ext2 -m 0 -L quirky2 /dev/${TARGETDRIVE}${PARTNUM2} ;;
 ext4) mkfs.ext4 -m 0 -L quirky2 /dev/${TARGETDRIVE}${PARTNUM2} ;;
 ext4-without-journal)
  mke2fs -t ext4 -O ^has_journal -L quirky2 -m 0 -b 4096 /dev/${TARGETDRIVE}${PARTNUM2}
  TARGETFS="ext4"
 ;;
 *)    mkfs.f2fs -l quirky2 /dev/${TARGETDRIVE}${PARTNUM2} ;;
esac
sync
echo "...done"

###populate target drive###
mkdir -p mntpt
mount -t squashfs -o loop,ro ${IMGFILE} mntpt #140111 ro
if [ $? -ne 0 ];then
 echo
 echo "Error mounting ${IMGFILE} on mntpt. Aborting"
 rm -f ${IMGFILE}
 exit
fi
TARGETVERSION="$(grep '^DISTRO_VERSION=' mntpt/etc/DISTRO_SPECS | cut -f 2 -d '=' | cut -f 2 -d "'" | cut -f 1 -d ' ')" #'ex: 6.0.1

#150324
##140212
#echo
#echo "Creating ${FILEPREFIX}-${TARGETVERSION}.sfs"
#echo "This will be copied to /audit/reference in the target drive, and
#may be used in future for recovery purposes. Creating now..."
#rm -f ${FILEPREFIX}-${TARGETVERSION}.sfs 2>/dev/null
#mksquashfs mntpt ${FILEPREFIX}-${TARGETVERSION}.sfs
#sync

echo
echo "Populating 1st partition, ${TARGETDRIVE}${PARTNUM1}..."
#have to run this again, as DISKUUID (NT disk signature) has changed after mbr installed...
FDISKINFO="$(LANG=C fdisk -l /dev/${TARGETDRIVE} 2>/dev/null)" #171109
DISKUUID="$(echo "$FDISKINFO" | grep '^Disk identifier:' | tr -s ' ' | cut -f 3 -d ' ' | sed -e 's%^0x%%')" #ex: 2669a57d

mkdir -p /mnt/${TARGETDRIVE}${PARTNUM1}
mount -t vfat /dev/${TARGETDRIVE}${PARTNUM1} /mnt/${TARGETDRIVE}${PARTNUM1}
if [ $? -ne 0 ];then
 echo
 echo "Error, failed to mount first partition, ${TARGETDRIVE}${PARTNUM1}. Aborting"
 exit
fi

#150324 now copy to EFI/BOOT... 150325 revert...
#cp -a mntpt/boot/syslinux/* /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/
cp -a mntpt/boot/syslinux/* /mnt/${TARGETDRIVE}${PARTNUM1}/
echo "PARTUUID of 2nd partition written to syslinux.cfg in 1st partition."
PTN1="s%INSERTPARTID%${DISKUUID}-02%"
sed -i -e "${PTN1}"  /mnt/${TARGETDRIVE}${PARTNUM1}/syslinux.cfg

#150326 have removed "video=640x480" from built-in kernel, do it here (but not for efi):
#150918 using my 64-bit kernel with 32-bit software booting on bios laptop, this causes problem, remove...
#sed -i -e 's%^append %append video=640x480 %' /mnt/${TARGETDRIVE}${PARTNUM1}/syslinux.cfg
sync
#cp -a mntpt/boot/vmlinuz /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/
cp -a mntpt/boot/vmlinuz /mnt/${TARGETDRIVE}${PARTNUM1}/

#171108 now using refind
##150325 copy syslinux.cfg for efi boot:
#cp -a mntpt/boot/syslinux/* /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/
#sed -i -e "${PTN1}"  /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/syslinux.cfg
#sed -i -e 's% vmlinuz% ../../vmlinuz%' /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/syslinux.cfg
if [ "$WOOF_VARIANT" == "easy" ];then #see file WOOFMERGEVARS
 cp -a /usr/share/refind/easy/refind.conf /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/
 PTNs="s%Easy OS 0\.6%${DISTRO_NAME} ${DISTRO_VERSION}%"
 sed -i -e "$PTNs" /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/refind.conf
else
 cp -a /usr/share/refind/quirky/refind.conf /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/
 sed -i '/ initrd /d' /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/refind.conf
 PTNr="s%^ options .*% options \"root=PARTUUID=${DISKUUID}-02 rootwait rw\"%"
 sed -i -e "$PTNr" /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/refind.conf
 PTNs="s%Quirky Linux%${DISTRO_NAME} ${DISTRO_VERSION}%"
 sed -i -e "$PTNs" /mnt/${TARGETDRIVE}${PARTNUM1}/EFI/BOOT/refind.conf
fi

sync
umount /mnt/${TARGETDRIVE}${PARTNUM1}
echo "...done"

echo
echo "Populating 2nd partition, ${TARGETDRIVE}${PARTNUM2}..."
mkdir -p /mnt/${TARGETDRIVE}${PARTNUM2}
mount -t ${TARGETFS} /dev/${TARGETDRIVE}${PARTNUM2} /mnt/${TARGETDRIVE}${PARTNUM2}
if [ $? -ne 0 ];then
 echo
 echo "Error, failed to mount second partition, ${TARGETDRIVE}${PARTNUM2}. Aborting"
 exit
fi
cp -a mntpt/* /mnt/${TARGETDRIVE}${PARTNUM2}/
sync
umount mntpt

#160424 record installed mode. maybe used by /usr/sbin/savesession, installquirky...
echo 'INSTALLED_MODE=full' > /mnt/${TARGETDRIVE}${PARTNUM2}/etc/rc.d/install.log #possible values: livecd, frugal, full

#save img file for our audit trail... 131227 no longer doing this...
#echo "Copying ${IMGFILE} to /mnt/${TARGETDRIVE}${PARTNUM2}/audit/, for audit-trail..."
mkdir -p /mnt/${TARGETDRIVE}${PARTNUM2}/audit
#cp -a ${IMGFILE} /mnt/${TARGETDRIVE}${PARTNUM2}/audit/
sync
umount /mnt/${TARGETDRIVE}${PARTNUM2}
rm -f ${IMGFILE}
#echo "...done"

#150324 somehow won't boot, for amd64 install. reinstalling mbr.bin here fixes it...
sync
dd bs=440 conv=notrunc count=1 if=${MBRBIN} of=/dev/${TARGETDRIVE}
sync

#have a daemon, send this uevent to it, then /usr/local/pup_event/frontend_change will be called...
echo change > /sys/block/${TARGETDRIVE}/uevent
sleep 5
echo
echo "That's it, ${TARGETDRIVE} is now ready to boot from!"
echo "But, please leave it plugged in for now."

if [ "$zerome" != "" ];then #140212 zeroized entire drive.
 echo
 echo "If you want to create a copy of the drive, as an image file, for deployment
to other users, the total size is 1M + 512M + 7M + ${FINALM}"
 echo -n "which is: "
 TOTALM=`expr 520 + $FINALM`
 echo "${TOTALM}MB"
 echo "An image can be created like this:"
 TOTAL4THM=`expr $TOTALM \/ 4`
 echo "# dd if=/dev/${TARGETDRIVE} bs=4M count=${TOTAL4THM} | xz --compress --stdout - > ${FILEPREFIX}-${TARGETVERSION}-${NOMINALG}gb.img.xz"
 echo
 echo "If you do not want to do this, just press ENTER key,"
 echo -n "otherwise, press any char then ENTER: "
 read goforit
 if [ "$goforit" != "" ];then
  echo
  echo "Creating compressed image file of drive..."
  dd if=/dev/${TARGETDRIVE} bs=4M count=${TOTAL4THM} | xz --compress --stdout - > ${FILEPREFIX}-${TARGETVERSION}-${NOMINALG}gb.img.xz
  sync
  sleep 5
  echo "...${FILEPREFIX}-${TARGETVERSION}-${NOMINALG}GB.img.xz created!"
  echo "That's it. You can instruct users to write the image to a drive, of nominal
size ${NOMINALG}GB or bigger, like this:"
  echo "# xz --decompress --stdout ${FILEPREFIX}-${TARGETVERSION}-${NOMINALG}gb.img.xz | dd of=/dev/<drive> bs=4M conv=fsync"
 fi
else #150326
 sleep 5 #drive led keeps flashing for awhile.
fi

#150324
##140212
#echo
#echo "Now copying ${FILEPREFIX}-${TARGETVERSION}.sfs to /audit/reference
#in partition ${TARGETDRIVE}${PARTNUM2}, please wait..."
#mount -t ${TARGETFS} /dev/${TARGETDRIVE}${PARTNUM2} /mnt/${TARGETDRIVE}${PARTNUM2}
#cp -a -f ${FILEPREFIX}-${TARGETVERSION}.sfs /mnt/${TARGETDRIVE}${PARTNUM2}/audit/reference/
#DATE="$(date +%Y%m%d%H%M)" #140213 141021
#echo "${DATE} ${FILEPREFIX}-${TARGETVERSION}.sfs" > /mnt/${TARGETDRIVE}${PARTNUM2}/audit/reference/dates #140213 141021
sync
#umount /mnt/${TARGETDRIVE}${PARTNUM2}
#rm -f ${FILEPREFIX}-${TARGETVERSION}.sfs

echo
echo "Done, all finished! You may unplug drive ${TARGETDRIVE}"

###END###
