#!/bin/bash
#(c) Copyright Barry Kauler July 2017, barryk.org
#Licence GPL3 (refer: /usr/share/doc/legal).
#170722 based on second half of previous install-quirky-to-partition
#170727 path fix.
#171109 non-english fdisk breaks script.
#180408 support nvme drives.

#note, exported from installquirky: RXVTEXE ATADRIVES Qarch Qfw. ex: Qarch=amd64 Qfw=UEFI
export TEXTDOMAIN=installquirky
export OUTPUT_CHARSET=UTF-8
[ ! "$RXVTEXE" ] && RXVTEXE='urxvt'

INSTMODE="partition"
INSTMODEtr="$(gettext 'partition')"
REQDSPACE=1200

###source files###
if [ -e ./get-quirky-src ];then #170727
. ./get-quirky-src
else
 if [ -e /usr/local/install_quirky/get-quirky-src ];then
. /usr/local/install_quirky/get-quirky-src
 fi
fi
#...exit with MNTPTsrc path to quirky source files vmlinuz, initrd.q, q.sfs
#...also current dir set to $TMPWKG_MNTPT

###choose target partition###
M_00="$(gettext 'Quirky will be downloaded and installed to a partition on a hard drive.')"
M_01="$(gettext 'Any kind of hard drive is acceptable, including conventional magnetic platter or SSD (Solid State Disk). Removable drives, such as USB drives, are also acceptable. The partition must ALREADY have a filesystem. It must be a Linux filesystem, ext2, ext3, or ext4 is recommended.')"
M_02="$(gettext 'The partition will need to be at least 8GB in size, and all of the partition will be erased.')"
M_03="$(gettext 'If you do not have a suitable available partition, abort this script!')"

PITEMS=""
ALLPARTS="$(${PRE}probepart -k | ${PRE}busybox grep -E 'ext2|ext3|ext4|f2fs|reiserfs|btrfs|minix|xfs' | ${PRE}busybox sed -e 's%^/dev/%%' | ${PRE}busybox tr '\n' ' ')"
for APART in $ALLPARTS
do
 ADEV="$(${PRE}busybox echo -n "$APART" | ${PRE}busybox cut -f 1 -d '|')"
 AFS="$(${PRE}busybox echo -n "$APART" | ${PRE}busybox cut -f 2 -d '|')"
 ASIZEK="$(${PRE}busybox echo -n "$APART" | ${PRE}busybox cut -f 3 -d '|')"
 if [ $ASIZEK -gt 1048576 ];then #1024*1024
  xONESIZE="`LANG=C ${PRE}busybox dc $ASIZEK 1048576 \/ p`"
  ONESIZE="`LANG=C ${PRE}busybox printf "%.1f" $xONESIZE`G"
 else
  if [ $ASIZEK -gt 99 ];then
   ONESIZE="`${PRE}busybox expr $ASIZEK \/ 1024`M"
  else
   xONESIZE="`LANG=C ${PRE}busybox dc $ASIZEK 1024 \/ p`"
   ONESIZE="`LANG=C ${PRE}busybox printf "%.1f" $xONESIZE`M"
  fi
 fi
 PITEMS="${PITEMS}<item>${ADEV} FS:${AFS} SIZE:${ONESIZE}</item>"
done
if [ "$PITEMS" == "" ];then
 errMSG="$(gettext 'Could not find any partitions to install to. A partition must have ext2, ext3, ext4, reiserfs, f2fs, btrfs or minix filesystem. Aborting install.')"
 ${PRE}popup "level=top background=#FF8080 terminate=ok|<b>$(gettext 'ERROR: no partitions found')</b>${CR}${errMSG}"
 exit
fi
while [ true ];do ###
 export IQ_DLGp="<window title=\"$(gettext "Quirky Installer: partition")\" icon-name=\"gtk-convert\">
 <vbox>
  <text><label>${M_00}</label></text>
  <text><label>${M_01}</label></text>
  <text><label>${M_02}</label></text>
  <text><label>${M_03}</label></text>
  <frame $(gettext 'Choose partition')>
   <text use-markup=\"true\"><label>\"<b>$(gettext 'Choose partition to install to:')</b>\"</label></text>
   <text><label>$(gettext 'Please be careful to choose the correct partition. It must be at least 8GB in size.')</label></text>
   <hbox><vbox width-request=\"260\"><combobox><variable>COMBOp</variable>${PITEMS}</combobox></vbox></hbox>
  </frame>
  <hbox>
   <button><label>$(gettext 'CONTINUE')</label><action type=\"exit\">continue</action></button>
   <button cancel></button>
  </hbox>
 </vbox>
 </window>"
 RETSTRINGp="$(${PRE}gtkdialog --program=IQ_DLGp --center)"
 [ $? -ne 0 ] && exit
 eval "$RETSTRINGp"
 [ "$EXIT" != "continue" ] && exit
 TARGETPART="$(${PRE}busybox echo -n "$COMBOp" | ${PRE}busybox cut -f 1 -d ' ')"
 TARGETFS="$(${PRE}busybox echo -n "$COMBOp" | ${PRE}busybox cut -f 2 -d ':' | ${PRE}busybox cut -f 1 -d ' ')"
 #make sure it is unmounted:
 MNTD="$(${PRE}busybox mount | ${PRE}busybox grep "^/dev/${TARGETPART} " | ${PRE}busybox cut -f 1 -d ' ')"
 if [ "$MNTD" ];then
  ${PRE}busybox umount $MNTD
  if [ $? -ne 0 ];then
   errTITLE="$(gettext 'ERROR, partition mounted:') ${MNTD}"
   errMSG="$(gettext 'The partition is mounted, and cannot unmount it. You need to unmount it and try again.')"
   ${PRE}popup "level=top background=#FF8080 terminate=ok|<b>${errTITLE}</b>${CR}${errMSG}"
   continue
  fi
 fi
 #Check that fdisk/gdisk utility is working...
 FDISK='fdisk'
 TARGETDRIVE="`${PRE}busybox echo -n "$TARGETPART" | ${PRE}busybox cut -c 1-3`"
 #special case, SD card /dev/mmcblk0p1...
 [ "$TARGETDRIVE" = "mmc" ] && TARGETDRIVE="`${PRE}busybox echo -n "$TARGETPART" | ${PRE}busybox sed -e 's/p[0-9]$//'`"
 #180408 nvme drives...
 [ "$TARGETDRIVE" = "nvm" ] && TARGETDRIVE="`${PRE}busybox echo -n "$TARGETPART" | ${PRE}busybox sed -e 's/p[0-9]*$//'`"
 #[ "$Qfw" == "UEFI" ] && FDISK='gdisk'
 GDCHK="$(LANG=C ${PRE}${FDISK} -l /dev/${TARGETDRIVE} 2>/dev/null | ${PRE}busybox grep "^/dev/${TARGETPART} ")" #171109
 if [ "$GDCHK" = "" ];then
  errTITLE="$(gettext 'Partition:') ${TARGETPART}"
  errMSG="$(gettext 'Unable to read this partition. Perhaps you should try a different partition.')"
  ${PRE}popup "level=top background=#FF8080 terminate=ok|<b>${errTITLE}</b>${CR}${errMSG}"
  continue
 fi
 break
done ###

###copy files to target###
${PRE}busybox cp -a -f ${MNTPTsrc}/q.sfs ./
${PRE}busybox cp -a -f ${MNTPTsrc}/initrd.q ./
${PRE}busybox cp -a -f ${MNTPTsrc}/vmlinuz ./
${PRE}busybox cp -a -f ${MNTPTsrc}/logo.16 ./
${PRE}busybox sync
${PRE}busybox umount ${MNTPTsrc}
#${PRE}busybox rmdir ${MNTPTsrc}
IMGFILE='q.sfs'

#151007 mark IMGFILE for deletion in exit_func()...
DELME2="`pwd`/${IMGFILE}"

${PRE}busybox sync
${PRE}busybox killall popup

FSUUID="$(${PRE}busybox blkid /dev/${TARGETPART} | ${PRE}busybox grep -o 'UUID="[^"]*' | ${PRE}busybox cut -f 2 -d '"')" #'

###write to target###
export IQ_DLGs="<window title=\"$(gettext "Quirky Installer: partition")\" icon-name=\"gtk-convert\">
<vbox>
 <text use-markup=\"true\"><label>\"<b>$(gettext 'Final sanity check, is this correct?:') <big>${TARGETPART}</big></b>\"</label></text>
 <text><label>$(gettext 'Quirky will be installed to partition:') ${TARGETPART} $(gettext 'Filesystem:') ${TARGETFS}</label></text>
 <text><label>$(gettext 'Anything previously in the partition will be erased.')</label></text>
 <text><label>$(gettext 'Note, if you already have Quirky installed on the partition, and wish to upgrade it, this is not the application to use. Instead, install a Service Pack PET.')</label></text>
 <text><label>\"  \"</label></text>
 <text><label>$(gettext 'Technical note: Temporary working folder: ')$(pwd)</label></text>
 <hbox>
  <button><label>$(gettext 'CONTINUE')</label><action type=\"exit\">continue</action></button>
  <button cancel></button>
 </hbox>
</vbox>
</window>"
RETSTRINGs="$(${PRE}gtkdialog --program=IQ_DLGs --center)"
[ $? -ne 0 ] && exit_func 0
eval "$RETSTRINGs"
[ "$EXIT" != "continue" ] && exit_func 0

${PRE}busybox mkdir -p /mnt/$TARGETPART
${PRE}busybox mount -t $TARGETFS /dev/$TARGETPART /mnt/$TARGETPART
if [ $? -ne 0 ];then
 errTITLE="$(gettext 'Partition:') ${TARGETPART}"
 errMSG="$(gettext 'failed to mount partition. Aborting install.')"
 ${PRE}popup "level=top background=#FF8080 terminate=ok|<b>${errTITLE}</b>${CR}${errMSG}"
 exit_func 1
fi

${PRE}popup "level=top background='#FFE000'|<b>$(gettext 'Partition:') ${TARGETPART}</b>${CR}$(gettext 'Please wait, erasing contents of partition...')"
${PRE}busybox rm -rf /mnt/$TARGETPART/*
${PRE}busybox rm -rf /mnt/$TARGETPART/.* 2> /dev/null
${PRE}busybox sync
${PRE}busybox killall popup
${PRE}busybox sleep 0.5

${PRE}popup "level=top background='#FFE000'|<b>$(gettext 'Partition:') ${TARGETPART}</b>${CR}$(gettext 'Please wait, writing Quirky files to partition...')"
${PRE}busybox mkdir -p mntpt
${PRE}busybox mount -t squashfs -o loop,ro ${IMGFILE} mntpt
if [ $? -ne 0 ];then
 errTITLE="$(gettext 'File:') ${IMGFILE}"
 errMSG="$(gettext 'Failed to mount file. Aborting install.')"
 ${PRE}popup "level=top background=#FF8080 terminate=ok|<b>${errTITLE}</b>${CR}${errMSG}"
 #151007 ${PRE}busybox rm -f ${IMGFILE}
 exit_func 1
fi

#151007 still trying find where precise 5.7.1 is failing...
if [ ! -f mntpt/etc/DISTRO_SPECS ];then
 errTITLE="$(gettext 'File:') ${IMGFILE}"
 errMSG="$(gettext 'File did not mount properly. Aborting install.')"
 ${PRE}popup "level=top background=#FF8080 terminate=ok|<b>${errTITLE}</b>${CR}${errMSG}"
 #${PRE}busybox rm -f ${IMGFILE}
 exit_func 1
fi

TARGETVERSION="$(${PRE}busybox grep '^DISTRO_VERSION=' mntpt/etc/DISTRO_SPECS | ${PRE}busybox cut -f 2 -d '=' | ${PRE}busybox cut -f 2 -d "'" | ${PRE}busybox cut -f 1 -d ' ')" #ex: 6.0.1'

##140212
#${PRE}popup "level=top background='#FFE000'|<b>$(gettext 'Creating:') ${FILEPREFIX}-${TARGETVERSION}.sfs</b>${CR}$(gettext 'Please wait...')"
#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
#${RXVTEXE} -geometry 80x3+0+0 -bg orange -fg black -title "$(gettext 'Creating:') ${FILEPREFIX}-${TARGETVERSION}.sfs" -e mksquashfs mntpt ${FILEPREFIX}-${TARGETVERSION}.sfs -processors 1
#sync
#killall popup

#151007 ${PRE}popup "level=top background='#FFE000'|<b>$(gettext 'Partition:') ${TARGETPART}</b>${CR}$(gettext 'Please wait, writing to partition...')"
${PRE}cp -a -f --remove-destination mntpt/* /mnt/$TARGETPART/ 2> /tmp/installquirky-cp-errlog

#160419 iso builds no longer have vmlinuz in /boot in q.sfs...
[ -f ./vmlinuz ] && [ ! -f /mnt/$TARGETPART/boot/vmlinuz ] && ${PRE}busybox cp -a ./vmlinuz /mnt/$TARGETPART/boot/

${PRE}busybox sync
${PRE}busybox killall popup
${PRE}busybox umount mntpt

#160420 /etc/rc.d/install.log still in use, add INSTALLED_MODE=full...
echo 'INSTALLED_MODE=full' >> /mnt/${TARGETPART}/etc/rc.d/install.log

#151209 do not want "install" and "save" icons on desktop with full install...
${PRE}busybox sed -i '/installquirky/d' /mnt/${TARGETPART}/root/Choices/ROX-Filer/PuppyPin #remove "install" icon
${PRE}busybox sed -i '/savesession/d' /mnt/${TARGETPART}/root/Choices/ROX-Filer/PuppyPin #remove "install" icon
${PRE}busybox rm -f ./${IMGFILE} #131227
[ -f vmlinuz ] && ${PRE}busybox rm -f vmlinuz
[ -f initrd.q ] && ${PRE}busybox rm -f initrd.q
[ -f logo.16 ] && ${PRE}busybox rm -f logo.16
${PRE}busybox sync

##140212
#echo
#echo "Now copying ${FILEPREFIX}-${TARGETVERSION}.sfs to /audit/reference
#in partition ${TARGETPART}, please wait..."
#cp -a -f ${FILEPREFIX}-${TARGETVERSION}.sfs /mnt/${TARGETPART}/audit/reference/
#DATE="$(date +%Y%m%d%H%M)" #140213 141021
#echo "${DATE} ${FILEPREFIX}-${TARGETVERSION}.sfs" > /mnt/${TARGETPART}/audit/reference/dates #140213 141021

${PRE}busybox sync
${PRE}busybox umount /mnt/${TARGETPART}

#${PRE}busybox rm -f ${FILEPREFIX}-${TARGETVERSION}.sfs

#140123 if installed to a removable drive, the grub "root=/dev/$TARGETPART" is not adequate...
TARGETDRIVE="$(${PRE}busybox echo -n "$TARGETPART" | ${PRE}busybox sed -e 's%[0-9]$%%' -e 's%[0-9]$%%' -e 's%p$%%')" #ex: mmcblk0p1 becomes mmcblk0, sdb12 becomes sdb
TARGETNUM="$(${PRE}busybox echo -n "$TARGETPART" | ${PRE}busybox rev | ${PRE}busybox grep -o '^[0-9]*' | ${PRE}busybox rev)" #ex: mmcblk0p1 becomes 1, sdb12 becomes 12

#171111 want part-num in hex:
xTARGETNUM="$(${PRE}busybox printf "%02x" ${TARGETNUM})" #exs: 9 -> 09, 10 -> 0a
[ "`${PRE}busybox echo -n "$TARGETNUM" | ${PRE}busybox wc -m`" = "1" ] && TARGETNUM="0${TARGETNUM}" #want two digits.

FDISKINFO="$(LANG=C ${PRE}fdisk -l /dev/${TARGETDRIVE} 2>/dev/null)" #171109
DISKUUID="$(${PRE}busybox echo "$FDISKINFO" | ${PRE}busybox grep '^Disk identifier:' | ${PRE}busybox tr -s ' ' | ${PRE}busybox cut -f 3 -d ' ' | ${PRE}busybox sed -e 's%^0x%%')" #ex: 2669a57d

GRUB4DOS="title Quirky ${TARGETVERSION} (full install on ${TARGETPART})
  uuid ${FSUUID}
  kernel /boot/vmlinuz root=PARTUUID=${DISKUUID}-${xTARGETNUM} rootwait rw"

export IQ_DLGf="<window title=\"$(gettext "Quirky Installer: partition")\" icon-name=\"gtk-convert\">
<vbox>
  <text use-markup=\"true\"><label>\"$(gettext 'Installation finished!')\"</label></text>
 <text><label>You will need to configure LILO, GRUB, or whatever boot manager you use, to boot from this partition. For example, for GRUB4DOS, put this in menu.lst:</label></text>
 <text use-markup=\"true\" selectable=\"true\"><label>\"<span bgcolor='white'>${GRUB4DOS}</span>\"</label></text>
 <frame $(gettext 'Notes')>
  <text><label>$(gettext 'The UUID of the filesystem was obtained by running:') blkid /dev/${TARGETPART}</label></text>
  <text><label>$(gettext 'This may not work if the drive is removable, such as USB or SD-card:') root=/dev/${TARGETPART}</label></text>
  <text><label>$(gettext 'But, this will always work:') root=PARTUUID=${DISKUUID}-${xTARGETNUM}</label></text>
  <text><label>$(gettext 'Disk-UUID:') ${DISKUUID} $(gettext 'This is obtained from: ') fdisk -l /dev/${TARGETDRIVE}</label></text>
  <text><label>$(gettext 'Partition:') ${xTARGETNUM} $(gettext 'Partition number in hexadecimal.')</label></text>
  <text><label>$(gettext 'rootwait is optional, essential for external USB drives.')</label></text>
  <text><label>$(gettext 'Unlike Puppy Linux, Quirky only recognises three Quirky-specific kernel boot parameters:') 'qfix=bak', 'qfix=nox' and 'qfix=fsck'</label></text>
 </frame>
 <hbox>
  <button><label>$(gettext 'OK')</label><action type=\"exit\">ok</action></button>
 </hbox>
</vbox>
</window>"
RETSTRINGf="$(${PRE}gtkdialog --program=IQ_DLGf --center)"

exit_func 0
###END###
