#! /bin/bash

. "${BASH_SOURCE%/*}/inisup"

clear
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "     The makeHDD script to install to hard drive or UFD - TeraByte, Inc."
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo

# Once installed to a partition (FAT16/32 or Ext2), that partition can be slid,
# copied, imaged/restored and will still boot. If installed to ext2, the partition
# can also be resized, but not for FAT16/32.

# although root not required if permissions are correct, there's too much
# chance that they aren't, and fixing it is dependent on distro and user's
# knowledge of Linux

# check running as root
userid=`id -u`
if [ ! "$userid" = "0" ]; then
    echo "This script must be run as root...exiting"
    echo
    exit 1
fi

# check if running from iflnet or from a distro
# if running from disk, determine if iflbuild dir contains the boot disk config items
# if so, run as if intalled on a distro, with the same options to create custom disks
if [ -f /tbu/utility/running ]; then
    rundir=`pwd`
    if [ "$rundir" = "/tbu/iflbuild" ] && [ "$0" = "./makeHDD" ]; then
	runmode=distro
	util=util
	tbosdtpath="./util/tbosdt"
    else
	runmode=running
	util=utility
	tbosdtpath="/tbu/tbosdt"
	cd /tbu
    fi
else
    util=util
    tbosdtpath="./util/tbosdt"
    runmode=distro
fi

# get directory owner id
currentdir=`pwd`
if [ "$runmode" = "distro" ]; then
    # get directory owner and group
    currentdir=`pwd`
    ownerid=`stat -c %U $currentdir`
    groupid=`stat -c %G $currentdir`
    if [ "$ownerid" = "root" ]; then ownerid=0; fi
    if [ "$groupid" = "root" ]; then groupid=0; fi
    if [ "$currentdir" = "/" ]; then
	echo "This script cannot be run from the / directory...exiting"
	echo
	exit 1
    fi
    # chown all files and directories to owner:group
    # as precaution make sure running from IFL dir, otherwise don't do it
    if [ "$0" = "./makeHDD" ]; then
	chown -R $ownerid:$groupid util 2> /dev/null
	chown -R $ownerid:$groupid help 2> /dev/null
	chown -R $ownerid:$groupid wireless 2> /dev/null
	chown -R $ownerid:$groupid scripts 2> /dev/null
	chown -R $ownerid:$groupid iscsi 2> /dev/null
	chown -R $ownerid:$groupid cdboot 2> /dev/null
	chown -R $ownerid:$groupid pxe 2> /dev/null
	chown -R $ownerid:$groupid grub 2> /dev/null
	chown -R $ownerid:$groupid tbosdtfiles 2> /dev/null
	chown $ownerid:$groupid *
    fi
else
    ownerid=0; groupid=0
fi

# check for read/write access and running on Linux fs
tf1=0;tf2=0
for i in `seq 1 5000`
do
    if [ "$tf1" = "0" ]; then
        if [ ! -f t$i ] && [ ! -d t$i ]; then tf1=t$i; fi
    elif [ "$tf2" = "0" ]; then
        if [ ! -f t$i ] && [ ! -d t$i ]; then tf2=t$i; fi
    else
        break
    fi
done
if [ ! "$tf1" = "0" ] && [ ! "$tf2" = "0" ]; then
    touch $tf1 2> /dev/null
    if [ ! -e $tf1 ]; then
        echo "Unable to create a test file. This indicates that this partition"
        echo "is mounted read only. To work with the IFL disk from Linux, the"
        echo "zip archive must be extracted on a *Linux* partition, and that"
        echo "partition must be mounted with read/write privileges...exiting"
        echo
        exit 1
    fi
    chmod +x $tf1
    chmod -x $tf1
    cp $tf1 $tf2
    if [ -x $tf2 ]; then
        rm $tf1; rm $tf2
        echo "This script must be run on a Linux file system. It appears to be"
        echo "either FAT/FAT32 or NTFS. Please extract the IFL zip archive on"
        echo "a Linux partition (ext2/3/4 or reiserfs)...exiting"
        echo
        exit 1
    fi
    rm $tf1; rm $tf2
fi

# if no /sys/block exit (usually means old kernel < 2.6.x)
# script depends heavily on /sys/block to get device information
# Note: contents of /sys/block vary between older/newer 2.6.x kernels
# This script attempts to use only data that is common among them
if [ ! -d /sys/block ]; then 
    echo "The /sys/block directory is not present on this system."
    echo "makeHDD cannot safely be used...exiting"
    echo
    exit 1
fi

# parse command line
mbr=0;active=0;custom=0;nn=0;synerror=0;doini=0;nocfm=0;nf=0;rest=0
for param in $2 $3 $4 $5 $6 $7 $8;
do
    if [ "$param" = "/a" ]; then let active=active+1
    elif [ "$param" = "/mbr" ]; then let mbr=mbr+1
    elif [ "$param" = "/c" ]; then let custom=custom+1
    elif [ "$param" = "/nn" ]; then let nn=nn+1
    elif [ "$param" = "/doini" ]; then let doini=doini+1
    elif [ "$param" = "/nocfm" ]; then let nocfm=nocfm+1
    elif [ "$param" = "/nf" ]; then let nf=nf+1
    elif [ "$param" = "/r" ]; then let rest=rest+1
    elif [ "$param" != "" ]; then synerror=1
    fi
done

if [ "$active" -gt "1" ]; then synerror=1; fi
if [ "$mbr" -gt "1" ]; then synerror=1; fi
if [ "$custom" -gt "1" ]; then synerror=1; fi
if [ "$nn" -gt "1" ]; then synerror=1; fi
if [ "$doini" -gt "1" ]; then synerror=1; fi
if [ "$nocfm" -gt "1" ]; then synerror=1; fi
if [ "$nf" -gt "1" ]; then synerror=1; fi
if [ "$rest" -gt "1" ]; then synerror=1; fi

# /c and /nn not supported when running from iflnet
if [ "$runmode" = "running" ] && [ "$custom" != "0" ]; then synerror=2; fi
if [ "$runmode" = "running" ] && [ "$nn" != "0" ]; then synerror=2; fi
# if [ "$runmode" = "running" ] && [ "$nocfm" != "0" ]; then synerror=2; fi
if [ "$runmode" = "distro" ] && [ "$doini" != "0" ]; then synerror=2; fi

if [ "$rest" = "1" ]; then
    if [ ! -d cdboot ]; then
	synerror=3
    elif [ "$nn" = "1" ] || [ "$custom" = "1" ] || [ "$doini" = "1" ]; then
	synerror=4
    fi
fi

if [ "$runmode" = "distro" ]; then
    if [ "$nn" = "1" ]; then 
	netsupport=0
	isofilename=ifl.iso
	volname=ifl
    elif [ "$nn" = "0" ]; then 
	netsupport=1
	isofilename=iflnet.iso
	volname=iflnet
    else
	netsupport=""
    fi
else
    netsupport=""
fi

device=0;wdevice=0;partition=0;checkremove=0;checkcdrom=0;checkhdx=0
#check for sdx devices first
if [ ! "$1" = "" ]; then
    # cover a to z - someone out there will have it...
    for fd in sd{a..z} nvme{0..20}n{1..9} hd{a..z}
    do
	if [ "$1" = "/dev/$fd" ]; then
	    device=$fd
	    wdevice=$fd
	    checkremove=1
	    if [ "${fd:0:2}" = "hd" ]; then
		checkcdrom=1
		checkhdx=1
	    fi
	    break
	else
	    plet=
	    if [ "${fd:0:4}" = "nvme" ]; then plet="p"; fi
	    for part in {1..63}   # max of 63 partitions on sdx/nvmex/hdx devices (check that)
	    do
		fdtotal=$fd$plet$part
		if [ "$1" = "/dev/$fdtotal" ]; then
		    device=$fdtotal
		    wdevice=$fd
		    partition=1
		    break
		fi
	    done
	    if [ ! "$device" = "0" ]; then break; fi
	fi
    done
fi

# show usage if command line error or device not supported
if [ "$device" = "0" ] || [ "$synerror" != "0" ]; then
    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
    echo
    if [ "$runmode" = "running" ] && [ "$synerror" = "2" ]; then
	echo "ERROR: The /c and /nn options are not supported in this mode"
	echo
    elif [ "$runmode" = "distro" ] && [ "$synerror" = "2" ]; then
	echo "ERROR: The /doini option is not supported in this mode"
	echo
    elif [ "$synerror" = "3" ]; then
	echo "ERROR: The /r option is not supported in this mode"
	echo
    elif [ "$synerror" = "4" ]; then
	echo "ERROR: The /c, /nn, and /doini options cannot be used with /r"
	echo
    fi

    if [ "$runmode" = "distro" ]; then
	echo "Usage:  ./makeHDD /dev/sdx[y] [/a] [/mbr] [/c] [/nn] [/nf] [/r]"
    else
	echo "Usage:  makeHDD /dev/sdx[y] [/a] [/mbr] [/doini] [/nf] [/r]"
    fi
    echo "  x      - letter repesenting a specific drive (e.g. sdb)"
    echo "  y      - number representing a specific partition (e.g. sdb2)"
    echo "  /mbr   - write standard MBR to drive containing target partition"
    echo "  /a     - set the target partition active"
    if [ "$runmode" = "distro" ]; then
	echo "  /c     - create custom version"
	echo "  /nn    - create non-network version (smaller size)"
	echo "  /nf    - do not re-format partition (FAT16, FAT32 only)"
    elif [ "$runmode" = "running" ]; then
    	echo "  /doini - copy custom MakeDisk files (if any) into rootfs"
    	echo "  /nf    - do not format partition (FAT16, FAT32 only)"
    fi
    if [ -d cdboot ]; then
	echo "  /r     - create restore media on drive or partition"
    fi
    echo
    echo "Usage examples:"
    if [ "$runmode" = "distro" ]; then
	echo "./makeHDD /dev/sdc          -> install default version to entire drive sdc"
	echo "./makeHDD /dev/sdc2         -> install to partition sdc2 on drive sdc"
	echo "./makeHDD /dev/sdc2 /a /mbr -> also install MBR to sdc and set sdc2 active"
	echo "./makeHDD /dev/sda3 /c      -> install customized version to partition sda3"
	echo "./makeHDD /dev/sda3 /nn     -> install non-network version to sda3"
    else
	echo "makeHDD /dev/sdc           -> install to entire drive sdc"
	echo "makeHDD /dev/sdc2          -> install to partition sdc2 on drive sdc"
	echo "makeHDD /dev/sdc2 /a /mbr  -> also install MBR to sdc and set sdc2 active"
	echo "makeHDD /dev/sdc2 /doini   -> install to sdc2 & copy MakeDisk files into rootfs"
    fi
    echo
    exit 1
fi

# check that device exists and do other checks based on drive vs partition
if [ "$partition" = "0" ]; then 	#installing to whole drive
    if [ ! -e /sys/block/$device ]; then
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo "Device /dev/$device was not detected on this system...exiting"
	if [ "$runmode" = "running" ]; then
	    echo
	    echo "Note: You can run 'listhw' to list all drives detected by Linux,"
	    echo "and 'fdisk -l' to list all partitions on all drives."
	fi
	echo
	exit 1 
    fi
    if [ "$checkremove" = "1" ]; then
	remov=`cat /sys/block/$device/removable`
	if [ "$remov" = "0" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Device /dev/$device is not a removable drive...exiting"
	    echo
	    exit 1
	fi
    fi
    if [ "$checkcdrom" = "1" ] && [ -e /sys/block/$device/device/media ]; then
	cdrom=`cat /sys/block/$device/device/media`
	if [ "$cdrom" = "cdrom" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Device /dev/$device is a CD/DVD drive...exiting"
	    echo
	    exit 1
	fi
    fi
    if [ "$checkhdx" = "1" ]; then
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo "Device /dev/$device represents an entire drive. For hdx drives,"
	echo "this script will only install to a partition...exiting"
	echo
	exit 1
    fi
else 	#installing to partition
    if [ ! -e /sys/block/$wdevice/$device ]; then
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo "Device /dev/$device was not detected on this system...exiting"
	if [ "$runmode" = "running" ]; then
            echo
            echo "Note: You can run 'listhw' to list all drives detected by Linux,"
	    echo "and 'fdisk -l' to list all partitions on all drives."
        fi
	echo
	exit 1
    fi
    # check for GPT - not supported for installing to a partition for now
    # read 1st 8 bytes of LBA 1 - should be "EFI PART" if GPT exists
    # check for disk sector sizes of both 512 and 4096 bytes
    for ssize in 512 4096
    do
	dd if=/dev/$wdevice of=/tmp/tmpfile bs=1 count=8 skip=$ssize 2> /dev/null
	a=`cat /tmp/tmpfile`; rm /tmp/tmpfile 2> /dev/null
	if [ "$a" = "EFI PART" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Drive /dev/$wdevice is a GPT disk containing a GUID partition table."
	    echo "makeHDD currently does not support installing to a partition on GPT"
	    echo "disks...exiting"
	    echo
	    exit 1
	fi
    done
fi

# Note: syslinux won't install to FAT32 partition if < 32 MiB
# Min size for partitions = 64 MiB as of v267
minsize=131072
minsizetext="64 MiB"
# Min size for UFD = 64 MiB (entire drive) as of v267
minsizeUFD=131072
minsizeUFDtext="64 MiB"
# Max size removable drive to install to entire drive as of v267
# maxsizeremovable=134217728
maxsizeremovable=268435456

let maxdisplay=$maxsizeremovable*512
# let maxdisplay=$maxdisplay/1048576
let maxdisplay=$maxdisplay/1073741824
maxdisplay="$maxdisplay GiB"

# get drive/partition size & set up variable to display in human readable manner
dsize=`cat /sys/block/$wdevice/size`
let dsizedisplay=dsize*512
let dsizedisplay=dsizedisplay/1024
let dsizedisplay=dsizedisplay/1024
if [ "$dsizedisplay" -lt "102400" ]; then
    dsizedisplay="$dsizedisplay MiB"
else
    let dsizedisplay=dsizedisplay/1024
    dsizedisplay="$dsizedisplay GiB"
fi
if [ "$partition" = "1" ]; then
    psize=`cat /sys/block/$wdevice/$device/size`
    let psizedisplay=psize*512
    let psizedisplay=psizedisplay/1024
    let psizedisplay=psizedisplay/1024
    if [ "$psizedisplay" -lt "102400" ]; then 
	psizedisplay="$psizedisplay MiB"
    else
	let psizedisplay=psizedisplay/1024
	psizedisplay="$psizedisplay GiB"
    fi
fi

# check that sfdisk is available, exit if not
sfdiskpath=`which sfdisk 2> /dev/null`
if [ "$?" != "0" ]; then
    echo "Required file sfdisk (typically /sbin/sfdisk) not found on the system...exiting"
    echo
    exit 1
fi

# check that blockdev (usually /sbin/blockdev) is available, exit if not
blockdevpath=`which blockdev 2> /dev/null`
if [ "$?" != "0" ]; then
    echo "Required file blockdev (typically /sbin/blockdev) not found on the system."
    echo "This can be usually be corrected by installing the util-linux package."
    echo "Exiting script..."
    echo
    exit 1
fi

# if partition, get the partition type with sfdisk and then do some checks
if [ "$partition" = "1" ]; then  
    # first check that util/sig.bin exists (used to write 55AA)
    if [ ! -e $util/sig.bin ]; then
	echo "Required file $util/sig.bin not found...exiting"
	echo
	exit 1
    fi
    # get partition type - if sfdisk gives error, write sig and try again
    # ptype=`$sfdiskpath --id --force /dev/$wdevice 1 2> /dev/null` (check for gpt disk - part 1 = type 55h)
    ptype=`$sfdiskpath --force --id /dev/$wdevice $part 2> /dev/null`
    if [ ! "$?" = "0" ]; then
	dd if=$util/sig.bin of=/dev/$wdevice bs=1 count=2 seek=510
	ptype=`$sfdiskpath --force --id /dev/$wdevice $part 2> /dev/null`
	if [ ! "$?" = "0" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Problem with partition table on /dev/$wdevice was reported by sfdisk"
	    echo "Run the command 'sfdisk --id /dev/$wdevice $part' to see the error"
	    echo
	    exit 1
	fi
    fi
    ptype=${ptype// /}    
    # check for supported partition type and minimum size
    if [ "$ptype" = "6" ] || [ "$ptype" = "e" ]; then  # FAT16
	ptypedisplay=FAT16
	if [ "$psize" -lt "$minsize" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Device /dev/$device is a $psizedisplay $ptypedisplay partition"
	    echo "Minimum size required for a FAT16 partition is $minsizetext...exiting"
	    echo
	    exit 1
	elif [ "$nf" = "1" ]; then
	    formatted=0
	    blkid | grep "/dev/$device:" > /dev/null
            if [ "$?" = "0" ]; then
        	for fs in vfat msdos
                do
		    blkid /dev/$device | grep " TYPE=\"$fs\"" > /dev/null
                    if [ "$?" = "0" ]; then
			formatted=1
			break
		    fi
		done
	    fi
	    if [ "$formatted" = "0" ]; then
		echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
		echo
		echo "The /nf option (no format) was specified on the command line, but dev/$device"
		echo "is not formatted. The /nf option can only be used on an already formatted"
		echo "partition...exiting"
		echo
		exit 1
	    fi
	fi
    elif [ "$ptype" = "b" ] || [ "$ptype" = "c" ]; then  # FAT32
	ptypedisplay=FAT32
	if [ "$psize" -lt "$minsize" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Device /dev/$device is a $psizedisplay $ptypedisplay partition"
	    echo "Minimum size required for a FAT32 partition is $minsizetext...exiting"
	    echo
	    exit 1
	elif [ "$nf" = "1" ]; then
	    formatted=0
	    blkid | grep "/dev/$device:" > /dev/null
            if [ "$?" = "0" ]; then
        	for fs in vfat msdos
                do
		    blkid /dev/$device | grep " TYPE=\"$fs\"" > /dev/null
                    if [ "$?" = "0" ]; then
			formatted=1
			break
		    fi
		done
	    fi
	    if [ "$formatted" = "0" ]; then
		echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
		echo
		echo "The /nf option (no format) was specified on the command line, but dev/$device"
		echo "is not formatted. The /nf option can only be used on an already formatted"
		echo "partition...exiting"
		echo
		exit 1
	    fi
	fi
    elif [ "$ptype" = "83" ]; then  # Linux
	ptypedisplay=Linux
	# can't boot from volume if Linux (due to extlinux boot loader not supporting it)
	if [ "$part" -gt "4" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Device /dev/$device is a Linux volume inside an extended partition. Because"
	    echo "the extlinux boot loader does not support booting from extended/logical"
	    echo "volumes, this script will only install to primary Linux partitions...exiting"
	    echo
	    exit 1 
	fi
	if [ "$psize" -lt "$minsize" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Device /dev/$device is a $psizedisplay $ptypedisplay partition"
	    echo "Minimum size required for a Linux partition is $minsizetext...exiting"
	    echo
	    exit 1
	fi
	#############################################################################################################
	# remove this block if/when it becomes OK to nf ext2/3/4 (tbosdt mount 0: /dev/sdxy) with extlinux installed)
	if [ "$nf" = "1" ]; then
            echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
            echo 
            echo "The /nf (no format) option is not supported for Linux partitions...exiting"
            echo 
	    exit 1
	fi
	#############################################################################################################
	if [ "$nf" = "1" ]; then
	    formatted=0
	    blkid | grep "/dev/$device:" > /dev/null
            if [ "$?" = "0" ]; then
        	for fs in ext2 ext3 ext4
                do
		    blkid /dev/$device | grep " TYPE=\"$fs\"" > /dev/null
                    if [ "$?" = "0" ]; then
			formatted=1
			break
		    fi
		done
	    fi
	    if [ "$formatted" = "0" ]; then
		echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
		echo
		echo "The /nf option (no format) was specified on the command line, but dev/$device"
		echo "is not formatted with ext2/3/4. The /nf option cannot be used on Linux"
		echo "partitions unless they are already formatted with ext2/3/4"
		echo
		exit 1
	    fi
	fi
    elif [ "$ptype" = "5" ] || [ "$ptype" = "f" ]; then  # extended partition
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo "Device /dev/$device is an extended partition...exiting"
	echo
	exit 1 
    elif [ "$ptype" = "df" ]; then  # BootItBM type partition
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo "Device /dev/$device is a type df (BootItBM) partition. Installing IFL to this"
	echo "partition type is not supported because its boot record would be overwritten"
	echo "each time BootItBM is updated, disabling the IFL boot code."
	echo
	echo "To have BootItBM and IFL share a partition, use a FAT16 or FAT32 partition,"
	echo "and ensure that it's large enough to hold both. A 100 MiB minimum size is"
	echo "recommended...exiting"
	echo
	exit 1
    else 	# anything else is not valid
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo "Device /dev/$device is a type $ptype partition. The target partition must"
	echo "be FAT16, FAT32, or Linux Native (type 83)...exiting"
	echo
	exit 1
    fi
    # if installing to logical volume, the /a option does not apply
    if [ "$active" = "1" ] && [ "$partition" = "1" ]; then
	if [ "$part" -gt "4" ]; then
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "The /a option was given, but /dev/$device cannot be set active because"
	    echo "it is not a primary partition."
	    echo
	    echo "It is still possible to install to this partition, but the /a option"
	    echo "cannot be used. Installing to this partition will require the use of a"
	    echo "boot manager that is capable of booting from an extended/logical volume."
	    echo "Note: BootIt BM from TeraByte Unlimited has this capability."
	    echo
	    exit 1 
	fi
    fi
fi

# if whole drive check size, see if it is partitioned, and if any partitions mounted
if [ "$partition" = "0" ]; then
    if [ "$dsize" -lt "$minsizeUFD" ]; then  # check min size (32 MB)
	    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	    echo
	    echo "Device /dev/$device is a $dsizedisplay drive. Minimum drive size"
	    echo "required is $minsizeUFDtext...exiting"
	    echo
	    exit 1
    fi
    
    # commented out this section - currently not limiting size of removable drive (UFD)
    #if [ "$dsize" -gt "$maxsizeremovable" ]; then  # check max size for removable (8 GB)
    #	    echo "Command line entered: $0 $1 $2 $3 $4"
    #	    echo
    #	    echo "Device /dev/$device is a removable drive, but it's size is $dsizedisplay. For"
    #	    echo "data safety reasons, this script will not install to a drive larger"
    #	    echo "than $maxdisplay unless installing to a partition...exiting"
    #	    echo
    #	    exit 1
    #fi
    
    
    # check if the drive is partitoned - exit if any are mounted
    # warn user that installing to partitioned drive will cause all partitions will be lost
    plet=
    if [ "${wdevice:0:4}" = "nvme" ]; then plet="p"; fi
    for i in `seq 1 63`
    do
	if [ -e /sys/block/$wdevice/$wdevice$plet$i ]; then
	    partitioned=1
	    break
	else
	    partitioned=0
	fi
    done
    # check if any partition on drive is mounted
    if [ "$partitioned" = "1" ]; then
	for i in `seq 1 64`
	do
	    mdisk=`mount | grep /dev/$device$plet$i > /dev/null`
	    if [ "$?" = "0" ]; then
		echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
		echo
		echo "Drive /dev/$device contains 1 or more PARTITIONS that are currently MOUNTED."
		echo "All partitions on /dev/$device must be unmounted before installing to this drive."
		echo
		echo "Since drive /dev/$device does contain partitions, please be sure that your"
		echo "intent is to install to the drive, rather than to a partition on the drive."
		echo "WARNING: Installing to /dev/$device will cause ALL data on ALL partitions"
		echo "on that drive to be LOST, and ALL partitions will be DELETED...exiting"
		echo
		exit 1
	    fi
	done
    fi
    # if whole drive, then /mbr, /a, and /nf options don't apply
    if [ "$mbr" = "1" ] || [ "$active" = "1" ] || [ "$nf" = "1" ]; then
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo	
	echo "One or more of the /mbr, /a, or /nf options are in the command line, but none"
	echo "of these options apply unless installing to a partition...exiting"
	echo
	exit 1
    fi
fi

# check if target drive or partition is currently mounted
mdisk=`mount | grep "/dev/$device "> /dev/null`
if [ "$?" = "0" ]; then
    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
    echo
    echo "Device /dev/$device is currently MOUNTED."
    if [ "$partition" = "0" ]; then 
	echo "Please unmount the drive and then run 'makeHDD' again."
    else
	echo "Please unmount the partition and then run 'makeHDD' again."
    fi
    echo
    exit 1
fi


# check for necessary files, dependent on options and target type
echo "Checking for required files, directories"
m=0

modprobepath=`which modprobe 2> /dev/null`
if [ "$?" != "0" ]; then
    m=1
    echo "Required file modprobe (typically /sbin/modprobe) not found on the system"
fi

# from distro, always need iflnet.iso or ifl.iso
if [ "$runmode" = "distro" ]; then
    if [ ! -e iflnet.iso ] ; then
	m=1
	echo "File iflnet.iso not found in the IFL directory"
    fi
    if [ ! -e ifl.iso ] ; then
	m=1
	echo "File ifl.iso not found in the IFL directory"
    fi    
fi
if [ ! -d $util ]; then
    m=1
    echo "Directory $util was not found"
fi

# if hdd/tmp still there, make sure it's not mounted, if can't unmount, exit
if [ -d hdd/tmp ]; then
    mdisk=`mount | grep hdd/tmp > /dev/null`
    if [ "$?" = "0" ]; then
        umount hdd/tmp 2> /dev/null
        if [ "$?" != "0" ]; then        # try again
            sleep 1
            umount hdd/tmp 2> /dev/null
            if [ "$?" != "0" ]; then
                echo "Unable to unmount hdd/tmp from previous run...exiting"
                echo
                exit 1
            fi
        fi
    fi
fi

# clean up and recreate the hdd working directory
rm -r hdd 2> /dev/null
mkdir hdd

# if building custom version, need cpio, config.txt, unzip if lang versions, zcat
if [ "$custom" = "1" ]; then
    # check if util/cpio will execute (won't on 64 bit systems)
    # use /bin/cpio if it exists, otherwise exit
    while [ 0 ]; do
	if [ -x $util/cpio ]; then
	    ./util/cpio --help > /dev/null 2>&1
    	    if [ "$?" = "0" ]; then
        	cpiopath="../$util/cpio"
        	echo "Using included version of cpio"
        	break
    	    fi
	fi
	cpiopath=`which cpio 2> /dev/null`
	if [ "$?" != "0" ]; then
    	    m=1
    	    echo "Required file cpio (typically /bin/cpio) not found on system"
    	    break
	else
    	    cpioversion=`$cpiopath --version`
    	    echo "Using cpio version $cpioversion"
    	    break
	fi
    done
    if [ ! -e config.txt ]; then
	m=1
	echo "File config.txt not found in the IFL directory"
    fi
    # check for unzip if any language files present (other than ifl_en.zip)
    nlangfiles=`ls ifl_*.zip 2> /dev/null | grep -c ifl`
    if [ "$nlangfiles" != "0" ]; then
	zipcheck=1
	if [ "$nlangfiles" = "1" ] && [ -f ifl_en.zip ]; then zipcheck=0; fi
	if [ "$nlangfiles" = "1" ] && [ -f ifl_en_trial.zip ]; then zipcheck=0; fi
	if [ "$nlangfiles" = "1" ] && [ -f ifl_en_gui.zip ]; then zipcheck=0; fi
	if [ "$nlangfiles" = "1" ] && [ -f ifl_en_gui_trial.zip ]; then zipcheck=0; fi
	if [ "$zipcheck" = "1" ]; then
    	    unzippath=`which unzip 2> /dev/null`
    	    if [ ! "$?" = "0" ]; then
        	m=1
        	echo "Required program unzip not found on system. This can usually be corrected"
        	echo "by installing the unzip package."
    	    fi
	fi
    fi
    # check for zcat
    zcatpath=`which zcat 2> /dev/null`
    if [ ! "$?" = "0" ]; then
	m=1
	echo "Required program zcat (typically /bin/zcat) not found on system."
    fi
fi    

# if setting partition active, need active.bin
if [ "$active" = "1" ] && [ ! -e $util/active.bin ]; then
    m=1
    echo "File $util/active.bin not found"
fi

# if installing mbr, need mbr.bin
if [ "$mbr" = "1" ] && [ ! -e $util/mbr.bin ]; then
    m=1
    echo "File $util/mbr.bin not found"
fi

# if Linux partition need extlinux/mke2fs
if [ "$partition" = "1" ] && [ "$ptype" = "83" ]; then
    if [ "$runmode" = "running" ]; then
	mke2fspath=mke2fs
    else
	mke2fspath=`which mke2fs 2> /dev/null`
	if [ "$?" != "0" ]; then
	    if [ -x /sbin/mke2fs ]; then
		mke2fspath=/sbin/mke2fs
	    elif [ -x /usr/sbin/mke2fs ]; then
	        mke2fspath=/usr/sbin/mke2fs
	    else
		m=1    
		echo "File mke2fs (typically /sbin/mke2fs) not found on the system"
		echo "This file is part of the e2fsprogs package, which is usually"
		echo "installed by default on most distros"
	    fi
	fi
    fi
    # check for installed version of extlinux, and if not, use included version based on 32 or 64 bit kernel
    # if included version won't run (based on 'ldd'), exit with message to install distro package
    if [ "$runmode" = "running" ]; then
	extlinuxpath=extlinux
    else    
	while [ 0 ]; do
	    uname -a | grep x86_64 > /dev/null
	    if [ "$?" = "0" ]; then bitness=64; else bitness=32; fi
	    # use installed version of extlinux if available
	    extlinuxpath=`which extlinux 2> /dev/null`
	    if [ "$?" != "0" ]; then
		if [ -x /sbin/extlinux ]; then
		    extlinuxpath=/sbin/extlinux
		    echo "Using distro $bitness bit version of extlinux"
    		    break
		elif [ -x /usr/sbin/extlinux ]; then
		    extlinuxpath=/usr/sbin/extlinux
		    echo "Using distro $bitness bit version of extlinux"
    		    break
		fi
	    else
    		echo "Using distro $bitness bit version of extlinux"
    		break
	    fi
	    # not installed in distro - try to use included version
	    if [ "$bitness" = "64" ]; then
		extlinuxpath="util/extlinux-64"
		extlinuxpathtext="Using included 64 bit version of extlinux"
	    else 
		extlinuxpath="util/extlinux"
		extlinuxpathtext="Using included 32 bit version of extlinux"
	    fi
    	    ldd $extlinuxpath > /dev/null
    	    if [ "$?" = "0" ]; then
		echo $extlinuxpathtext
        	break
	    # included versions don't run - prompt for user to install disto version
    	    else
		m=1
    		echo "Required file extlinux (typically /usr/bin/extlinux) not found on the system."
		echo "This can be corrected by installing either the 'syslinux' package. For some"
		echo "distros it may be in a separate 'extlinux' package"
    		break
	    fi
	done
    fi
else	# FATxx partition OR entire drive, need mkdosfs, mcopy, and syslinux
    if [ "$runmode" = "running" ]; then
	mkdosfspath=mkdosfs
    else    
	mkdosfspath=`which mkdosfs 2> /dev/null`
	if [ "$?" != "0" ]; then
	    if [ -x /sbin/mkdosfs ]; then
		mkdosfspath=/sbin/mkdosfs
	    elif [ -x /usr/sbin/mkdosfs ]; then
		mkdosfspath=/usr/sbin/mkdosfs
	    else
		m=1
    		echo "Required file mkdosfs (typically /sbin/mkdosfs) not found on system"
		echo "This can be corrected by installing the dosfstools package"
	    fi
	fi
    fi
    # mcopy is required by syslinux (fails w/o it)
    if [ "$runmode" = "running" ]; then
	mcopypath=mcopy
    else    
	mcopypath=`which mcopy 2> /dev/null`
	if [ "$?" != "0" ]; then
	    if [ -x /sbin/mcopy ]; then
		mcopypath=/sbin/mcopy
	    elif [ -x /usr/sbin/mcopy ]; then
		mcopypath=/usr/sbin/mcopy
	    else
		m=1
    		echo "Required file mcopy (typically /usr/bin/mcopy) not found on system"
		echo "This can be corrected by installing the mtools package"
	    fi
	fi
    fi
    # check for installed version of syslinux, and if not, use included version based on 32 or 64 bit kernel
    # if included version won't run (based on 'ldd'), exit with message to install distro package
    if [ "$runmode" = "running" ]; then
	syslinuxpath=syslinux
    else    
	while [ 0 ]; do
	    uname -a | grep x86_64 > /dev/null
	    if [ "$?" = "0" ]; then bitness=64; else bitness=32; fi
	    # use installed version of syslinux if available
	    syslinuxpath=`which syslinux 2> /dev/null`
	    if [ "$?" != "0" ]; then
		if [ -x /sbin/syslinux ]; then
		    syslinuxpath=/sbin/syslinux
		    echo "Using distro $bitness bit version of syslinux"
    		    break
		elif [ -x /usr/sbin/syslinux ]; then
		    syslinuxpath=/usr/sbin/syslinux
		    echo "Using distro $bitness bit version of syslinux"
    		    break
		fi
	    else
    		echo "Using distro $bitness bit version of syslinux"
    		break
	    fi
	    # not installed in distro - try to use included version
	    if [ "$bitness" = "64" ]; then
		syslinuxpath="util/syslinux-64"
		syslinuxpathtext="Using included 64 bit version of syslinux"
	    else 
		syslinuxpath="util/syslinux"
		syslinuxpathtext="Using included 32 bit version of syslinux"
	    fi
    	    ldd $syslinuxpath > /dev/null
    	    if [ "$?" = "0" ]; then
		echo $syslinuxpathtext
        	break
	    # included versions don't run - prompt for user to install disto version
    	    else
		m=1
		echo "Required file syslinux (typically /usr/bin/syslinux) not found on system"
		echo "This can be corrected by installing the 'syslinux' package"
    		break
	    fi
	done
    fi
    # check if --install required by this version
    if [ "$m" = "0" ]; then
	$syslinuxpath --help 2>&1 | grep -- --install > /dev/null
	if [ "$?" = "0" ]; then
	    syslinuxopt="--install"
	else 
	    syslinuxopt="" 
	fi
	echo "syslinux install option: $syslinuxopt"
    fi
fi

if [ "$m" = "0" ]; then
    echo "All required files and directories were found"
else
    echo
    echo "One or more required files or directories were not found."
    echo "See above messages for details...exiting"
    echo
    exit 1
fi

clear
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "     The makeHDD script to install to hard drive or UFD - TeraByte, Inc."
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo
#######################################begin confirm####################################
vendor=`cat /sys/block/$wdevice/device/vendor 2> /dev/null`
model=`cat /sys/block/$wdevice/device/model 2> /dev/null`
model=$(echo $model)
vendor=$(echo $vendor)
if [ "$nocfm" = "0" ]; then
    # get confirmation to write to device 
    if [ "$partition" = "0" ] && [ "$partitioned" = "1" ]; then
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo "Install Target: DRIVE /dev/$device  ($dsizedisplay  $vendor $model)"
	echo
	echo "WARNING: Device /dev/$device represents an ENTIRE drive, and it currently"
	echo "contains one or more PARTITIONS."
	echo
	echo "Installing to /dev/$device will cause ALL partitions and data currently on"
	echo "/dev/$device to be LOST. ALL partitions will be DELETED. If this is not what"
	echo "you want to do, decline the confirmation below."
	echo
	echo -n "To install to /dev/$device, please confirm by typing 'yes': "
	read yn
	if [ ! "$yn" = "yes" ]; then
	    echo "Install to /dev/$device not confirmed...exiting"
	    echo
	    exit 1
	else
	    echo
	    echo "2nd WARNING: Target drive /dev/$device currently contains one or more"
	    echo "PARTITIONS. Installing to /dev/$device will cause the loss of ALL data"
	    echo "and ALL partitions currently on the drive."
	    echo
	    echo -n "Please confirm again by typing 'yes': "
	    read yn
	    if [ ! "$yn" = "yes" ]; then
		echo "Install to /dev/$device not confirmed...exiting"
		echo
		exit 1
	    else
		echo "Install to /dev/$device confirmed twice"
	    fi
	fi 
    else
	echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
	echo
	echo -n "Install Target: "
	if [ "$partition" = "1" ]; then
	    echo "PARTITION /dev/$device  ($psizedisplay, $ptypedisplay)"
	    echo "The partition is on DRIVE /dev/$wdevice ($dsizedisplay  $vendor $model)"
	    if [ "$nf" = "0" ]; then
		echo
		echo "WARNING: ALL data on partition /dev/$device will be LOST"
	    else
		echo
		echo "NOTE: Partition /dev/$device will NOT be re-formatted (/nf option)"
	    fi
	else
	    echo "DRIVE /dev/$device  ($dsizedisplay  $vendor $model)"
	    echo
	    echo "WARNING: ALL data on drive /dev/$device will be LOST"
	fi
	echo "To back out, decline the confirmation below"
	echo
	echo -n "To install to /dev/$device, please confirm by typing 'yes': "
	read yn
	if [ ! "$yn" = "yes" ]; then
	    echo "Install to /dev/$device not confirmed...exiting"
	    echo
	    exit 1
	else
	    echo "Install to /dev/$device confirmed"
	fi 
    fi
else
    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
    echo
    echo -n "Install Target: "
    if [ "$partition" = "1" ]; then
	echo "PARTITION /dev/$device  ($psizedisplay, $ptypedisplay)"
	echo "The partition is on DRIVE /dev/$wdevice ($dsizedisplay  $vendor $model)"
	echo
	echo "WARNING: ALL data on partition /dev/$device will be LOST"
    else
	echo "DRIVE /dev/$device  ($dsizedisplay  $vendor $model)"
	echo
    fi
fi
#######################################end confirm######################################

# name of boot loader config file depends on whether using syslinux or extlinux
if [ "$partition" = "1" ] && [ "$ptype" = "83" ]; then
    cfile=extlinux.conf
else
    cfile=syslinux.cfg
fi


if [ "$rest" != "1" ]; then ############################################################


# clean up and  then create the cdpath directory where ISO or disc gets mounted
# cdpath=cdrom/cdrom
cdpath=cdroot
rm -r $cdpath 2> /dev/null
mkdir -p $cdpath

# get files from ISO or CD/DVD
if [ "$runmode" = "distro" ]; then
    # use tbosdt to copy contents of ISO file to $cdpath (cdroot)
    if [ "$netsupport" = "0" ]; then
	echo "mount 0: ifl.iso" > getiflfiles.run
	echo "copy 0: cdroot -s -q" >> getiflfiles.run
	$tbosdtpath getiflfiles.run
	rm getiflfiles.run
    else
	echo "mount 0: iflnet.iso" > getiflnetfiles.run
	echo "copy 0: cdroot -s -q" >> getiflnetfiles.run
	$tbosdtpath getiflnetfiles.run
	rm getiflnetfiles.run
    fi
else
    echo
    echo
    echo "An IFL Boot CD/DVD or UFD is required as the SOURCE to copy files from."
    echo
    echo "IMPORTANT NOTE: The source can be either a CD/DVD or a UFD that has IFL"
    echo "installed on it. Both the source and the target can be UFDs, but they "
    echo "cannot be the same one. The target UFD, as specified on the command line"
    echo "above, will not be selected as the source"
    echo
    echo "Please insert the source CD/DVD or UFD now (if not already inserted)."
    echo -n "Press <Enter> when ready: "
    read cdready
    $util/mountiflcd /makeHDD $wdevice
    if [ "$?" != "0" ]; then
	echo "A valid source IFL Boot CD/DVD or UFD was not found. Exiting script"
	echo
	exit 1
    fi
    netstatus=`grep -c Network $cdpath/menu.txt 2> /dev/null`
    if [ "$netstatus" = "1" ]; then
	volname=iflnet
    else
	volname=ifl
    fi
fi

if [ "$custom" = "0" ]; then
    if [ "$runmode" = "distro" ]; then 
	if [ "$netsupport" = "1" ]; then
	    echo "Building default full version with network support"
	else
	    echo "Building default smaller version with no network support"
	fi
    else
	echo "Using makeHDD copy mode to copy existing IFL boot media to /dev/$device"
    fi

    # copy the files from the source (either isofile or mounted IFL boot disk)
    for fname in boot disk efi private scripts vmlinuz initrmfs.gz menu.txt qwerty.ktl dvorak.ktl azerty.ktl qwertz.ktl fgGIod.ktl scripts.conf
    do
	cp -a $cdpath/$fname hdd 2> /dev/null
    done
    for fname in IFL.INI ifl.ini
    do
	cp $cdpath/$fname hdd/ifl.ini 2> /dev/null
    done
    for fname in  BOOTITBM.INI bootitbm.ini
    do
	cp $cdpath/$fname hdd/BOOTITBM.INI 2> /dev/null
    done
    # when copying boot loader config file, look for iflbflag set to 2 or 3, which indicates custom ifl.ini by makedisk
    # syslinux.cfg can be upper case if source is UFD created by makedisk
    foundmakedisk=0
    for fname in isolinux.cfg syslinux.cfg SYSLINUX.CFG extlinux.conf
    do
	if [ -f $cdpath/$fname ]; then
	    cp $cdpath/$fname hdd/$fname
	    # set all instances of iflbflag variable to 0, which it may already be
	    grep "iflbflag=2 " hdd/$fname > /dev/null 2>&1
	    if [ "$?" = "0" ];then foundmakedisk=2; fi
	    grep "iflbflag=21 " hdd/$fname > /dev/null 2>&1
	    if [ "$?" = "0" ];then foundmakedisk=21; fi
	    grep "iflbflag=3 " hdd/$fname > /dev/null 2>&1
	    if [ "$?" = "0" ];then foundmakedisk=3; fi
	    grep "iflbflag=31 " hdd/$fname > /dev/null 2>&1
	    if [ "$?" = "0" ];then foundmakedisk=31; fi

	    # if doing /doini set iflbflag to 0 becuase the makedisk files will be copied into the rootfs
	    if [ "$doini" = "1" ]; then
		case $foundmakedisk in
		0)
		    ;;
		2)
		    sed -i -e 's/iflbflag=2 /iflbflag=0 /' hdd/$fname
		    sed -i -e 's/iflbflag=2 /iflbflag=0 /' hdd/boot/grub/grub.cfg;;
		3)
		    sed -i -e 's/iflbflag=3 /iflbflag=0 /' hdd/$fname
		    sed -i -e 's/iflbflag=3 /iflbflag=0 /' hdd/boot/grub/grub.cfg;;
		21)
		    sed -i -e 's/iflbflag=21 /iflbflag=0 /' hdd/$fname
		    sed -i -e 's/iflbflag=21 /iflbflag=0 /' hdd/boot/grub/grub.cfg;;
		31)
		    sed -i -e 's/iflbflag=31 /iflbflag=0 /' hdd/$fname
		    sed -i -e 's/iflbflag=31 /iflbflag=0 /' hdd/boot/grub/grub.cfg;;
		*)
		    ;;
		esac
	    # if not, make sure that "2" values get changed to "3" (copying from optical disk created by makedisk)
	    else
		case $foundmakedisk in
		0)
		    ;;
		2)
		    sed -i -e 's/iflbflag=2 /iflbflag=3 /' hdd/$fname
		    sed -i -e 's/iflbflag=2 /iflbflag=3 /' hdd/boot/grub/grub.cfg;;
		21)
		    sed -i -e 's/iflbflag=21 /iflbflag=31 /' hdd/$fname
		    sed -i -e 's/iflbflag=21 /iflbflag=31 /' hdd/boot/grub/grub.cfg;;
		*)
		    ;;
		esac
	    fi
	    break
	fi
    done
    # ensure syslinux.cfg is lower case, so that it gets copied to target in copy_tbosdt function below
    if [ -f hdd/SYSLINUX.CFG ]; then mv hdd/SYSLINUX.CFG hdd/syslinux.cfg; fi
    # finished with $cdpath temp directory - can be deleted
    rm -r $cdpath 2> /dev/null

    # If source created by makedisk (iflbflag = 2,21,3,31), then foundmakedisk != 0
    # If /doini option is used, then copy makedisk files into the rootfs
    # (decompress initrmfs.gz, copy files, recompress initrmfs.gz)
    # Otherwise makedisk files (if any) will be copied to the root of target drive/partition

    memerror=0
    if [ "$foundmakedisk" != "0" ] && [ "$doini" = "1" ]; then
	echo "Copying makedisk files & directories into rootfs (per /doini option)"
	echo "  Decompressing the rootfs"
	rm -r initrmfs 2> /dev/null
	mkdir initrmfs
	cd initrmfs
	/bin/zcat ../hdd/initrmfs.gz | /bin/cpio -i -m -d
	if [ "$?" != "0" ]; then memerror=1; fi
	cd ..
	if [ "$memerror" = "0" ]; then
	    rm hdd/initrmfs.gz 2> /dev/null
	    if [ -f hdd/ifl.ini ]; then
		echo "  Copying ifl.ini from source boot media to rootfs"
		cp hdd/ifl.ini initrmfs/tbu/ifl.ini
		while read line || [ -n "$line" ]
		do
		    echo $line >> initrmfs/tbu/ifltmp.ini
		done < "initrmfs/tbu/ifl.ini"
		mv initrmfs/tbu/ifltmp.ini initrmfs/tbu/ifl.ini
		chmod 644 initrmfs/tbu/ifl.ini
	    fi
	    if [ -d hdd/scripts ]; then
		echo "  Copying scripts directory from source boot media to rootfs"
		mkdir -p initrmfs/tbu/scripts
		cp hdd/scripts/* initrmfs/tbu/scripts 2> /dev/null
	    fi
	    if [ -f initrmfs/tbu/utility/priv ]; then
		echo "  Copying files in private directory from source boot media to rootfs"
		if [ -f hdd/private/oembackground.png ]; then
		    cp hdd/private/oembackground.png initrmfs/usr/share/pixmaps/ifl_background.png 2> /dev/null
		    chmod 644 initrmfs/usr/share/pixmaps/ifl_background.png
		    chown 0:0 initrmfs/usr/share/pixmaps/ifl_background.png
		fi
		if [ -f hdd/private/oemleft.png ]; then
		    cp hdd/private/oemleft.png initrmfs/tbu/iflleft.png 2> /dev/null
		    chmod 644 initrmfs/tbu/iflleft.png
		    chown 0:0 initrmfs/tbu/iflleft.png
		fi
	    fi
	    if [ -f hdd/scripts.conf ]; then
		a=`cat hdd/scripts.conf`
        	if [ "$a" != "" ] && [ "$a" != " " ]; then
		    echo "  Copying scripts.conf from source boot media to rootfs"
		    cp hdd/scripts.conf initrmfs/tbu/utility/iflscript 2> /dev/null
		    chmod 644 initrmfs/tbu/utility/iflscript 2> /dev/null
		    chown 0:0 initrmfs/tbu/utility/iflscript 2> /dev/null
		    fromdos initrmfs/tbu/utility/iflscript 2> /dev/null
		fi
	    fi
	    if [ -f hdd/bootitbm.ini ] || [ -f hdd/BOOTITBM.INI ]; then
		echo "  Copying BOOTITBM.INI from source boot media to rootfs"
		if [ -f hdd/bootitbm.ini ]; then
		    cp hdd/bootitbm.ini initrmfs/tbu/BOOTITBM.INI 2> /dev/null
        	elif [ -f hdd/BOOTITBM.INI ]; then
		    cp hdd/BOOTITBM.INI initrmfs/tbu/BOOTITBM.INI 2> /dev/null
        	fi
        	chmod 644 initrmfs/tbu/BOOTITBM.INI 2> /dev/null
        	chown 0:0 initrmfs/tbu/BOOTITBM.INI 2> /dev/null
	    fi

	    cd initrmfs
	    echo "  Recompressing the rootfs...please wait"
	    find . -print | /bin/cpio -o -a -H newc > ../hdd/initrmfs
	    if [ "$?" != "0" ]; then let memerror=1; fi
	    cd ..
	    rm -r initrmfs 2> /dev/null
	    gzip -9 hdd/initrmfs
	    if [ "$?" != "0" ]; then let memerror=1; fi
	fi

	if [ "$memerror" != "0" ]; then
	    rm -r hdd 2> /dev/null
	    echo
	    echo "ERROR detected, most likely caused by insufficient RAM."
	    echo
	    echo "The installation to /dev/$device has FAILED. Exiting script..."
	    echo
	    exit 1
	fi
    elif [ "$foundmakedisk" != "0" ]; then
	echo "Makedisk files will be copied to the root of /dev/$device"
    fi

    # if doing /doini (copying into rootfs) delete makedisk files in hdd dir so not copied to root of target disk
    if [ "$doini" = "1" ]; then
	for fname in scripts.conf # BOOTITBM.INI bootitbm.ini IFL.INI ifl.ini
	do
	    rm hdd/$fname 2> /dev/null
	done
	rm -r hdd/scripts 2> /dev/null
	rm -r hdd/private 2> /dev/null
    fi

else #################################################################
# clean up from possible failed run, then create temp dir
# probably need a couple more checks here

# echo "Copying contents of $isofile to build directory"
#cp -a $cdpath/* hdd/

    for fname in boot disk efi vmlinuz initrmfs.gz menu.txt qwerty.ktl dvorak.ktl azerty.ktl qwertz.ktl fgGIod.ktl
    do
	cp -a $cdpath/$fname hdd 2> /dev/null
    done
    for fname in IFL.INI ifl.ini
    do
	cp $cdpath/$fname hdd/ifl.ini 2> /dev/null
    done
    cp $cdpath/isolinux.cfg hdd/$cfile 2> /dev/null

sync
rm -r $cdpath 2> /dev/null

# decompress and extract root file system so that changes can be made
rm -r initrmfs 2> /dev/null
mkdir initrmfs
echo "Decompressing and extracting the root filesystem"
cd initrmfs
$zcatpath ../hdd/initrmfs.gz | $cpiopath -i -m -d
cd ..
rm hdd/initrmfs.gz 2> /dev/null

# check for unreg flag at /tbu/utility/ur to determine if reg or unreg version
if [ -f initrmfs/tbu/utility/ur ]; then reg=0; else reg=1; fi
# check for gui flag at /tbu/utility/gui to determine if gui version or not
if [ -f initrmfs/tbu/utility/gui ]; then gui=1; else gui=0; fi

# source config.txt to get options
chown $ownerid:$groupid config.txt
. config.txt

# set up settings directory if needed
if [ "$netsupport" = "1" ]; then
    if [ ! -d $util/settings ]; then mkdir $util/settings; fi
    if [ ! -d $util/settings/network ]; then mkdir $util/settings/network; fi
    settingspath="$util/settings"
else
    if [ ! -d $util/settings ]; then mkdir $util/settings; fi
    settingspath="$util/settings"
fi

# get settings from saved values, and copy ndiswrapper directory to root fs
cp $settingspath/* initrmfs/tbu/utility 2> /dev/null
if [ "$netsupport" = "1" ]; then
    rulesfile="70-persistent-net.rules"
    cp $settingspath/network/* initrmfs/etc/network 2> /dev/null
    mv initrmfs/etc/network/$rulesfile initrmfs/etc/udev/rules.d/$rulesfile 2> /dev/null
    if [ -d wireless/ndiswrapper ]; then
        cp -a wireless/ndiswrapper initrmfs/tbu/ndiswrapper
        chown -R 0:0 initrmfs/tbu/ndiswrapper/
    fi
fi

# copy scripts directory to root fs, ensure files are owned by root
if [ -d scripts ]; then
    # echo "Copying scripts directory to the root filesystem"
    cp -a scripts initrmfs/tbu/scripts
    chown -R 0:0 initrmfs/tbu/scripts/
fi

# take care of language settings in root fs
if [ "$gui" = "1" ]; then
    if [ "$reg" = "1" ]; then langfilefinish="_gui.zip"; else langfilefinish="_gui_trial.zip"; fi
elif [ "$gui" = "0" ]; then
    if [ "$reg" = "1" ]; then langfilefinish=".zip"; else langfilefinish="_trial.zip"; fi
fi
if [ -e initrmfs/tbu/utility/lang ]; then lang=`cat initrmfs/tbu/utility/lang`; else lang=""; fi
if [ -e initrmfs/tbu/utility/rdlang ]; then rdlang=`cat initrmfs/tbu/utility/rdlang`; else rdlang=""; fi
rm initrmfs/tbu/utility/lang-avail 2> /dev/null
while read line
do
    if [ -f ifl_${line:0:2}$langfilefinish ]; then
        echo $line >> initrmfs/tbu/utility/lang-avail
    else
        if [ "$lang" = "${line:0:2}" ]; then rm initrmfs/tbu/utility/lang 2> /dev/null; fi
        if [ "$rdlang" = "${line:0:2}" ]; then rm initrmfs/tbu/utility/rdlang 2> /dev/null; fi
    fi
done < "initrmfs/tbu/utility/lang-versions"

# call settings menu
chroot initrmfs /usr/bin/custom-menu

# save settings and clean up root fs
for i in iflkmap ktl vga xres vmode vmodeuefi boot iflscript lang lvm md rdiflkmap rdktl rdlang rdvga rdxres rdvmode rdvmodeuefi rdboot rdcmd rdlvm rdmenu rdmenuconfig
do
    if [ -e initrmfs/tbu/utility/$i ]; then
        cp -a initrmfs/tbu/utility/$i $settingspath/$i
    else
        rm $settingspath/$i 2> /dev/null
    fi
done
for i in iflkmap ktl vga xres lang rdlang lang-avail
do
    if [ -e initrmfs/tbu/utility/$i ]; then
        rm initrmfs/tbu/utility/$i 2> /dev/null
    fi
done

# if net version, save network config files
if [ "$netsupport" = "1" ]; then
    for i in interfaces ifacelist ndisinstall
    do
        if [ -f initrmfs/etc/network/$i ]; then
            cp -a initrmfs/etc/network/$i $settingspath/network/$i
        else
            rm $settingspath/network/$i 2> /dev/null
        fi
    done
    cmp -s initrmfs/etc/network/interfaces initrmfs/etc/network/interfaces-default 2> /dev/null
    if [ "$?" = "0" ]; then rm $settingspath/network/interfaces 2> /dev/null; fi
    rm $settingspath/network/settings-* 2> /dev/null
    cp -a initrmfs/etc/network/settings-* $settingspath/network 2> /dev/null
    rm $settingspath/network/settings-default 2> /dev/null
    if [ -f initrmfs/etc/udev/rules.d/$rulesfile ]; then
        cp -a initrmfs/etc/udev/rules.d/$rulesfile $settingspath/network/$rulesfile
    else
        rm $settingspath/network/$rulesfile 2> /dev/null
    fi
fi

# get variables for config files
# keyboard
if [ -e $settingspath/iflkmap ]; then
    kbd=`cat $settingspath/iflkmap`
    ktl=`cat $settingspath/ktl`
else
    kbd=us
    ktl=qwerty
fi

# video
if [ -f $settingspath/vmode ]; then
    defaultitem=`cat $settingspath/vmode`
elif [ -f initrmfs/tbu/utility/x64 ]; then
    defaultitem=2
else
    defaultitem=1
fi
# UEFI video
    if [ -e $settingspath/vmodeuefi ]; then
        vmodeuefi=`cat $settingspath/vmodeuefi`
    else
        vmodeuefi=0
    fi

# boot parameters
if [ -e $settingspath/boot ]; then
    bootparms=`cat $settingspath/boot`
else
    bootparms=""
fi

if [ ! -f initrmfs/tbu/utility/gui ]; then
    # build boot loader config file (extlinux.conf or syslinux.cfg)
    echo "timeout 50" > hdd/$cfile
    echo "kbdmap $ktl.ktl" >> hdd/$cfile
    echo "prompt 1" >> hdd/$cfile
    echo "display menu.txt" >> hdd/$cfile
    echo "default $defaultitem" >> hdd/$cfile
    echo "label 1" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=0 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 2" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=773 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 3" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=771 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 4" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=769 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 5" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=ask iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 4gh" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=0 mem=2G iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile

    # build menu.txt file
    if [ "$netsupport" = "1" ]; then
	boottitle="Image For Linux (CUI) Network Boot Disk - TeraByte, Inc."
    else
	boottitle="Image For Linux (CUI) Boot Disk - TeraByte, Inc."
    fi

    echo "" > hdd/menu.txt
    echo $boottitle >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "Boot Menu:" >> hdd/menu.txt
    echo "<1>  80x25 text mode" >> hdd/menu.txt
    echo "<2>  1024x768 frame bufffer mode" >> hdd/menu.txt
    echo "<3>  800x600 frame bufffer mode" >> hdd/menu.txt
    echo "<4>  640x480 frame bufffer mode" >> hdd/menu.txt
    echo "<5>  Select alternate video mode during boot" >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "Booting default <$defaultitem> in 5 seconds. Press <Enter> to boot now." >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    # For UEFI mode
    if [ "$netsupport" = "1" ]; then
        cat hdd/boot/grub/grub.cfg-default | sed -e "s/iflkmap=us ktl=qwerty/iflkmap=$kbd ktl=$ktl/" | sed -e "s/iflbflag=0/iflbflag=0 $bootparms/" | sed -e "s/default=0/default=$vmodeuefi/" > hdd/boot/grub/grub.cfg
    else
        cat hdd/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" | sed -e "s/iflkmap=us ktl=qwerty/iflkmap=$kbd ktl=$ktl/" | sed -e "s/iflbflag=0/iflbflag=0 $bootparms/" | sed -e "s/default=0/default=$vmodeuefi/" > hdd/boot/grub/grub.cfg
    fi
elif [ -f initrmfs/tbu/utility/gui ] && [ -f initrmfs/tbu/utility/x64 ]; then
    # build boot loader config file for GUI version (isolinux.cfg)
    echo "timeout 50" > hdd/$cfile
    echo "kbdmap $ktl.ktl" >> hdd/$cfile
    echo "prompt 1" >> hdd/$cfile
    echo "display menu.txt" >> hdd/$cfile
    echo "default $defaultitem" >> hdd/$cfile
    echo "label 1" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=794 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 2" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=791 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 3" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=788 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 4" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=785 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 4gh" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=791 switchx=yes mem=2G iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile

    # build menu.txt file 
    if [ "$netsupport" = "1" ]; then
        boottitle="Image For Linux (GUI) Network Boot Disk - TeraByte, Inc."
    else
        boottitle="Image For Linux (GUI) Boot Disk - TeraByte, Inc."
    fi

    echo "" > hdd/menu.txt
    echo $boottitle >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "Boot Menu:" >> hdd/menu.txt
    echo "<1>  1280x1024 frame buffer mode" >> hdd/menu.txt
    echo "<2>  1024x768 frame buffer mode" >> hdd/menu.txt
    echo "<3>  800x600 frame buffer mode" >> hdd/menu.txt
    echo "<4>  640x480 frame buffer mode" >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "For systems that fail to start the GUI after boot, please try" >> hdd/menu.txt
    echo "another video mode from the list above (e.g. boot: 3)." >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "Booting default <$defaultitem> in 5 seconds. Press <Enter> to boot now." >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    # For UEFI mode
    if [ "$netsupport" = "1" ]; then
        cat hdd/boot/grub/grub.cfg-default | sed -e "s/iflkmap=us ktl=qwerty/iflkmap=$kbd ktl=$ktl/" | sed -e "s/iflbflag=0/iflbflag=0 $bootparms/" | sed -e "s/default=0/default=$vmodeuefi/" > hdd/boot/grub/grub.cfg
    else
        cat hdd/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" | sed -e "s/iflkmap=us ktl=qwerty/iflkmap=$kbd ktl=$ktl/" | sed -e "s/iflbflag=0/iflbflag=0 $bootparms/" | sed -e "s/default=0/default=$vmodeuefi/" > hdd/boot/grub/grub.cfg
    fi
elif [ -f initrmfs/tbu/utility/gui ] && [ ! -f initrmfs/tbu/utility/x64 ]; then
    # build boot loader config file for GUI version (isolinux.cfg)
    echo "timeout 50" > hdd/$cfile
    echo "kbdmap $ktl.ktl" >> hdd/$cfile
    echo "prompt 1" >> hdd/$cfile
    echo "display menu.txt" >> hdd/$cfile
    echo "default $defaultitem" >> hdd/$cfile
    echo "label 1" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=773 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 2" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=773 xres=1024 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 3" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=773 xres=800 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 4" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=773 xres=640 iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 1fb" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=794 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 2fb" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=791 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 3fb" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=788 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 4fb" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=785 switchx=yes iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile
    echo "label 4gh" >> hdd/$cfile
    echo " kernel vmlinuz" >> hdd/$cfile
    echo " append vga=773 mem=2G iflkmap=$kbd ktl=$ktl initrd=initrmfs.gz iflbflag=0  $bootparms" >> hdd/$cfile

    # build menu.txt file 
    if [ "$netsupport" = "1" ]; then
        boottitle="Image For Linux (GUI) Network Boot Disk - TeraByte, Inc."
    else
        boottitle="Image For Linux (GUI) Boot Disk - TeraByte, Inc."
    fi

    echo "" > hdd/menu.txt
    echo $boottitle >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "Boot Menu:" >> hdd/menu.txt
    echo "<1>  Best available graphics mode" >> hdd/menu.txt
    echo "<2>  1024x768 graphics mode" >> hdd/menu.txt
    echo "<3>  800x600 graphics mode" >> hdd/menu.txt
    echo "<4>  640x480 graphics mode" >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "For systems that fail to start the GUI after boot, please use" >> hdd/menu.txt
    echo "frame buffer option 1fb, 2fb, 3fb, or 4fb (e.g. boot: 2fb)." >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    echo "Booting default <$defaultitem> in 5 seconds. Press <Enter> to boot now." >> hdd/menu.txt
    echo "" >> hdd/menu.txt
    # For UEFI mode
    if [ "$netsupport" = "1" ]; then
        cat hdd/boot/grub/grub.cfg-default | sed -e "s/iflkmap=us ktl=qwerty/iflkmap=$kbd ktl=$ktl/" | sed -e "s/iflbflag=0/iflbflag=0 $bootparms/" | sed -e "s/default=0/default=$vmodeuefi/" > hdd/boot/grub/grub.cfg
    else
        cat hdd/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" | sed -e "s/iflkmap=us ktl=qwerty/iflkmap=$kbd ktl=$ktl/" | sed -e "s/iflbflag=0/iflbflag=0 $bootparms/" | sed -e "s/default=0/default=$vmodeuefi/" > hdd/boot/grub/grub.cfg
    fi
fi


clear
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "     The makeHDD script to install to hard drive or UFD - TeraByte, Inc."
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo
if [ "$partition" = "0" ] && [ "$partitioned" = "1" ]; then
    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
    echo
    echo "Install Target: DRIVE /dev/$device  ($dsizedisplay)"
else
    echo "Command line entered: $0 $1 $2 $3 $4 $5 $6 $7 $8"
    echo
    echo -n "Install Target: "
    if [ "$partition" = "1" ]; then
	echo "PARTITION /dev/$device  ($psizedisplay, $ptypedisplay)"
	echo "The target partition is located on DRIVE /dev/$wdevice ($dsizedisplay)"
    else
	echo "DRIVE /dev/$device  ($dsizedisplay)" 
    fi
fi
echo
echo "OPTION 1: Settings menu"
echo

# prompt for console login option
echo "OPTION 2: Do you want a console login to be required (default is No)?"
echo "Enter y and press <Enter> for Yes"
echo -n "Just press <Enter> for No  "
yn=0
read yn
if [ "$yn" = "y" ] || [ "$yn" = "Y" ]; then
    echo "Configuring root filesystem to require console login"
    echo "Note: The default root password is 'ifl'"
    cp -a initrmfs/etc/inittab-getty initrmfs/etc/inittab
else
    echo "Console login will not be required (default)"
fi

# prompt for password change option
echo
echo "OPTION 3: Change root password from the default of 'ifl'?"
echo "Enter y and press <Enter> for Yes"
echo -n "Just press <Enter> for No  "
yn=0
read yn
if [ "$yn" = "y" ] || [ "$yn" = "Y" ]; then
    echo "The root password will be changed"
    echo "You will now be prompted to enter a new root password"
    echo "Password can be ANY string of 1 to 8 characters"
    ps=0
    while [ "$ps" = "0" ]
    do
        chroot initrmfs /usr/bin/passwd
        if [ "$?" = "0" ]; then
            ps=1
        else
            echo "Error while changing password...please try again"
        fi
    done
else
    echo "The default root password will be used"
fi
echo

if [ "$netsupport" = "1" ]; then
    echo "Building custom full version with network support"
else
    echo "Building custom smaller version with no network support"
fi

# copy files and directories to root file system
if [ -e ifl-custom.ini ]; then
	keyini="initrmfs/tbu/ifl.ini license productkey"
	userini="initrmfs/tbu/ifl.ini license user"
	productkey=$(ReadIniValue $keyini)
	prodkeyname=$(ReadIniValue $userini)
	echo "Copying ifl-custom.ini to the root filesystem as ifl.ini"
	cp -a ifl-custom.ini initrmfs/tbu/ifl.ini
	chown 0:0 initrmfs/tbu/ifl.ini
	if [ "$(ReadIniValue $keyini)" = "" ]; then
		WriteIniValue $userini "$prodkeyname"
		WriteIniValue $keyini "$productkey"
	fi
fi

if [ -e config.txt ]; then
    echo "Copying config.txt to the root filesystem"
    cp -a config.txt initrmfs/etc/config.txt
    chown 0:0 initrmfs/etc/config.txt
elif [ -e CONFIG.TXT ]; then
    echo "Copying CONFIG.TXT to the root filesystem"
    cp -a CONFIG.TXT initrmfs/etc/config.txt
    chown 0:0 initrmfs/etc/config.txt
fi

#if [ -d scripts ]; then
    #echo "Copying scripts directory to the root filesystem"
    #cp -a scripts initrmfs/tbu/scripts
    #chown -R 0:0 initrmfs/tbu/scripts/
#fi

if [ -d wireless/firmware ] && [ "$netsupport" = "1" ]; then
    echo "Copying wireless/firmware directory to the root filesystem"
    cp -a wireless/firmware/* initrmfs/lib/firmware 2> /dev/null
    chown -R 0:0 initrmfs/lib/firmware/
fi

if [ -d iscsi ] && [ "$netsupport" = "1" ]; then
    echo "Copying iscsi directory to the root filesystem"
    rm -r initrmfs/etc/iscsi
    cp -a iscsi initrmfs/etc/iscsi
    cp -a help/iscsi.txt initrmfs/etc/iscsi/iscsi.txt
    chown -R 0:0 initrmfs/etc/iscsi/
fi

if [ -d tbosdtfiles ]; then
    echo "Copying tbosdtfiles directory to the root filesystem"
    cp -a tbosdtfiles initrmfs/tbu
    chown -R 0:0 initrmfs/tbu/tbosdtfiles/
fi

if [ -f BOOTITBM-CUSTOM.INI ]; then
    keyini="initrmfs/tbu/BOOTITBM.INI license productkey"
    userini="initrmfs/tbu/BOOTITBM.INI license user"
    productkey=$(ReadIniValue $keyini)
    prodkeyname=$(ReadIniValue $userini)
    echo "Copying BOOTITBM-CUSTOM.INI to the root filesystem as BOOTITBM.INI"
    cp -a BOOTITBM-CUSTOM.INI initrmfs/tbu/BOOTITBM.INI
    chown 0:0 initrmfs/tbu/BOOTITBM.INI
    WriteIniValue $userini "$prodkeyname"
    WriteIniValue $keyini "$productkey"
fi

    # process language versions selected in menus
    # lang is boot media setting, rdlang is restore disc setting
    # if lang setting doesn't exist, it's English
    if [ -e $settingspath/lang ]; then
        lang=`cat $settingspath/lang`
        while read line
        do
            if [ "${line:0:2}" = "$lang" ]; then
                langtext=${line:3}
                break
            fi
        done < "initrmfs/tbu/utility/lang-versions"
        # if rdlang doesn't exist, it's the same as lang
        if [ -e $settingspath/rdlang ]; then
            rdlang=`cat $settingspath/rdlang`
        else
            rdlang=$lang
        fi
        rdlangtext="English (default)"
        while read line
        do
            if [ "${line:0:2}" = "$rdlang" ]; then
                rdlangtext=${line:3}
                break
            fi
        done < "initrmfs/tbu/utility/lang-versions"
        rm -r lang-tmp 2> /dev/null
        mkdir lang-tmp
        unzip -q -d lang-tmp ifl_$lang$langfilefinish
        echo "Boot Media language version is $langtext"
        if [ -e lang-tmp/imagel ]; then
            echo "Copying $langtext version of imagel from ifl_$lang$langfilefinish to root filesystem"
            # if unregistered version, save English version for restore disc in case that uses English
            if [ "$reg" = "0" ]; then
                cp initrmfs/tbu/imagel initrmfs/tbu/imagelrd
            fi
            cp lang-tmp/imagel initrmfs/tbu/imagel
            chown 0:0 initrmfs/tbu/imagel
            chmod +x initrmfs/tbu/imagel
        else
            echo "$langtext version of imagel not found in ifl_$lang$langfilefinish"
            echo "The English (default) version of imagel will be used"
        fi
        echo "Restore Disc language version is $rdlangtext"
        if [ "$rdlang" != "en" ]; then
            rm -r lang-tmp 2> /dev/null
            mkdir lang-tmp
            unzip -q -d lang-tmp ifl_$rdlang$langfilefinish
            if [ -e lang-tmp/tbirest ]; then
                echo "Copying $rdlangtext version of tbirest from ifl_$rdlang$langfilefinish to root filesystem"
                cp lang-tmp/tbirest initrmfs/tbu/tbirest
                chown 0:0 initrmfs/tbu/tbirest
                chmod +x initrmfs/tbu/tbirest
            elif [ "$reg" = "1" ]; then
                echo "$rdlangtext version of tbirest not found in ifl_$rdlang$langfilefinish"
                echo "The English (default) version of tbirest will be used"
            elif [ -e lang-tmp/imagel ]; then
                echo "Copying $rdlangtext version of imagel from ifl_$rdlang$langfilefinish to root filesystem"
                cp lang-tmp/imagel initrmfs/tbu/imagelrd
                chown 0:0 initrmfs/tbu/imagelrd
                chmod +x initrmfs/tbu/imagelrd
            else
                echo "$rdlangtext version of imagel not found in ifl_$rdlang$langfilefinish"
                echo "The English (default) version of imagel will be used"
            fi
        fi
    elif [ -e $settingspath/rdlang ]; then
        echo "Boot Media language version is English (default)"
        rdlang=`cat $settingspath/rdlang`
        rdlangtext="English (default)"
        while read line
        do
            if [ "${line:0:2}" = "$rdlang" ]; then
                rdlangtext=${line:3}
                break
            fi
        done < "initrmfs/tbu/utility/lang-versions"
        echo "Restore Disc language version is $rdlangtext"
        if [ "$rdlang" != "en" ]; then
            rm -r lang-tmp 2> /dev/null
            mkdir lang-tmp
            unzip -q -d lang-tmp ifl_$rdlang$langfilefinish
            if [ -e lang-tmp/tbirest ]; then
                echo "Copying $rdlangtext version of tbirest from ifl_$rdlang$langfilefinish to root filesystem"
                cp lang-tmp/tbirest initrmfs/tbu/tbirest
                chown 0:0 initrmfs/tbu/tbirest
                chmod +x initrmfs/tbu/tbirest
            elif [ "$reg" = "1" ]; then
                echo "$rdlangtext version of tbirest not found in ifl_$rdlang$langfilefinish"
                echo "The English (default) version of tbirest will be used"
            elif [ -e lang-tmp/imagel ]; then
                echo "Copying $rdlangtext version of imagel from ifl_$rdlang$langfilefinish to root filesystem"
                cp lang-tmp/imagel initrmfs/tbu/imagelrd
                chown 0:0 initrmfs/tbu/imagelrd
                chmod +x initrmfs/tbu/imagelrd
            else
                echo "$rdlangtext version of imagel not found in ifl_$rdlang$langfilefinish"
                echo "The English (default) version of imagel will be used"
            fi
        fi
    else
        echo "Boot Media language version is English (default)"
        echo "Restore Disc language version is English (default)"
    fi
    rm -r lang-tmp 2> /dev/null

# run getty on one or both serial ports, based on config.txt
if [ "$SERIAL_PORTS" = "1" ]; then
    echo "ttyS0::respawn:-/sbin/getty -L ttyS0 9600 vt100" >> initrmfs/etc/inittab
elif [ "$SERIAL_PORTS" = "2" ]; then
    echo "ttyS1::respawn:-/sbin/getty -L ttyS1 9600 vt100" >> initrmfs/etc/inittab
elif [ "$SERIAL_PORTS" = "B" ]; then
    echo "ttyS0::respawn:-/sbin/getty -L ttyS0 9600 vt100" >> initrmfs/etc/inittab
    echo "ttyS1::respawn:-/sbin/getty -L ttyS1 9600 vt100" >> initrmfs/etc/inittab
fi

# recompress the root file system
rm initrmfs/tmp/* 2> /dev/null
cd initrmfs
echo "Recompressing the root filesystem...please wait"
find . -print | $cpiopath -o -a -H newc > ../hdd/initrmfs
cd ..
rm -r initrmfs 2> /dev/null
gzip -9 hdd/initrmfs
sync

# clean up
# rm -r initrmfs 2> /dev/null (moved up to just before gzip command)
if [ "$0" = "./makeHDD" ]; then
    chown -R $ownerid:$groupid util 2> /dev/null
fi

fi ##############################################################################


else
    volname="TBI Backup Disk"
fi ########################## end /rest block ##################################################

# error exit point
error_exit() {
rm -r hdd 2> /dev/null
exit 1
}

# function to copy ifl files to drive or partition with tbosdt
copy_files_tbosdt() {
    copyerror=0
    if [ "$partition" = "1" ]; then
	echo "Copying files to partition /dev/$device..."
    else
	echo "Copying files to drive /dev/$device..."
    fi
    if [ "$custom" = "0" ]; then
	if [ -f hdd/isolinux.cfg ]; then
	    mv hdd/isolinux.cfg hdd/$cfile
	elif [ -f hdd/syslinux.cfg ]; then
	    if [ "$cfile" != "syslinux.cfg" ]; then
		mv hdd/syslinux.cfg hdd/$cfile
	    fi
	elif [ -f hdd/extlinux.conf ]; then
	    if [ "$cfile" != "extlinux.conf" ]; then
		mv hdd/extlinux.conf hdd/$cfile
	    fi
	fi
    fi
    # use tbosdt to copy files to drive/partition
    echo "mount 0: /dev/$device" > copyhdd.run
    echo "copy hdd 0: -s -q" >> copyhdd.run
    $tbosdtpath copyhdd.run > /dev/null 2>&1
    if [ ! "$?" = "0" ]; then copyerror=1; fi
    rm copyhdd.run
    sync
}

# function to copy restore disc files to drive/partition from cdboot directory
copy_files_restore() {
    copyerror=0
    if [ "$partition" = "1" ]; then
	echo "Copying files to partition /dev/$device..."
    else
	echo "Copying files to drive /dev/$device..."
    fi
    # use tbosdt to copy restore files to drive/partition
    echo "mount 0: /dev/$device" > copyhdd.run
    echo "copy cdboot 0: -y -s -q" >> copyhdd.run
    echo "del 0:$cfile -y" >> copyhdd.run
    echo "ren 0:isolinux.cfg 0:$cfile" >> copyhdd.run
    echo "del 0:isolinux.bin -y" >> copyhdd.run
    echo "umount 0:" >> copyhdd.run
    $tbosdtpath copyhdd.run > /dev/null 2>&1
    # $tbosdtpath copyhdd.run > thisfile.txt 2>&1
    if [ ! "$?" = "0" ]; then copyerror=1; fi
    rm copyhdd.run
    sync
}

copy_error() {
    echo "Error(s) encountered while copying files to /dev/$device...exiting"
    echo
    error_exit
}

format_error() {
    echo "Formatting of /dev/$device failed...exiting"
    echo
    error_exit
}

bootloader_error() {
    echo "Installation of boot loader to /dev/$device failed...exiting"
    echo
    if [ "$runmode" = "distro" ]; then
	echo "Note: This error might be corrected by installing the 'syslinux' package"
	echo "and then running 'makeHDD' or 'iflbuild' again. If 'syslinux' is already"
	echo "installed, please try installing to a partition (e.g. /dev/sdc1) instead"
	echo "of to an entire drive (e.g. /dev/sdc)"
    fi
    echo
    error_exit
}

mount_error() {
    echo "Mounting of /dev/$device for copying failed...exiting"
    echo
    error_exit
}

unmount_error() {
    sleep 1
    umount hdd/tmp 2> /dev/null  # try again
    if [ ! "$?" = "0" ]; then
	echo "Unmounting of /dev/$device failed...exiting"
	echo
	exit 1
    fi
    error_exit
}

# if installing to drive, format it, install syslinux, copy files to it with tbosdt
if [ "$partition" = "0" ]; then
    echo "Formatting drive /dev/$device as FAT32"
    $mkdosfspath -n "$volname" -F32 -I /dev/$device > /dev/null
    if [ ! "$?" = "0" ]; then format_error; fi 
    echo "Installing the syslinux boot loader to /dev/$device ($syslinuxpath)"
    $syslinuxpath $syslinuxopt /dev/$device
    if [ ! "$?" = "0" ]; then bootloader_error; fi
    if [ "$rest" = "1" ]; then copy_files_restore; else copy_files_tbosdt; fi
    rm -r hdd 2> /dev/null
    echo "Syncing drive /dev/$device with Linux kernel (blockdev --rereadpt /dev/$device)"
    $blockdevpath --rereadpt /dev/$device   # re-read partition table
    if [ "$copyerror" = "0" ]; then
	echo "Installation to drive /dev/$device completed successfully"
	echo "Drive /dev/$device is now ready to use"
    else
	copy_error
    fi
# if partition, set active if /a given, then format according to partition type
# then install boot loader, copy files to it with tbosdt
else
    if [ "$active" = "1" ]; then
	echo "Setting /dev/$device active as requested (the /a option was given)"
	# use parted if there (quieter)
	partedpath=`which parted 2> /dev/null`
	if [ "$?" = "0" ]; then
	    for slot in 1 2 3 4
	    do
		if [ "$slot" = "$part" ]; then
		    $partedpath -s /dev/$wdevice set $slot boot on
		else
		    $partedpath -s /dev/$wdevice set $slot boot off > /dev/null 2>&1
		fi
	    done
	else
	    aoffset=446  # offset to first active byte in pt
	    for slot in 1 2 3 4
	    do
		if [ "$slot" = "$part" ]; then
		    dd if=$util/active.bin of=/dev/$wdevice bs=1 count=1 seek=$aoffset
		else
		    dd if=/dev/zero of=/dev/$wdevice bs=1 count=1 seek=$aoffset
		fi
		let aoffset=aoffset+16
	    done
	    echo "Partition /dev/$device on drive /dev/$wdevice is now set active"
	fi
    fi
    if [ "$ptype" = "6" ] || [ "$ptype" = "e" ]; then 
	if [ "$nf" = "1" ]; then
	    echo "Not formatting partition /dev/$device (/nf specified)"
	else
	    echo "Formatting partition /dev/$device as FAT16"
	    $mkdosfspath -n "$volname" -F16 /dev/$device > /dev/null
	    if [ ! "$?" = "0" ]; then format_error; fi
	fi
	echo "Installing the syslinux boot loader to /dev/$device ($syslinuxpath)"
	$syslinuxpath $syslinuxopt /dev/$device
	if [ ! "$?" = "0" ]; then bootloader_error; fi
	if [ "$rest" = "1" ]; then copy_files_restore; else copy_files_tbosdt; fi
    elif [ "$ptype" = "b" ] || [ "$ptype" = "c" ]; then
	if [ "$nf" = "1" ]; then
	    echo "Not formatting partition /dev/$device (/nf specified)"
	else
	    echo "Formatting partition /dev/$device as FAT32"
	    $mkdosfspath -n "$volname" -F32 /dev/$device > /dev/null
	    if [ ! "$?" = "0" ]; then format_error; fi
	fi
	echo "Installing the syslinux boot loader to /dev/$device ($syslinuxpath)"
	$syslinuxpath $syslinuxopt /dev/$device
	if [ ! "$?" = "0" ]; then bootloader_error; fi
	if [ "$rest" = "1" ]; then copy_files_restore; else copy_files_tbosdt; fi
    elif [ "$ptype" = "df" ]; then
	echo "Not formatting partition /dev/$device (type $ptype)"
	echo "Installing the syslinux boot loader to /dev/$device"
	$syslinuxpath $syslinuxopt /dev/$device
	if [ ! "$?" = "0" ]; then bootloader_error; fi
	if [ "$rest" = "1" ]; then copy_files_restore; else copy_files_tbosdt; fi
    else
	if [ "$nf" = "1" ]; then
	    echo "Not formatting partition /dev/$device (/nf specified)"
	else
	    echo "Formatting partition /dev/$device as ext2"
	    $mke2fspath -L "$volname" /dev/$device > /dev/null
	    if [ ! "$?" = "0" ]; then format_error; fi
	fi
	if [ "$rest" = "1" ]; then copy_files_restore; else copy_files_tbosdt; fi
	mkdir hdd/tmp
	mount /dev/$device hdd/tmp > /dev/null
	if [ ! "$?" = "0" ]; then mount_error; fi
	echo "Installing the extlinux boot loader to /dev/$device ($extlinuxpath)"
	$extlinuxpath -i hdd/tmp
	if [ ! "$?" = "0" ]; then
	    echo "Installation of extlinux boot loader failed"
	    echo
	    if [ "$runmode" = "distro" ]; then
		echo "Note: This extlinux error may be corrected by installing the 'syslinux' package"
		echo "(if not already installed), or on some distros there may be a separate 'extlinux'"
		echo "package. Then run makeHDD again."
	    fi
	    umount hdd/tmp 2> /dev/null
	    if [ ! "$?" = "0" ]; then unmount_error; fi
	    echo
	    exit 1
	else
	    umount hdd/tmp 2> /dev/null
	    if [ ! "$?" = "0" ]; then unmount_error; fi
	fi
	rm -r hdd/tmp 2> /dev/null
    fi
    rm -r hdd 2> /dev/null
    if [ "$copyerror" = "0" ]; then
	echo "Installation to partition /dev/$device completed successfully"
    else
	copy_error
    fi
fi

# write standard mbr if /mbr given - warn user about overwriting existing MBR etc.
if [ "$mbr" = "1" ]; then
    echo    
    echo "Install standard MBR to /dev/$wdevice (the /mbr option was given):"
    echo "WARNING: Installing the standard MBR on drive /dev/$wdevice will overwrite"
    echo "any existing MBR code currently on the drive, including any boot managers"
    echo "or boot loaders. It will NOT overwrite the partition table. Installing the"
    echo "standard MBR is required if you intend to boot DIRECTLY from this drive,"
    echo "rather than using a boot manager."
    echo
    echo -n "Type 'yes' to confirm installing standard MBR to /dev/$wdevice: "
    read yn
    if [ "$yn" = "yes" ]; then
	echo "Installation of standard MBR to /dev/$wdevice was confirmed"
	echo "Writing standard MBR code to drive /dev/$wdevice"
	cp $util/mbr.bin /dev/$wdevice
	if [ "$?" = "0" ]; then
	     echo "Installation of MBR code to /dev/$wdevice completed successfully"
	else
	    echo "Installation of MBR code to /dev/$wdevice failed"
	    echo
	    error_exit
	fi    
    else
	echo "Confirmation declined. Standard MBR code not installed to /dev/$wdevice"
    fi 
fi

# extlinux requires BIBM's swap mode if on drive other than HDO
if [ "$partition" = "1" ] && [ "$ptype" = "83" ]; then
    echo
    echo "IMPORTANT: If booting this partition with BootIt BM, swap mode must be"
    echo "selected in the Boot Item if the partition is on any drive other than"
    echo "HD0. This is due to the use of extlinux as the boot loader."
fi
echo
exit 0
