#!/bin/bash
##############################################################################
# copycat version 2.0.3
# 2024
##############################################################################
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#
# PATH
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin:/usr/lib/kde4/libexec/
# Added for translation purposes
# i18n - Internationalisation - Internationalisierung
VERSION=2.0.3
export TEXTDOMAIN=copycat_$VERSION
export TEXTDOMAINDIR="/usr/share/locale"
# variable for the gui
ICON="/usr/share/copycat/icons/copycat.svg"
LICON="/usr/share/icons/hicolor/48x48/apps/copycat.svg"
EICON="/usr/share/copycat/icons/error.svg"
WICON="/usr/share/copycat/icons/warning.svg"
CANCEL="/usr/share/copycat/icons/cancel.svg"
OK="/usr/share/copycat/icons/ok.svg"
TITLE="CopyCat"
run_as_root() {
### run as root ####
PID=`ps -eaf | grep yad | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID > /dev/null 2>&1 &
fi
if [ `id -u` -eq 0 ]; then
exec $@
else
`yad --title="CopyCat" --width=400 \
--height=100 --fixed --image="$EICON" \
--window-icon="$EICON" --center \
--text=$"\n\You need to be root to run CopyCat!" \
--button=Ok!/usr/share/copycat/icons/ok.svg:"1"`
if [ "$?" = "1" ] ; then
exit 1
 fi 	
fi
if ! test -d /union; then
exec $@
else
`yad --title="CopyCat" --width=400 \
--height=100 --fixed --image="$EICON" \
--window-icon="$EICON" --center \
--text=$"\n\Copycat Will Only Work With Installed Systems!\nBootloader Will Fail to Function Properly." \
--button=Ok!/usr/share/copycat/icons/ok.svg:"1"`
if [ "$?" = "1" ] ; then
exit 1
 fi 
  fi
rm -f /tmp/copycat >/dev/null 2>&1
rm -f /tmp/copycat_installed >/dev/null 2>&1
NVME=$(grep -o nvme /etc/mtab| awk 'NR==1{print $0}')
if [[ $NVME = "$NVME" ]] 
then
lsblk | grep -o sd[a-z] | tail -n1 |awk '$0="/dev/"$0' > /tmp/copycat
sleep 0.50
USBdevice=$(grep -o sd[a-z] /proc/partitions |tail -n1)
lsblk -do VENDOR,MODEL,SIZE /dev/$USBdevice |sed -e 's/ \+/ /g'| awk 'NR == 2' >> /tmp/copycat
else
lsblk | grep -o sd[b-z] | tail -n1 |awk '$0="/dev/"$0' > /tmp/copycat
sleep 0.50
USBdevice=$(grep -o sd[a-z] /proc/partitions |tail -n1)
lsblk -do VENDOR,MODEL,SIZE /dev/$USBdevice |sed -e 's/ \+/ /g'| awk 'NR == 2' >> /tmp/copycat
USBinfo=$(cat /tmp/copycat | awk 'NR == 2')
fi
if [ -s "/tmp/copycat" ]; then 
exec $@
else
`yad --title="CopyCat" --width=450 --height=100 --fixed --center --image=$WICON \
--window-icon=$WICON --center \
--text=$"\n\No USB Device has been Detected on System?" \
--button=Ok!$OK:"1"`
if [ "$?" = "1" ] ; then
exit 1
 fi 
  fi
# Check if the user remounted the usb key 
CHMOUNT=$(grep -o "0B" /tmp/copycat)  
if [ "$CHMOUNT" = "" ] ; then
exec $@
else
`yad --title="CopyCat" --width=450 --height=100 --fixed --center --image=$ICON \
--window-icon=$ICON --center \
--text=$"\n\Remount the USB Device so it can be detected?\n<span color=\"#e07b39\">Continue only when the USB Device has been Inserted.</span>" \
--button=Cancel!$CANCEL:"1"`
if [ $? = 1 ] ; then 
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0 
   fi
    fi
}
#########################
set_variables() {
STANDARD=""                         # For boot option selection by user
COPY2RAM=""                         # For boot option selection by user
PERSIST=""                          # For boot option selection by user
INSTALL=""                          # For boot option selection by user
DeBug=""                            # For boot option selection by user
DRIVES=""                           # The drive after the USB is plugged in
Part_Num=""                         # The partition number
ISO_FILE=""                         # The selected ISO file for the installation
JOB=""                              # Used to get ADD and LIVE variables from user
ADD=""                              # This is true if an additional OS is being installed
MPnt="/media/CopyCat.$RANDOM"       # The mount point for the target partition (ext4)
NAME=""                             # The chosen name for the OS to be installed
SIZE1=""                            # The free space on the selected partition
SIZE2=""                            # The space required for the selected OS
Install_To=""                       # The partition selected for the installation
Type=""                             # We check the FS to ensure it is usable for the install
isolin_full=""                      # The full path and filename of the isolinx or renamed directory
isolin_path=""                      # The corresponding isolinux directory when not using an ISO
PID=$$                              # Allows to kill the script on error.
sqfs_dir=""                         # The path only of the sqfs file
sqfs_full=""                        # Full path and name of the sqfs file
sqfs_name=""                        # The name only of the sqfs file ie. livecd
efi_Part=""                         # The EFI partition base name e.g  /dev/sdk1
efi_Mnt="/media/CopyCat.$RANDOM"    # The mount point for the EFI partition.
}
#########################
create_mounts() {
mkdir $efi_Mnt                 # Create the directory for the EFI mount
mkdir $MPnt                 # Create the main directory to mount to
}
#########################
get_job() {
########################################################
USBinfo=$(cat /tmp/copycat | awk 'NR == 2')
USBdevice=$(cat /tmp/copycat | awk 'NR == 1')
JOB=$(yad --window-icon=$LICON --center --title="$TITLE" \
--button=Cancel!$CANCEL:3 \
--button=Ok!$OK:0 \
--text=$"\n<b>Select the Action You Wish to Perform</b>\n \
<span color=\"#e07b39\">Please select the action which you wish to perform from the list below.</span>" --entry --height=120 --width=550 --fixed --hide-column=2  --column $"Select" --column $" Option " --column $"- Job Type -" \
$"Create an initial OS  to $USBinfo (  $USBdevice  )" $"Add another OS  to $USBinfo (  $USBdevice  )")
if [ $? = "3" ]; then
yad --window-icon=$LICON --width=500 --height=150 --fixed --center --image="$EICON" \
--title=$"CopyCat" --text=$"
   <b>No Operation was Selected and Canceled</b>!

Restart the program if you want to continue" \
--button=Cancel!$CANCEL:1
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
 fi
if [ -n "${JOB}" ]; then
case $JOB in
"Create an initial OS  to $USBinfo (  $USBdevice  )")
ADD=$"no"
;;
"Add another OS  to $USBinfo (  $USBdevice  )")
ADD=$"yes"
;;
 esac
fi
}
#########################
get_device() {
#########################
# Get usb mounted device
#########################
USBinfo=$(cat /tmp/copycat | awk 'NR == 2')
USBdevice=$(cat /tmp/copycat | awk 'NR == 1')
DRIVES="$USBdevice"
Install_To="$USBdevice"3""
FMT_BOOT=$(yad --window-icon=$LICON --center --title="$TITLE" \
--width=550 --height=100 --fixed --image="$LICON" \
--entry \
--column=$"" \
--text=$"<b>Select an Operation for the USB Key Device</b>\n \
<span color=\"#e07b39\">Format The USB Device before installing the first initial ISO!</span>" \
$"Install PCLinuxOS to $USBinfo (  $USBdevice  )" $"Format and Partition $USBinfo (  $USBdevice  )" \
--button=Cancel!$CANCEL:"1" \
--button=Ok!/usr/share/copycat/icons/ok.svg:"0")
if [ $? = "1" ]; then
umount {/tmp/iso,/media/*}
rm -rf {/tmp/iso,/media/CopyCat.*,/tmp/copycat} > /dev/null 2>&1
pkill -SIGKILL copycat >/dev/null 2>&1
 fi |
if [ $? = "3" ]; then
$(yad --width=375 --height=100 --fixed --center \
--window-icon=/usr/share/copycat/icons/info-help.svg \
--image=/usr/share/copycat/icons/help.png \
--title='Copycat' \
--button=Close!$CANCEL)
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
rm -f /tmp/copycat >/dev/null 2>&1
pkill -SIGKILL copycat >/dev/null 2>&1
else
if [ -n "${FMT_BOOT}" ]; then
case $FMT_BOOT in
"Install PCLinuxOS to $USBinfo (  $USBdevice  )")
;;
"Format and Partition $USBinfo (  $USBdevice  )")
$(yad --title="CopyCat" --width=600 --height=100 --fixed --center \
--text=$"Creating and formatting on $USBinfo $USBdevice\n\n<span color=\"#e07b39\">Warning! This will delete all current data from this usb device!</span>\n" \
--window-icon=$ICON \
--image=$LICON \
--button=Cancel!$CANCEL:"1" \
--button=Ok!/usr/share/copycat/icons/ok.svg:"0")
if [ "$?" = "1" ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
else
exec $@
fi
USBinfo=$(cat /tmp/copycat | awk 'NR == 2')
USBdevice=$(cat /tmp/copycat | awk 'NR == 1')
install_usb="$USBdevice"
DRIVES="$install_usb"
sleep 1
USB_DEVICE=""
Partitions=""
dmesg -c > /dev/null
sleep 0.1
#Format and Partition
while true; do 
echo "#Creating and formatting device..." ;  
sleep 5m;
done | yad --center --progress --pulsate --title="CopyCat" \
--window-icon="$ICON" --image="$LICON" --width=550 \
--button="Cancel!"$CANCEL"":1 --height=100 --fixed \
--text=$"\nCreating Partitions and formatting $USBinfo (  $USBdevice  )" &
while [ "$USB_DEVICE" = "" ]
do
sleep 1
USB_DEVICE=$(cat /tmp/copycat | awk 'NR ==1')
done
# umount any existing mounted partitions
Partitions=$(lsblk -l -o FSTYPE,NAME,SIZE,LABEL $USB_DEVICE | grep "sd[a-z][1-9]" | tr -s ' ' | cut -d ' ' -f2)
for i in $Partitions; do umount /dev/$i ; done
#

# Delete the device partition structure
wipefs -a $USB_DEVICE
#
# Zero the first 2MB for the bios_grub
dd if=/dev/zero of=$USB_DEVICE bs=1M count=2
#
# Create new structure
# This causes the /ext4 partition to mount so we need to umount it below
# so it can be formatted.
echo "label: gpt
unit: sectors
first-lba: 34
: start=        2048, size=        2048, type=21686148-6449-6E6F-744E-656564454649
: start=        4096, size=       67584, type=C12A7328-F81F-11D2-BA4B-00A0C93EC93B
: start=       71680,                    type=0FC63DAF-8483-4772-8E79-3D69D8477DE4
" | sfdisk $USB_DEVICE
#
# Format partitions
(
Device="$USB_DEVICE"2
mkfs.fat -F 32 -I $Device
sleep 2
Device="$USB_DEVICE"3
umount  $Device
sleep 2
echo y | mkfs.ext4 $Device
)
eject $USB_DEVICE
sleep 1
PID=`ps -eaf | grep yad | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1
fi &
$(yad --window-icon=$LICON --height=125 --width=550 --fixed --image="$LICON" \
--center --on-top --title="$TITLE" --text=$"
<b>Creating partitions and formatting complete!</b>

<span color=\"#e07b39\">Remove $USBinfo (  $USBdevice  ) Reinsert and\nMount The USB Key Device to continue the Installation</span>\n" \
--button="Close!$CANCEL":1) 
if [ $? = 1 ]; then
umount {/tmp/iso,/media/*}
rm -rf {/tmp/iso,/media/CopyCat.*,/tmp/copycat} > /dev/null 2>&1
pkill -SIGKILL copycat > /dev/null 2>&1
exit 0
fi
;;
 esac
fi
  fi
USBinfo=$(cat /tmp/copycat | awk 'NR == 2')
USBdevice=$(cat /tmp/copycat | awk 'NR ==1')
install_usb="$USBdevice"
if [ "$DRIVES" = "$DRIVES" ]; then
USBdevice=$(cat /tmp/copycat | awk 'NR == 2')
sleep 1
Install_To="$USBdevice"3""
echo "$Install_To"
else
yad --width=375 --height=100 --fixed --center \
--text=$"\nNo usb key mounted on system!\nMount the usb key to continue setup" \
--window-icon=/usr/share/copycat/icons/copycat.svg \
--image="$EICON" \
--title='Error' \
--button=Close!$CANCEL:1
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
 fi
##########################################################
USBdevice=$(cat /tmp/copycat | awk 'NR == 1')
sleep 1
Install_To="$USBdevice"3""
echo "$Install_To"
Install_To=$(echo $Install_To | sed 's/[|].*//'); echo $Install_To
####################################################################
umount -q $Install_To
Part_Num=$(echo "$Install_To" | cut -c9-10 )
}
#########################
get_device_type() {
FDISK_GET=$(dmesg | tail -8 | grep -i "Attached SCSI " | grep -i " disk" | grep -i sd[a-z] | sed 's|^.*\[||' | sed 's|\].*||' | sed 's|s|/dev/s|')
if [ $FDISK_GET = "" > /dev/null 2>&1 ]; then
FDISK_GET="$install_usb"
fi
DOS=""
GPT=""
DOS=$(fdisk -l $FDISK_GET | grep "dos" | sed 's| ||g'| cut -d : -f2)
GPT=$(fdisk -l $FDISK_GET | grep "gpt" | sed 's| ||g'| cut -d : -f2)
}
#########################
get_uuid() {
if [ "$DRIVES" = "$DRIVES" ]; then
exec
else
yad --width=375 --height=100 --fixed --center \
--text=$"\nInstallation Setup Failed!\nReinsert the usb key to continue" \
--window-icon=/usr/share/copycat/icons/copycat.svg \
--image="$EICON" \
--title='Error' \
--button=Close!$CANCEL:1
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
pkill -SIGKILL copycat > /dev/null 2>&1
exit 0
fi
###############################################
#### Get the UUID of partition.           ####
###############################################
PART_UUID=$(lsblk -l -n -o UUID "$Install_To")
if [ "$PART_UUID" == "" ] ; then
umount /media/CopyCat.*
rm -rf /media/CopyCat.*
pkill -f /usr/bin/copycat
exit 0
fi
}
##################################
# Write a label for the USB drive
#################################
write_label() {
if [ "$DRIVES" = "$DRIVES" ]; then
LABEL="CopyCat" 
LABEL_Exist=$(e2label $Install_To)
e2label "$Install_To" "$LABEL"
else
yad --width=450 --height=100 --fixed --center \
--text=$"\nReinsert the key mounted on system!\nRemount the usb key to continue" \
--window-icon=/usr/share/copycat/icons/copycat.svg \
--image="$EICON" \
--title='Error' \
--button=Close!$CANCEL:1
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
 fi
}
#########################
get_iso() {
#############################
# Get the iso image
#############################
USER=$(who |sed 's/ .*//'|tail -n1)
ISO_FILE=$(yad --file --filename=/home/$USER --center --file-filter="*.iso" \
--window-icon=/usr/share/copycat/icons/copycat.svg \
--image=/usr/share/copycat/icons/copycat.svg --height=550 \
--width=725 --on-top --title="CopyCat" \
--text=$"<b>Select a ISO File to Install  to $USBinfo $USBdevice</b>" \
--button=Cancel!$CANCEL:2 \
--button=Select!/usr/share/copycat/icons/ok.svg:0)
if [ ${ISO_FILE: -4} == ".iso" > /dev/null 2>&1 ]; then
ISOCHECK=(`isoinfo -l -i "$ISO_FILE" | grep -E "PCLINUXOS" | awk 'NR==1{print $0}' | awk -F']' '{print $NF}' | sed 's/^..//' > /tmp/check`)
Check="`grep -E "PCLINUXOS" /tmp/check | awk 'NR==1{print $0}'`"
if [[ $Check == "" ]]
then 
`yad --title="CopyCat" --width=500 --height=100 --fixed --center --image=$WICON \
--window-icon=$WICON --center \
--text=$"\n\<span color=\"#e07b39\">Stop! You have chosen a iso that is not a PCLinuxOS iso?</span>" \
--button=Cancel!$CANCEL:"1"`
if [ $? = 1 ] ; then 
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
pkill -SIGKILL copycat >/dev/null 2>&1 
exit
   fi
else
echo "$ISO_FILE"
fi
rm -f /tmp/check >/dev/null 2>&1
else
yad --window-icon=$LICON --width=425 --height=125 --fixed --center \
--image="$EICON" \
--title=$"CopyCat" --text=$"
     <b>No File Selected or Available</b>!

 Restart the program if you want to continue" \
--button=Cancel!$CANCEL:1
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
 fi
if [ $? = "2" ]; then
yad --window-icon=$LICON --width=425 --height=125 --fixed --center \
--image="$EICON" \
--title=$"CopyCat" --text=$"
     <b>No File Selected or Available</b>!

 Restart the program if you want to continue" \
--button=Cancel!$CANCEL:5
if [ $? = "5" ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
 fi
}
#########################
mount_part() {
mount $Install_To $MPnt
if [ "$?" != "0" ] ; then
yad --window-icon=$LICON --width=450 --height=125 --fixed --center \
--image="$EICON" \
--title=$"Error" --text=$"
     <b>A Mounting Error has Occured</b>

     Seems the USB key has not been mounted properly?

         Please check about this mounting error." \
--button=Cancel!$CANCEL:1
if [ $? = 1 ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
pkill -SIGKILL copycat > /dev/null 2>&1
exit 0
fi
 fi
}
#########################
get_name() {
if [ "$ADD" = "yes" ]
then
find /media/*/* -iname '*.sqfs' 2>/dev/null|awk '{print $0}'|sed 's/.....$//' |awk -F'/' '{print $NF}' > /tmp/copycat_installed
sleep 0.50
if [ -s "/tmp/copycat_installed" ]; then 
rm -f /tmp/copycat_installed >/dev/null 2>&1
else
$(cat "/tmp/copycat_installed" | awk '{print $0}')
$(yad --title="CopyCat" --width=600 --height=100 --fixed --center \
--text=$"\n\n<span color=\"#e07b39\">STOP! Use the <b>Create an Initial OS</b> option for the first installation!</span>\n" \
--window-icon=$WICON \
--image=$WICON \
--button=Cancel!$CANCEL:"1") 
if [ "$?" = "1" ]; then
exec "/usr/bin/copycat"
fi
 fi
  fi
if [ "$ADD" = "no" ]
then
find /media/*/* -iname '*.sqfs' 2>/dev/null|awk '{print $0}'|sed 's/.....$//' |awk -F'/' '{print $NF}' > /tmp/copycat_installed
sleep 0.50
if [ -s "/tmp/copycat_installed" ]; then 
list=$(cat "/tmp/copycat_installed" | awk '{print $0}')
$(yad --title="CopyCat" --width=550 --height=150 --fixed --center \
--text=$"Please Use the Second Option to Add another ISO to Device\n<span color=\"#e07b39\">Installed list currently on this USB key device installed previous</span>\n$list" \
--window-icon=$WICON \
--image=$WICON \
--button=Cancel!$CANCEL:"1") 
if [ "$?" = "1" ]; then
exec "/usr/bin/copycat"
 fi
  fi
   fi
while [[ ! "$NAME" =~ [a-zA-Z0-9] ]]; do
NAME=$(yad --window-icon=$LICON --center --list --height=400 --width=525 --title="$TITLE" --text=$"
<b>Select a PCLinuxOS Distro Name</b>
<span color=\"#e07b39\">Please ensure you do not select a name already in use on the device
Highlight a name and select <b>OK</b> to accept it</span>" --editable --column $"- Add Custom Name -
Highlight entry to edit name. Press Enter twice to apply your edit.
Name changes must not be left blank or spaces in the name!"  "KDE" "MATE" "Xfce" "Darkstar" "Trinity" "Openbox" \
--button=Cancel!$CANCEL:1 \
--button=OK!/usr/share/copycat/icons/ok.svg:0)
if [ "$?" = "0" ] ; then
echo "$NAME"
fi
# Replace spaces with _    Leading spaces are omitted.
NAME=$(echo "$NAME" | sed 's/[|].*//')
if [ "$?" != "0" ] ; then
yad --window-icon=$LICON --height=100 --center --width=500 --fixed \
--image="$EICON" --title=$"Error" --text=$"
                         <b>CANCEL</b>

     You have chosen to cancel this application.

        We will now abort the installation.

  Thank you for trying CopyCat" \
--button=Cancel!$CANCEL:1
if [ "$?" = "1" ] ; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
 fi
if [ "$NAME" = "" ]
then
yad --window-icon=$LICON --center --width=400 --height=125 --fixed \
--image="$EICON" --title=$"Error" --text=$"
		<b>An Error has Occured</b>

  You failed to correctly enter or select a name for the OS.

                      Please try again." \
--button=Quit!$CANCEL:1 \
--button=OK!/usr/share/copycat/icons/ok.svg:0
if [ "$?" = "1" ] ; then
umount {/tmp/iso,/media/*}
rm -rf {/tmp/iso,/media/CopyCat.*} > /dev/null 2>&1
exit 0
fi
else
##################################
# check if adding an OS
##################################
if [ "$ADD" = "yes" ]
then
if [ -d $MPnt/$NAME ]
then
yad --window-icon=$LICON --center --height=100 --width=500 --fixed \
--image="$EICON" --title="$TITLE" --text=$"
		<b>An Error has Occured</b>

     You have selected an existing name for the OS.

              Please try again." \
--button=Quit!$CANCEL:1 \
--button=OK!/usr/share/copycat/icons/ok.svg:0
if [ "$?" = "0" ] ; then
NAME=""
else
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
fi
 fi
  fi
done
 }
get_size() {
####################################
#### Check we have sufficient space
####################################
SIZE1=$(df -B M --output=avail $MPnt | sed '1d' | cut -d 'M' -f1)
SIZE2=$(du -B M "$ISO_FILE" | cut -d 'M' -f1)
SIZE2=$(($SIZE2+10))
if [ $SIZE2 -gt $SIZE1 ]; then
unmount_part
yad --window-icon=$LICON --width=475 --height=125 --fixed --on-top --center \
--image="$EICON" \
--title=$"Error" --text=$"
	          <b>A Fatal Error has Occured</b>

There is Insufficient Room for the Installation.

                      This application will now abort!" \
--button=Close!$CANCEL:1
if [ $? = 1 ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
 fi
}
get_size2() {
#### Check have sufficient space for Extracted Files ####
###################################################################
SIZE1=$(df -B M --output=avail $MPnt | sed '1d' | cut -d 'M' -f1)
SIZEA=$(du -B M -s "$sqfs_full" | cut -d 'M' -f1)
if [ "$?" != "0" ] ; then
yad --window-icon=$LICON --width=475 --height=125 --fixed --on-top \
--center --image="$EICON" \
--title=$"Error" --text=$"
	          <b>Cannot find your files</b>

       An ERROR has occurred so we are aborting.

          Please give feedback about this error.

                            Thank you!" \
--button=Close!$CANCEL:1
if [ $? = 1 ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
  fi
SIZEB=$(du -B M -s "$isolin_full" | cut -d 'M' -f1)
if [ "$?" != "0" ] ; then
yad --window-icon=$LICON --width=475 --height=125 --fixed --on-top \
--center --image="$EICON" \
--title=$"Error" --text=$"
	          <b>Cannot find your files</b>

       An ERROR has occurred so we are aborting.

          Please give feedback about this error.

                            Thank you!" \
--button=Close!$CANCEL:1
if [ $? = 1 ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
 fi
SIZE2=$(($SIZEA+$SIZEB+10))
if [ $SIZE2 -gt $SIZE1 ]; then
unmount_part
yad --window-icon=$LICON --width=475 --height=125 --fixed --on-top \
--center --image="$EICON" \
--title=$"Error" --text=$"
	          <b>An Fatal Error has Occured</b>

There is Insufficient Room for the Installation to Proceed.
You need either a larger device or else choose a smaller
OS to fit on this device.
            This application will now abort!" \
--button=Close!$CANCEL:1
if [ $? = 1 ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
 fi
}
wipe_part() {
rm -rf $MPnt/*
efi_wipe=$(fdisk -l $FDISK_GET -o Device,Type | grep EFI | tr -s ' ' | cut -d ' ' -f1)
if [ "$efi_wipe" != "" ]; then
rm -rf $efi_Mnt/*
fi
}
copy_iso_files() {
#######################################
#### Extract the files from the ISO ###
#######################################
if [ "$?" != "0" ] ; then
yad --window-icon=$LICON --width=475 --height=125 --fixed \
--on-top --center --image="$EICON" \
--title=$"Error" --text=$"
	          <b>An Error has Occured</b>

       We were unable to create a directory on your partition.

           Please give feedback about this error.


                             Thank you!" \
--button=Close!$CANCEL:1
if [ $? = 1 ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
 fi
###############################################
# Cleanup /tmp/iso if it exists
###############################################
if [ -d /tmp/iso ]; then
umount /tmp/iso
rm -rf /tmp/iso > /dev/null 2>&1
fi
###############################################
# Mount the iso
###############################################
if [ ! -d /tmp/iso ]; then
mkdir -p /tmp/iso
fi
mount "$ISO_FILE" /tmp/iso 
cp -r /tmp/iso/isolinux $MPnt/$NAME 
cp -r /tmp/iso/livecd.sqfs $MPnt/$NAME.sqfs &
########################################################################
####   Change name of ISO files to that provided by the user.       ####
########################################################################
if [ "$ADD" != "yes" ]
then
stat /tmp/iso/EFI > /dev/null 2>&1
if [ "$?" = "0" ] ; then
cp -r /tmp/iso/EFI $MPnt/EFI
fi
 fi
}
#########################
copy_extracted_files() {

if [ "$?" != "0" ] ; then
yad --window-icon=$LICON --width=475 --height=125 --fixed \
--on-top --center --image="$EICON" \
--title=$"Error" --text=$"
	          <b>An Error has Occured</b>

    We were unable to create a directory on your partition.

           Please give feedback about this error.


                             Thank you!" \
--button=Close!$CANCEL:1
if [ $? = 1 ]; then
umount /media/*
rm -rf /media/CopyCat.* > /dev/null 2>&1
exit 0
fi
 fi
######################################################################
#### Change name of files to that provided by the user.           ####
#### Added the EFI directory to list. This will need to be moved  ####
#### to EFI partition later or else deleted if not used.          ####
######################################################################

if [ "$ADD" != "yes" ]
then
stat $sqfs_dir/EFI
if [ "$?" = "0" ] ; then
cp -r $sqfs_dir/EFI $MPnt/EFI
fi
 fi
#########################################################
#### Move and rename files and delete temp directory ####
#########################################################

}
#########################
permissions() {
#########################
chmod -R 0777 $MPnt
rm -rf $MPnt/boot/grub
wait
}
unmount_part() {
# Copy the boot theme everytime
if [ -d $MPnt/boot/grub2/themes ]
then
rm -rf $MPnt/boot/grub2/themes
fi
if [ ! -d $MPnt/theme ]
then
cp -rf "/usr/share/copycat/theme" $MPnt
chmod 777 $MPnt/theme
chmod 777 $MPnt/theme/*
fi
################################
#### Unmount all partitions ####
################################
mv -f $MPnt/isolinux $MPnt/"$NAME" 
mv -f $MPnt/livecd.sqfs $MPnt/"$NAME".sqfs 
umount -q {$Install_To,$MPnt,$efi_Part,$efi_Mnt,/tmp/iso,/media/CopyCat}
}
finished() {
######################################################
### Show finished dialog
######################################################
rm -rf {/media/root,/tmp/iso,/media/CopyCat.*,/media/CopyCat/.tmp} > /dev/null 2>&1
rm -f /tmp/copycat >/dev/null 2>&1
PID=`ps -eaf | grep yad | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1
fi &
sleep 1
iso_name=$(echo "$NAME" | sed 's/[|].*//')
yad --window-icon=$LICON --width=475 --image="$LICON" \
--center --on-top --height=100 --fixed --title="$TITLE" --text=$"
<b>PCLinuxOS $iso_name installation is complete!</b>

<span color=\"#e07b39\">You may Safely Remove the USB device now.</span>" \
--button=Close!$CANCEL:"1"
if [ "$?" = "1" ];then
exit 0
fi
}
#########################
abort() {
##########################
#### On error do this ####
##########################
if [ "$Install_To" != "" ]; then
umount -q $Install_To
fi
rm -rf /media/CopyCat.*
kill $PID
exit
}
#########################
copy_grub2() {
#################################################
#### Copy Grub2 files from the installed OS   ####
#################################################
mkdir -p $MPnt/boot/grub2
cp -r /boot/grub2/*  $MPnt/boot/grub2/
cp -r /boot/gfxmenu $MPnt/boot/
#####################################
####   Remove unwanted files.    ####
#####################################
rm -f $MPnt/boot/grub2/{grub*,cust*,inst*,menu.lst}
}
#########################
prepare_for_install() {
##############################
#### Select EFI Partition ####
##############################
efi_Part=""
efi_Part=$(fdisk -l $FDISK_GET -o Device,Type | grep EFI | tr -s ' ' | cut -d ' ' -f1)
###########################################################
## Check for presence of bios_grub (BIOS boot) partition ##
###########################################################
bios_grub=$(fdisk -l $FDISK_GET -o Device,Type | grep BIOS | tr -s ' ' | cut -d ' ' -f1)
###########################################################
#### Only do the following IF the EFI partition exists ####
###########################################################
        if [ "$efi_Part" != "" ]; then
mount $efi_Part $efi_Mnt
##################################################################
#### If not adding to an existing install remove the original ####
#### EFI directory and copy in the new one.                   ####
##################################################################
   if [ "$ADD" = "no" ]
then
rm -rf $efi_Mnt/*
mkdir -p $efi_Mnt/EFI
###########################################################################
#### Insert test to ensure we have EFI directory on the EFI partition  ####
####                  Create it if required                            ####
###########################################################################
if [ "$ADD" = "yes" ]
then
    stat "$efi_Mnt/EFI" > /dev/null 2>&1
if [ "$?" != "0" ]
then
mkdir -p $efi_Mnt/EFI
fi
 fi
  fi
   fi
   if [ "$ADD" = "no" ]
then
#####################################
#### Copy Grub2 files            ####
#### Delete all grub.cfg* files. ####
#####################################
copy_grub2
###################################
#### Write a new grub.cfg file ####
###################################
cat >> $MPnt/boot/grub2/grub.cfg <<EOF
set timeout=5
insmod part_gpt
insmod part_msdos
insmod fat
insmod ext2
insmod all_video
insmod font
insmod png
insmod jpeg

if loadfont "\${prefix}/fonts/unicode.pf2"
then
	insmod gfxterm
	set gfxmode=1024x768
	set gfxpayload=keep
	terminal_input console
	terminal_output gfxterm
fi

set theme=(\$root)/theme/theme.txt
export theme
search --no-floppy --set=root -u $PART_UUID

EOF
	fi

########################################
#### Get Grub2 Boot options from user ####
########################################
grub2_boot_options
#################################################
#### Append menuentries in $BOOT to grub.cfg ####
#################################################
for i in "$BOOT"; do echo "$i" >> $MPnt/boot/grub2/grub.cfg; done
##################################
#### Call the installers      ####
##################################
do_installs
permissions
#########################################
#### Remove the copied EFI directory ####
####    Unmount the EFI partition    ####
#########################################
umount -q {$efi_Mnt,$efi_Part}
rm -rf $MPnt/EFI
}
#########################
grub2_boot_options() {
#######################################################
####      $BOOT holds the boot options.            ####
#### Define the variables  for the grub.cfg file   ####
#######################################################
# Clear previously used Variables
STANDARD=""
COPY2RAM=""
PERSIST=""
INSTALL=""
DeBug=""
# Apply complete name to $osname
osname="$NAME"
#
# Define the 5 boot options here for EFI grub.cfg file

PERSIST="
menuentry  "'"'$NAME' with Persistence"'"  --class pclinuxos {
linux /$osname/vmlinuz livecd=/$osname root=/ changes_dev=UUID=$PART_UUID acpi=on fstab=rw,noauto fromusb quiet splash=silent
initrd /$osname/initrd.gz
}"

STANDARD="
menuentry "'"'$NAME' Standard Boot"'"  --class pclinuxos {
linux /$osname/vmlinuz livecd=/$osname root=/ acpi=on fromusb quiet splash=silent
initrd /$osname/initrd.gz
}"

SafeMode="
menuentry "'"'$NAME' Video Safe Mode - Vesa"'"  --class pclinuxos {
linux /$osname/vmlinuz livecd=/$osname root=/ xdriver=vesa fromusb quiet splash=silent
initrd /$osname/initrd.gz
}"

COPY2RAM="
menuentry   "'"'$NAME' Copy to RAM"'"  --class pclinuxos {
linux /$osname/vmlinuz livecd=/$osname root=/ copy2ram acpi=on fromusb quiet splash=silent
initrd /$osname/initrd.gz
}"

INSTALL="
menuentry   "'"'$NAME' Install"'"  --class pclinuxos {
linux /$osname/vmlinuz livecd=/$osname root=/ acpi=on fromusb quiet splash=silent install
initrd /$osname/initrd.gz
}"

DeBug="
menuentry   "'"'$NAME' Debug On"'"  --class pclinuxos {
linux /$osname/vmlinuz livecd=/$osname root=/ acpi=on fromusb debug
initrd /$osname/initrd.gz
}"

#### window for user to select options ####
##################################################
BOOT=$(yad --window-icon=$LICON --on-top --center --list --title="$TITLE" --text=$"<b>Select the <b>EFI</b> Boot options to Include</b>\n<span color=\"#e07b39\">Please Select One Boot Option from the list below</span>" --checklist --hide-column=2 --print-column=2 --multiple --separator=" " --height=420 --width=400 --column $"Select" --column $" Option " --column $" - Option Detail - " TRUE  "$PERSIST" $"Boot with Persistence
" FALSE "$STANDARD"   $"Standard live boot option
" FALSE "$SafeMode"   $"Video Safe Mode - Vesa
" FALSE "$COPY2RAM"   $"Copy To RAM
" FALSE "$INSTALL"    $"Install PCLOS
" FALSE "$DeBug"      $"Boot in debug Mode" --button=Ok!/usr/share/copycat/icons/ok.svg:0)
if [ $? = 0 ]; then
echo "$BOOT" > /dev/null 2>&1
fi
 }
#########################
do_installs() {
##########################################################
#### Copy files & show progress  
##########################################################
if [ "$ADD" = "no" ]
then
rm -rf $MPnt/$NAME > /dev/null 2>&1
rm -f $MPnt/$NAME.sqfs > /dev/null 2>&1
# show progress 
USB_device="$install_usb"
iso_name=$(echo "$NAME" | sed 's/[|].*//')
    touch $MPnt/.temp
    source=$ISO_FILE
    sourcesize=$(du -m -s "$source" | cut -f1)
    target=$MPnt/.temp
    targetsize=$(du -m -s $target | cut -f1)
    cp_target=$MPnt
    cp_sourcesize=$(du -m -s $source | cut -f1)
    cp_targetsize=$(du -m -s $MPnt | cut -f1)
     rsync -av "/tmp/iso"/ "$MPnt"/ &
    dd if=$source of=$target oflag=nocache &
    sleep 0.1;
    while [[ $cp_targetsize -lt $cp_sourcesize ]]; do
    sleep 0.1;
    cp_targetsize=$(du -m -s $target | cut -f1)
    percent=$(("$cp_targetsize"*110/$cp_sourcesize))
    echo $percent 2>/dev/null
    done | yad --window-icon=$LICON --image=$LICON \
    --on-top --width=550 --height=100 --center --fixed --progress --title="$TITLE" --text=$"
<b>Creating the Operating System on the Device</b>

<span color=\"#e07b39\">Installing  $OSNAME $iso_name  to $USBinfo ( $USBdevice )</span>" \
    --auto-close --button=Cancel!$CANCEL:"5" 
    if [ $? = "5" ]; then
    killall "rsync" >/dev/null 2>&1
    killall "dd" >/dev/null 2>&1
    sleep 0.50
    umount /tmp/iso
    rm -rf /tmp/iso  > /dev/null 2>&1
    rm -rf /media/root/CopyCat > /dev/null 2>&1
    rm -f /tmp/{selected,copycat} > /dev/null 2>&1
    sleep 1
    umount {$Install_To,$MPnt,$MPnt.*}
    rm -rf {$MPnt.*,$MPnt} > /dev/null 2>&1
    su $USERS -c /usr/share/copycat/cancel_notify.py
    rm -f /tmp/{selected,copycat} > /dev/null 2>&1
    killall "pclos" 2>/dev/null
    killall "copycat" 2>/dev/null
    exit
     fi
      fi
if [ "$ADD" = "yes" ]
then
USB_device="$install_usb"
iso_name=$(echo "$NAME" | sed 's/[|].*//')
if [ "$?" = 0 ]; then
while true; do 
if [ $1 ]
then
    date1=`date +%s`+$1;
else
    date1=`date +%s`;
fi
while true; do 
echo "#Copying files... Please wait!   Elapsed time: $(date -u --date @$((`date +%s` - $date1)) +%M:%S) minutes" 
sleep 1
done
done | yad --progress --pulsate --window-icon="$LICON" --image="$LICON" \
--on-top --width=600 --height=100 --center --fixed --title="$TITLE" --text=$"
<b>Adding and Creating a Multifunctional USB Key Device</b>

<span color=\"#e07b39\">Installing PCLinuxOS $iso_name  to $USBinfo ( $USBdevice )</span>" \
--button=Close!$CANCEL --auto-close &
 fi
  fi |
if [ "$FORCE" == "1" ] ; then ADD="no"
fi
if [ "$ADD" = "no" ] && [ "$GPT" = "gpt" ] && [ "$bios_grub" != "" ]
then
grub2-install --target=i386-pc --boot-directory=$MPnt/boot $DRIVES
 fi
 if [ "$ADD" = "no" ] && [ "$GPT" = "gpt" ] && [ "$efi_Part" != "" ]
then
grub2-install --target=x86_64-efi --efi-directory=$efi_Mnt --boot-directory=$MPnt/boot --removable --recheck > /dev/null 2>&1
 fi
 if [ "$ADD" = "no" ] && [ "$DOS" = "dos" ]
then
grub2-install --target=i386-pc --boot-directory=$MPnt/boot $DRIVES
 fi
 if [ "$ADD" = "no" ] && [ "$DOS" = "dos" ] && [ "$efi_Part" != "" ]
then
grub2-install --target=x86_64-efi --efi-directory=$efi_Mnt --boot-directory=$MPnt/boot --removable --recheck > /dev/null 2>&1
 fi
}
#########################
usb_install() {
set_variables
get_device
get_device_type
create_mounts
write_label
get_uuid
get_job
mount_part
get_name
if [ "$LIVE" != "yes" ]

then
get_iso
fi
	(
        echo ; sleep 1
if [ "$ADD" = "yes" ]; then
stat "$MPnt/boot/grub2/grub.cfg"
 fi
if [ "$ADD" != "yes" ]
then
wipe_part
fi
if [ "$LIVE" != "yes" ]
then
get_size
copy_iso_files
else
get_size2
copy_extracted_files
fi
prepare_for_install
unmount_part
echo "Finishing up install" > /dev/null 2>&1
 )
finished
##########################
#### Eject the device ####
##########################
eject $DRIVES
}
#########################
#
# Main Program
run_as_root
usb_install

exit 0


