#!/bin/bash

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

clear
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "            Setup Script For Image For Linux - TeraByte, Inc."
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo

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

# 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 or reiserfs)...exiting"
		echo
		exit 1
	fi
	rm $tf1; rm $tf2
fi

# check command line
checkedd=0;eficadir=
for param in $1 $2;
do
	if [ "$param" = "/edd" ]; then checkedd=1
	elif [ "$param" = "/msca2011" ]; then 
		eficadir=MicrosoftCA2011
	elif [ "$param" = "/msca2023" ]; then 
		eficadir=MicrosoftCA2023
	elif [ "$param" = "/tbca2026" ]; then 
		eficadir=TeraByte
	elif [ "$param" != "" ]; then
		echo "Usage:  ./setup [/edd] [msca2011|msca2023|tbca2026]"
		echo "  /edd      - Check edd status"
		echo "  /msca2011 - UEFI boot using MS 2011 CA"
		echo "  /msca2023 - UEFI boot using MS 2023 CA"
		echo "  /tbca2026 - UEFI boot using TeraByte 2026 CA"
		echo
		echo "Invalid Parameter: $param"
		echo
		exit 1
	fi
done

yn=0
while [ "$yn" = "0" ]
do
	clear
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "            Setup Script For Image For Linux - TeraByte, Inc."
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo
	echo "Image for Linux License Agreement:"
	echo
	echo "The use of Image for Linux (IFL) constitutes acceptance of the terms of the"
	echo "License Agreement as defined in the LICENSE.TXT file in this directory"
	echo
	echo "Do you ACCEPT the terms of the License Agreement?"
	echo -n "Enter y or n, then press <Enter>: "
	read yn
	if [ "$yn" = "y" ] || [ "$yn" = "Y" ]; then
		yn=y
		break
	elif [ "$yn" = "n" ] || [ "$yn" = "N" ]; then
		yn=n
		break
	fi
	yn=0
done

if [ "$yn" = "n" ]
	then
	echo
	echo "You have chosen NOT to accept the terms of the License Agreement"
	echo -n "Press <Enter> to exit..."
	read e
	echo
	exit 1
else
	echo
	echo "You have chosen to ACCEPT the License Agreement"
	echo
fi

echo "STEP 1: Check for required files"
iok=0
if [ -x /sbin/modprobe ]; then
	modprobepath=/sbin/modprobe
elif [ -x /usr/sbin/modprobe ]; then
	modprobepath=/usr/sbin/modprobe
else
	iok=1
	echo "ERROR: Required file modprobe (typically /sbin/modprobe) not found on"
	echo "       the system"
fi
if [ ! -e iflnet.iso ]; then
	iok=1
	echo "ERROR: Required file iflnet.iso not found in the IFL directory (case matters)"
	# need to use full version (nonet version doesn't support installation)
	echo "       The 'nonet' (non-network) version of Image for Linux available for"
	echo "       download from the download portal is intended for Windows users.  It"
	echo "       does not include the required files needed for use in Linux.  Make"
	echo "       sure you download and use a standard version of Image for Linux.  The"
	echo "       standard version 'setup' will create both the network (iflnet.iso)"
	echo "       and non-network (ifl.iso) versions."
fi
if [ ! `which unzip 2> /dev/null` ]; then
	iok=1
	echo "ERROR: Required program unzip not found on system. This can usually be"
	echo "       corrected by installing the unzip package."
fi

# check if x64
uname -a | grep -i "x86_64" > /dev/null
if [ "$?" = "0" ] && [ ! -f /tbu/utility/running ]; then
	isx64=1
else
	isx64=0
fi

if [ ! -e config.zip ]; then
	iok=1
	echo "ERROR: Required file config.zip not found in the IFL directory"
elif [ "$iok" = "0" ]; then
	# extract newer or files that don't exist (preserve ifl-custom.ini)
	echo "Extracting the file config.zip"
	unzip -q -ou config.zip
	if [ "$isx64" = "1" ] && [ -f "x64-bin.zip" ]; then
		echo "Extracting the file x64-bin.zip"
		unzip -q -o x64-bin.zip
	fi
fi
if [ ! `which chroot 2> /dev/null` ]; then
	# add sbin paths to PATH and recheck
	PATH=$PATH:/usr/sbin:/sbin
	if [ ! `which chroot 2> /dev/null` ]; then
		iok=1
		echo "ERROR: Required program chroot not found on system. This can usually be"
		echo "       corrected by making sure /usr/sbin and /sbin are included in the"
		echo "       environment PATH variable for the root user. Alternatives include"
		echo "       running script with 'sudo' (e.g. sudo ./setup) or using 'su -' to"
		echo "       open a login shell, then changing to the script's folder and"
		echo "       running it."
	fi
fi


# determine which genisoimage / mkisofs to use -> makeisopath variable
# uefi requires the -efi-boot option, not all versions support it
# Note: iso files are **built in chroot** as of v242, so above is not an issue

# check if cpio will execute (won't on 64 bit systems)
# if not, use /bin/cpio if there, 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
		iok=1
		echo "ERROR: Required file cpio (typically /bin/cpio) not found on system"
		break
	else
		read -r cpioversion < <($cpiopath --version)
		echo "-"		
		echo "Using cpio version $cpioversion"
		echo "-"
		break
	fi
done

# check for zcat, determine path
zcatpath=`which zcat 2> /dev/null`
if [ ! "$?" = "0" ]; then
	iok=1
	echo "ERROR: Required program zcat (typically /bin/zcat) not found on system"
fi

gzippath=`which gzip 2> /dev/null`
if [ ! "$?" = "0" ]; then
	iok=1
	echo "ERROR: Required program gzip (typically /bin/gzip) not found on system"
fi

if [ "$iok" = "0" ]; then
	if [ "$isx64" = "1" ] && [ -f "./x64/tbosdt64" ]; then
		tbosdt="./x64/tbosdt64"
	else
		tbosdt="./util/tbosdt"
	fi
	if [ -x ${tbosdt} ]; then
		echo > checkpackage.run
		${tbosdt} checkpackage.run 2> /dev/null
		if [ ! "$?" = "0" ]; then
			iok=1
			echo "ERROR: The tbosdt program was unable to run"
			if [ "$isx64" = "1" ] && [ ! -f "./x64/tbosdt64" ]; then
				echo
				echo "This issue is likely caused by the missing 32-bit package"
				echo "libncursesw6."
				echo
				echo "IMPORTANT: On 64-bit systems, 32-bit shared libraries must be"
				echo "installed in order to run the setup script and IFL. For more"
				echo "details, please see the knowledge base article at:"
				echo "http://www.terabyteunlimited.com/kb/article.php?id=566"
				echo
				echo "NOTE: A 64-bit download of IFL is also available. If you use"
				echo "that version, no 32-bit libraries are required."
			fi
		fi
		rm checkpackage.run
	else
		echo "ERROR: Required program tbosdt not found"
	fi
fi

if [ "$iok" = "1" ]; then
	echo
	echo "ERROR: One or more required files not found or unable to run"
	echo "       See above messages in STEP 1 for details."
	echo
	exit 1
else
	if [ "$iok" = "2" ]; then
		echo
		echo "Warning: All required files were found but one or more"
		echo "         recommended files were not found"
		echo
	else
		echo "All required files found"
	fi
fi

echo
echo "STEP 2: Decompress and extract the root fs. Please wait..."
# echo "Cleaning up any previous contents of working directories"
for workingdir in cdroot initrmfs
do
	rm -r $workingdir 2> /dev/null
	mkdir $workingdir
done
echo "mount 0: iflnet.iso" > getiflnetfiles.run
echo "copy 0: cdroot -s -q" >> getiflnetfiles.run
${tbosdt} getiflnetfiles.run 2> /dev/null
rm getiflnetfiles.run

cd initrmfs
#$cpiopath --quiet -i -m -d < ../cdroot/initrmfs
$zcatpath ../cdroot/initrmfs.gz | $cpiopath --quiet -i -m -d
checkerror=$?
if [ "$checkerror" != "0" ]; then
	echo "Error $checkerror for command: $cpiopath --quiet -i -m -d < ../cdroot/initrmfs"
	echo "Possible cause: less than 100 MB of free disk space before running setup"
	echo "Exiting setup..."
	cd ..
	rm -r cdroot 2> /dev/null
	rm -r initrmfs 2> /dev/null
	exit 1
fi

cd ..   # back in IFL directory

if [ -e tbimount -a -e tbimount.ko ]; then
  cp -a tbimount initrmfs/tbu
  cp -a tbimount.ko initrmfs/tbu
  chmod +x initrmfs/tbu/tbimount
fi

sync

# debug code to capture chroot data
# chroot initrmfs /usr/bin/env > ./env.txt
# chroot initrmfs /bin/ls -l /dev > ./dev.txt
# end debug code

if [ "$eficadir" = "" ]; then
	while [ 0 ]; do
		echo
		echo "STEP 3: Select the Certificate Type for UEFI Secure Boot."
		echo " 0) Use current default"
		echo " 1) Microsoft CA 2011"
		echo " 2) Microsoft CA 2023"
		echo " 3) TeraByte"
		read -r -p "Select 0-3: " choice
		case "$choice" in
			0)
				break
				;;
			1)
				eficadir=MicrosoftCA2011
				break
				;;
			2)
				eficadir=MicrosoftCA2023
				break
				;;
			3)
				eficadir=TeraByte
				break
				;;
			*)
				echo "Invalid selection. Enter 0, 1, 2, or 3."
				echo
				;;
		esac
	done
	echo
fi

# handle secure boot efi
if [ "$eficadir" != "" ]; then
	cp cdroot/sbca/$eficadir/bootx64.efi cdroot/efi/boot
	cp cdroot/sbca/$eficadir/efi.img cdroot/boot/grub
	cp cdroot/boot/grub/efi.img initrmfs/tbu/cdboot/boot/grub
fi

# check for unreg flag at /tbu/utility/ur
if [ -f initrmfs/tbu/utility/ur ]; then full=0; else full=1; fi
# check for gui flag at /tbu/utility/gui
if [ -f initrmfs/tbu/utility/gui ]; then gui=1; else gui=0; fi

# prompt for ProductKey if full version
if [ "$full" = "1" ]; then
	keyini="ifl.ini license productkey"
	userini="ifl.ini license user"
	
	# remove /r if in file
	if [ -e ifl.ini ]; then
		sed -i `printf "s/\r//g"` ifl.ini
	fi
	
	CurrentProductKey=$(ReadIniValue $keyini)
	CurrentKeyName=$(ReadIniValue $userini)
	chroot initrmfs /usr/bin/setproductkey "$CurrentKeyName" "$CurrentProductKey"
	
	if [ -e initrmfs/tmp/ProductKeyValue ]; then
		ProductKey=`cat initrmfs/tmp/ProductKeyValue`
	else
		ProductKey=$CurrentProductKey
	fi
	
	if [ -e initrmfs/tmp/ProductKeyName ]; then
		ProductKeyName=`cat initrmfs/tmp/ProductKeyName`
	else
		ProductKeyName=$CurrentKeyName
	fi
	
	rm initrmfs/tmp/* 2> /dev/null
	
	# move BOOTIT.INI to BM name for other scripts
	if [ ! -f BOOTITBM.INI ]; then
		if [ -f BOOTIT.INI ]; then 
			mv BOOTIT.INI BOOTITBM.INI
		fi
	elif [ -f BOOTIT.INI ]; then
		echo "Warning: Both BOOTIT.INI and BOOTITBM.INI exist!"
		read -p "Press enter to continue..."
	fi
	
	# prompt for BootIt key
	keyini="BOOTITBM.INI license productkey"
	userini="BOOTITBM.INI license user"
	
	# remove /r if in file
	if [ -e BOOTITBM.INI ]; then
		sed -i `printf "s/\r//g"` BOOTITBM.INI
	fi
	
	CurrentProductKey=$(ReadIniValue $keyini)
	CurrentKeyName=$(ReadIniValue $userini)
	chroot initrmfs /usr/bin/setbootitkey "$CurrentKeyName" "$CurrentProductKey"
	
	if [ -e initrmfs/tmp/ProductKeyValue ]; then
		BIBMProductKey=`cat initrmfs/tmp/ProductKeyValue`
	else
		BIBMProductKey=$CurrentProductKey
	fi
	
	if [ -e initrmfs/tmp/ProductKeyName ]; then
		BIBMUserName=`cat initrmfs/tmp/ProductKeyName`
	else
		BIBMUserName=$CurrentKeyName
	fi
	
	rm initrmfs/tmp/* 2> /dev/null	
	
	
	# isolinux.cfg file
	chmod +w cdroot/isolinux.cfg*
	cp cdroot/isolinux.cfg-default cdroot/isolinux.cfg
	cp cdroot/menu.txt-default cdroot/menu.txt
	# UEFI grub.cfg file
	chmod +w cdroot/boot/grub/grub.cfg*
	cp cdroot/boot/grub/grub.cfg-default cdroot/boot/grub/grub.cfg

	# do ifl.ini for ProductKey - add to existing file contents if applicable
	keyini="ifl.ini license productkey"
	userini="ifl.ini license user"
	keyver="ifl.ini license keyver 4"
	
	WriteIniValue $keyini "$ProductKey"
	WriteIniValue $userini "$ProductKeyName"
	WriteIniValue $keyver
	if [ -f ifl.ini ]; then cp -a ifl.ini initrmfs/tbu/ifl.ini; fi
	
	if [ "$ProductKey" = "" ]; then ProductKey="None"; fi
	if [ "$ProductKeyName" = "" ]; then ProductKeyName="None"; fi

	# optionally write out BootIt name/key 
	if [ "$BIBMProductKey" != "" -o "$BIBMProductKey" != "" ]; then
		keyini="BOOTITBM.INI license productkey"
		userini="BOOTITBM.INI license user"
		WriteIniValue $keyini "$BIBMProductKey"
		WriteIniValue $userini "$BIBMUserName"
	fi
	keyver="BOOTITBM.INI license keyver 2"
	WriteIniValue $keyver
	
	if [ -f BOOTITBM.INI ]; then cp -a BOOTITBM.INI initrmfs/tbu/BOOTITBM.INI; fi
	
	if [ "$BIBMProductKey" = "" ]; then BIBMProductKeyText="None"; else BIBMProductKeyText="$BIBMProductKey"; fi
	if [ "$BIBMUserName" = "" ]; then BIBMUserNameText="None"; else BIBMUserNameText="$BIBMUserName"; fi
	
	
	# put up place wait 
	chroot initrmfs /usr/bin/dialog --no-shadow --infobox "   Please wait..." 3 25
	
	
	# rebuild rootfs to include ini files
	cd initrmfs
	#echo "  Recompressing the rootfs...please wait"
	find . -print | $cpiopath -o -a -H newc | $gzippath -9 > ../cdroot/initrmfs.gz
	if [ "$?" != "0" ]; then 
		echo "unable to recompress the rootfs."
		cd ..
		rm -r initrmfs 2> /dev/null
		exit 2
	fi
	cd ..
	
	# rebuild iflnet.iso in chroot
	mv cdroot initrmfs
	chroot initrmfs /usr/bin/genisoimage -quiet -V iflnet -l -R -r -J -o iflnet.iso -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -eltorito-alt-boot -efi-boot boot/grub/efi.img -no-emul-boot cdroot/
	mv initrmfs/iflnet.iso iflnet.iso
	mv initrmfs/cdroot cdroot
	sleep 1


	case "$eficadir" in
		"MicrosoftCA2011")
			eficadescr="Microsoft CA 2011"
			;;
		"MicrosoftCA2023")
			eficadescr="Microsoft CA 2023"
			;;
		"TeraByte")
			eficadescr="TeraByte"
			;;
		*)
			eficadescr="Current default"
			;;
	esac
	
	if [ "$gui" = "1" ]; then
		clear
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "            Setup Script For Image For Linux - TeraByte, Inc."
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo
		echo "STEP 1: Check for required files"
		echo
		echo "STEP 2: Decompress and extract the root fs from iflnet.iso"
		echo
		echo "STEP 3: Choose UEFI Secure Boot Certificate: $eficadescr"
		echo
		echo "STEP 4: IFL Product Key: $ProductKey  IFL Licensed Name: $ProductKeyName"
		echo
		echo "STEP 5: BIBM Product Key: $BIBMProductKeyText  BIBM Licensed Name: $BIBMUserNameText"
		echo
		Nextstep=6
	else
		clear
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "            Setup Script For Image For Linux - TeraByte, Inc."
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo
		echo "STEP 1: Check for required files"
		echo
		echo "STEP 2: Decompress and extract the root fs from iflnet.iso"
		echo
		echo "STEP 3: Choose UEFI Secure Boot Certificate: $eficadescr"
		echo
		echo "STEP 4: IFL Product Key: $ProductKey  IFL Licensed Name: $ProductKeyName"
		echo
		echo "STEP 5: BIBM Product Key: $BIBMProductKeyText  BIBM Licensed Name: $BIBMUserNameText"
		echo
		Nextstep=6
	fi
else
	echo
	Nextstep=4
fi

# create non-network version of disk (ifl.iso)
# create root fs from network version and copy to cdroot directory
echo "STEP $Nextstep: Creating non-network version from network version. Please wait..."
let Nextstep=Nextstep+1
# echo "Both network (iflnet.iso) and non-network (ifl.iso) versions will be available"
# echo "Creating initrmfs.gz for non-network version. Please wait..."
chroot initrmfs /tbu/utility/build-initrmfs-nonet
cp -a initrmfs/initrmfs.gz cdroot/initrmfs.gz

# create menu.txt file (title of disk dislayed on boot is different)
# echo "Creating menu.txt for non-network version"
cat cdroot/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" > cdroot/boot/grub/grub.cfg
cat cdroot/menu.txt-default | sed -e "s/Network Boot/Boot/" > cdroot/menu.txt

# create the ISO file (uses the same isolinux.cfg file)
# echo "Creating ifl.iso for non-network version"
mv cdroot initrmfs
chroot initrmfs /usr/bin/genisoimage -quiet -V ifl -l -R -r -J -o ifl.iso -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -eltorito-alt-boot -efi-boot boot/grub/efi.img -no-emul-boot cdroot/
mv initrmfs/ifl.iso ifl.iso
rm -r initrmfs/cdroot 2> /dev/null

# remove temporary directories no longer needed
# rm -r cdroot 2> /dev/null
# echo "Build of non-network version (ifl.iso) is complete"
# echo

################################################################################### exclude section 1
if [ ! -f /tbu/utility/running ]; then

	# get restore disc settings (if any) from previous run of setup
	# then clean up any previous files and directories
	if [ -e cdboot/isolinux.cfg ]; then
		KbdSearch=`grep -o -m1 iflkmap=[^[:space:]]* cdboot/isolinux.cfg`
		Currentkbd=`echo ${KbdSearch:8}`
		KtlSearch=`grep -o -m1 ktl=[^[:space:]]* cdboot/isolinux.cfg`
		Currentktl=`echo ${KtlSearch:4}`
	else
		Currentkbd=us
		Currentktl=qwerty
	fi
	echo $Currentkbd > initrmfs/tbu/utility/rdiflkmap
	echo $Currentktl > initrmfs/tbu/utility/rdktl
	if [ -e cdboot/rdvmode ]; then cp -a cdboot/rdvmode initrmfs/tbu/utility/rdvmode; fi
	if [ -e cdboot/rdboot ]; then cp -a cdboot/rdboot initrmfs/tbu/utility/rdboot; fi
	if [ -e cdboot/rdcmd ]; then cp -a cdboot/rdcmd initrmfs/tbu/utility/rdcmd; fi
	if [ -e cdboot/rdmenu ]; then cp -a cdboot/rdmenu initrmfs/tbu/utility/rdmenu; fi
	if [ -e cdboot/rdmenuconfig ]; then cp -a cdboot/rdmenuconfig initrmfs/tbu/utility/rdmenuconfig; fi
	if [ -e cdboot/lvm ]; then 	echo "1" > initrmfs/tbu/utility/rdlvm; fi
	if [ -e cdboot/rdvmodeuefi ]; then cp -a cdboot/rdvmodeuefi initrmfs/tbu/utility/rdvmodeuefi; fi

	if [ "$gui" = "1" ]; then
		if [ "$full" = "1" ]; then langfilefinish="_gui_v4.zip"; else langfilefinish="_gui_trial.zip"; fi
	elif [ "$gui" = "0" ]; then
		if [ "$full" = "1" ]; then langfilefinish="_v4.zip"; else langfilefinish="_trial.zip"; fi
	fi

	if [ -e cdboot/lang ]; then lang=`cat cdboot/lang`; else lang=""; fi
	if [ -e cdboot/rdlang ]; then rdlang=`cat cdboot/rdlang`; else rdlang=""; fi
	rm initrmfs/tbu/utility/lang-avail 2> /dev/null
	while read line
	do
		langabbrev=${line:0:2}  # first 2 characters are the language abbreviation
		if [ -f ifl_$langabbrev$langfilefinish ]; then
			echo $line >> initrmfs/tbu/utility/lang-avail
			if [ "$lang" = "$langabbrev" ]; then echo $lang > initrmfs/tbu/utility/lang; fi
			if [ "$rdlang" = "$langabbrev" ]; then echo $rdlang > initrmfs/tbu/utility/rdlang; fi
		fi	
	done < "initrmfs/tbu/utility/lang-versions"

	rm -r cdboot 2> /dev/null

	# display restore disc message box
	chroot initrmfs /usr/bin/restore-msgbox setup

	# display restore settings menu
	chroot initrmfs /usr/bin/restore-menu

	# choose language version of distro IFL
	chroot initrmfs /usr/bin/setlanguagever setup


	clear
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "            Setup Script For Image For Linux - TeraByte, Inc."
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo
	echo "STEP 1: Check for required files"
	echo
	echo "STEP 2: Decompress and extract the root fs from iflnet.iso"
	echo
	if [ "$full" = "1" ]; then
		echo "STEP 3: IFL Product Key: $ProductKey  IFL Licensed Name: $ProductKeyName"
		Nextstep=4
		echo
#		if [ "$gui" = "1" ]; then
			echo "STEP 4: BIBM Product Key: $BIBMProductKeyText  BIBM Licensed Name: $BIBMUserNameText"
			echo
			Nextstep=5
#		fi
	else
		Nextstep=3
	fi
	echo "STEP $Nextstep: Create non-network version from network version"
	echo
	let Nextstep=Nextstep+1
	echo "STEP $Nextstep: Select Restore Disc Settings"
	echo
	let Nextstep=Nextstep+1

	if [ -e initrmfs/tbu/utility/lang ]; then
		lang=`cat initrmfs/tbu/utility/lang`
		while read line
		do
			langabbrev=${line:0:2}  # first 2 characters are the language abbreviation
			if [ "$lang" = "$langabbrev" ]; then 
				langtext=${line:3}
				break
			fi
		done < "initrmfs/tbu/utility/lang-versions"
	else
		langtext="English (default)"    
	fi
	echo "STEP $Nextstep: Select IFL language version for distribution: $langtext"
	echo
	let Nextstep=Nextstep+1

	# build restore disc files and save settings
	echo "STEP $Nextstep: Setting up files in IFL directory"
	let Nextstep=Nextstep+1
	# process language versions
	if [ -e initrmfs/tbu/utility/rdlang ]; then
		rdlang=`cat initrmfs/tbu/utility/rdlang`
		while read line
		do
			langabbrev=${line:0:2}  # first 2 characters are the language abbreviation
			if [ "$rdlang" = "$langabbrev" ]; then 
				rdlangtext=${line:3}
				break
			fi
		done < "initrmfs/tbu/utility/lang-versions"
		echo "Restore Disc IFL language version is $rdlangtext"
		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
		elif [ "$full" = "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
		else
			echo "$rdlangtext version of imagel not found in ifl_$rdlang$langfilefinish"
			echo "The English (default) version of imagel will be used"
		fi
		chown 0:0 initrmfs/tbu/tbirest 2> /dev/null
		chmod +x initrmfs/tbu/tbirest 2> /dev/null
		chown 0:0 initrmfs/tbu/imagelrd 2> /dev/null
		chmod +x initrmfs/tbu/imagelrd 2> /dev/null
	else
		echo "Restore Disc language version is English (default)"
	fi
	if [ -e initrmfs/tbu/utility/lang ]; then
		echo "Distribution IFL language version is $langtext"
		rm -r lang-tmp 2> /dev/null
		mkdir lang-tmp
		unzip -q -d lang-tmp ifl_$lang$langfilefinish
		if [ -e lang-tmp/imagel ]; then
			echo "Copying $langtext version of imagel from ifl_$lang$langfilefinish to root filesystem"
			if [ ! -f initrmfs/tbu/imagelrd ]; 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
	else
		echo "Distribution IFL language version is English (default)"
	fi
	rm -r lang-tmp 2> /dev/null

	echo "Copying imagel, tbiview, cdboot.ins, and tbosdt-related files from root fs"
	cp -a initrmfs/tbu/cdboot.ins cdboot.ins
	cp -a initrmfs/tbu/imagel imagel
	if [ "$isx64" = "1" ] && [ -e "x64" ]; then
		cp -a x64/*64 .
	fi
	if [ -f initrmfs/tbu/tbirest ]; then cp -a initrmfs/tbu/tbirest tbirest; fi
	if [ -f initrmfs/tbu/imagelrd ]; then cp -a initrmfs/tbu/imagelrd imagelrd; else rm imagelrd 2> /dev/null; fi
	if [ -f initrmfs/tbu/iflleft.png ]; then cp -a initrmfs/tbu/iflleft.png iflleft.png; fi
	if [ -f initrmfs/usr/share/pixmaps/ifl_48x48.png ]; then cp -a initrmfs/usr/share/pixmaps/ifl_48x48.png ifl_48x48.png; fi
	# copy tbosdt, tbosdtw.exe, osdtool.tbs, tbexplo.tbs, tbidtool.tbs, and tbiview from root fs
	if [ -f initrmfs/tbu/tbosdt ]; then cp -a initrmfs/tbu/tbosdt tbosdt; fi
	if [ -f initrmfs/tbu/tbosdtw.exe ]; then cp -a initrmfs/tbu/tbosdtw.exe tbosdtw.exe; fi
	if [ -f initrmfs/tbu/osdtool.tbs ]; then cp -a initrmfs/tbu/osdtool.tbs osdtool.tbs; fi
	if [ -f initrmfs/tbu/copyp2v.tbs ]; then cp -a initrmfs/tbu/copyp2v.tbs copyp2v.tbs; fi
	if [ -f initrmfs/tbu/tbexplo.tbs ]; then cp -a initrmfs/tbu/tbexplo.tbs tbexplo.tbs; fi
	if [ -f initrmfs/tbu/tbidtool.tbs ]; then cp -a initrmfs/tbu/tbidtool.tbs tbidtool.tbs; fi
	if [ -f initrmfs/tbu/tbiview ]; then cp -a initrmfs/tbu/tbiview tbiview; fi
	if [ -f initrmfs/usr/bin/iflbuild ]; then cp -a initrmfs/usr/bin/iflbuild iflbuild; fi
	if [ -f initrmfs/tbu/partinfo ]; then cp -a initrmfs/tbu/partinfo partinfo; fi
	if [ -f initrmfs/tbu/multicastsender ]; then cp -a initrmfs/tbu/multicastsender multicastsender; fi
	echo "Creating initrmfs.gz for restore disc"
	chroot initrmfs /tbu/utility/build-initrmfs-cdboot distro 
	echo "Copying cdboot directory from root fs"
	cp -a initrmfs/tbu/cdboot ./
	# rm cdboot/tbirest 2> /dev/null
	rm cdboot/initrmfs-cdboot.gz 2> /dev/null
	if [ "$full" = "0" ] && [ ! -e ifl.ini ]; then touch ifl.ini; fi
	# save settings
	if [ -e initrmfs/tbu/utility/rdboot ]; then
		cp -a initrmfs/tbu/utility/rdboot cdboot/rdboot
	fi
	if [ -e initrmfs/tbu/utility/rdcmd ]; then
		cp -a initrmfs/tbu/utility/rdcmd cdboot/rdcmd
	fi
	if [ -e initrmfs/tbu/utility/rdmenu ]; then
		cp -a initrmfs/tbu/utility/rdmenu cdboot/rdmenu
	fi
	if [ -e initrmfs/tbu/utility/rdmenuconfig ]; then
		cp -a initrmfs/tbu/utility/rdmenuconfig cdboot/rdmenuconfig
	fi
	if [ -e initrmfs/tbu/utility/rdlang ]; then
		cp -a initrmfs/tbu/utility/rdlang cdboot/rdlang
	fi
	if [ -e initrmfs/tbu/utility/lang ]; then
		cp -a initrmfs/tbu/utility/lang cdboot/lang
	fi
	if [ -e initrmfs/tbu/utility/rdlvm ]; then
		rdlvm=`cat initrmfs/tbu/utility/rdlvm`
		if [ "$rdlvm" = "1" ]; then
			touch cdboot/lvm
		else
			rm cdboot/lvm 2> /dev/null
		fi
	else
		rm cdboot/lvm 2> /dev/null
	fi
	if [ -e initrmfs/tbu/utility/rdvmode ]; then
		cp -a initrmfs/tbu/utility/rdvmode cdboot/rdvmode
	fi
	if [ -e initrmfs/tbu/utility/rdvmodeuefi ]; then
		cp -a initrmfs/tbu/utility/rdvmodeuefi cdboot/rdvmodeuefi
	fi
fi
################################################################################### exclude section 1
# process the partwork related files if registered gui version
if [ "$full" = "1" ] && [ "$gui" = "1" ]; then
	if [ -f /tbu/utility/running ]; then
		echo
		echo "STEP $Nextstep: Setting up partwork files in the /tbu/iflbuild directory"
		let Nextstep=Nextstep+1
	fi
	echo "Copying partwork files from root fs"
	cp -a initrmfs/tbu/partwork partwork 2> /dev/null
	cp -a initrmfs/tbu/partwork.hlp partwork.hlp 2> /dev/null
	cp -a initrmfs/tbu/BCDED.TXT BCDED.TXT 2> /dev/null
	cp -a initrmfs/usr/share/pixmaps/ifl_partwork_48x48.png ifl_partwork_48x48.png 2> /dev/null
	echo "Setting up INI files for partwork"
	for bibmfile in BOOTITBM.INI BOOTITBM-CUSTOM.INI
	do
		keyini="${bibmfile} license productkey"
		userini="${bibmfile} license user"
		keyver="${bibmfile} license keyver 2"
		if [ ! -f $bibmfile ]; then
			WriteIniValue $keyini "$BIBMProductKey"
			WriteIniValue $userini "$BIBMUserName"
			WriteIniValue $keyver
		elif [ "$bibmfile" = "BOOTITBM-CUSTOM.INI" ]; then
			# update custom file for other scripts
			WriteIniValue $keyini "$BIBMProductKey"
			WriteIniValue $userini "$BIBMUserName"
			WriteIniValue $keyver
		fi
	done
fi

# delete the extracted root fs - we're finished with it
rm -r initrmfs 2> /dev/null

# delete files only needed in Windows
for f in makedisk.exe makedisk.cfg SYSLINUX.F35
do
	if [ -f "$f" ]; then rm $f; fi
done

# chown all files and directories to owner:group
# as precaution make sure running from IFL dir, otherwise don't do it
if [ "$0" = "./setup" ]; 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

echo

if [ "$checkedd" = "1" ]; then
	echo "STEP $Nextstep: Check the status of the Linux edd module"
	edd=0
	if [ -e /sys/firmware/edd ]; then edd=1; fi

	if [ "$edd"  = "0" ]; then
		kversion=`uname -r`
		kseries1=${kversion:0:3}
		kseries2=${kversion:0:2}
		if [ "$kseries1" = "2.6" ]; then
			$modprobepath edd 2> /dev/null
			if [ -e /sys/firmware/edd ]; then
				edd=2	#exists, but loaded manually
			else
				modinfo edd > /dev/null 2>&1
				if [ "$?" = "0" ]; then
					edd=5 # uefi system
				else
					edd=3 #is 2.6, but no edd
				fi
			fi
		elif [ "$kseries2" = "3." ] || [ "$kseries2" = "4." ]; then
			$modprobepath edd 2> /dev/null
			if [ -e /sys/firmware/edd ]; then
				edd=2	#exists, but loaded manually
			else
				modinfo edd > /dev/null 2>&1
				if [ "$?" = "0" ]; then
					edd=5 # uefi system
				else
					edd=3 #is 3.x, but no edd
				fi
			fi
		else
			edd=4 #is kernel < 2.6 series
		fi
	fi

	if [ "$edd" = "5" ]; then
		echo
		echo "**************************** PLEASE READ BELOW ****************************"
		echo "***************************************************************************"
		echo
		echo "Linux edd status 5: The edd module is available but fails to load"
		echo
		echo "This usually means it's a UEFI system, and edd is not relevant"
		echo
		echo "Please refer to the file edd.txt in the help directory for additional"
		echo "information on edd."
		echo
		echo "***************************************************************************"
	elif [ "$edd" = "4" ]; then
		echo
		echo "**************************** PLEASE READ BELOW ****************************"
		echo "***************************************************************************"
		echo
		echo "Linux edd status 4: The edd module is not available due to old kernel"
		echo
		echo "This can affect restore operations to an empty hard drive (empty meaning"
		echo "no partitions) while running IFL from this Linux distribution. This does"
		echo "not affect any imaging operations from the IFL boot media."
		echo
		echo "Please refer to the file edd.txt in the help directory for additional"
		echo "information on edd."
		echo
		echo "***************************************************************************"
	elif [ "$edd" = "3" ]; then
		echo
		echo "**************************** PLEASE READ BELOW ****************************"
		echo "***************************************************************************"
		echo
		echo "Linux edd status 3: The edd module is not included in the Linux kernel"
		echo
		echo "This can affect restore operations to an empty hard drive (empty meaning"
		echo "no partitions) while running IFL from this Linux distribution. This does"
		echo "not affect any imaging operations from the IFL boot media."
		echo
		echo "Please refer to the file edd.txt in the help directory for additional"
		echo "information on edd."
		echo
		echo "***************************************************************************"
	elif [ "$edd" = "2" ]; then
		echo
		echo "**************************** PLEASE READ BELOW ****************************"
		echo "***************************************************************************"
		echo    
		echo "Linux edd status 2: The edd module is available but not loaded on boot"
		echo
		echo "This can affect restore operations to an empty hard drive (empty meaning"
		echo "no partitions) while running IFL from this Linux distribution. This does"
		echo "not affect any imaging operations from the IFL boot media."
		echo
		echo "This issue can be corrected by a simple edit to a boot script. Please"
		echo "refer to the file edd.txt in the help directory for additional information"
		echo "on edd"
		echo 
		echo "***************************************************************************"
	elif [ "$edd" = "1" ]; then
		echo "Linux edd status 1: The edd module is available and loaded"
	fi
	echo
fi
if [ -f /tbu/utility/running ]; then
	echo
	echo "Setup is now complete. The /tbu/iflbuild directory is now set up to create"
	echo "both default and custom versions of IFL boot media, with or without network"
	echo "support."
else
	echo
	echo "Setup is now complete. Both network (iflnet.iso) and non-network (ifl.iso)"
	echo "versions are available to create boot media from. In addition, the iflbuild"
	echo "script is available as a front end for common uses of the make scripts."
	echo
	echo "NOTE: To access drives as a normal user with IFL or tbosdt, it may be"
	echo "necessary to add the user to the 'disk' group. Please see the KB article"
	echo "at the link below for additional information:"
	echo "http://www.terabyteunlimited.com/kb/article.php?id=567"
	if [ "$isx64" = "1" ]; then
		echo
		echo "Final Note: On this 64-bit Linux system, you’ll normally want to use the"
		echo "64-bit applications (their names end in 64).  If you’d rather run the"
		echo "32-bit versions, just be sure to install the required 32-bit shared"
		echo "libraries first. For step-by-step guidance, check the KB article:"
		echo "http://www.terabyteunlimited.com/kb/article.php?id=566"
	fi
fi
echo
