#!/bin/bash

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

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 "Required file modprobe (typically /sbin/modprobe) not found on the system"
fi
if [ ! -e iflnet.iso ]; then
    iok=1
    echo "Required file iflnet.iso not found in the IFL directory (case matters)"
fi
if [ ! `which unzip 2> /dev/null` ]; then
    iok=1
    echo "Required program unzip not found on system. This can usually be corrected"
    echo "by installing the unzip package."
fi
if [ ! -e config.zip ]; then
    iok=1
    echo "Required file config.zip not found in the IFL directory"
elif [ "$iok" = "0" ]; then
    # check if config.zip has been extracted yet
    for i in wireless util iscsi tbosdtfiles
    do
	if [ -d $i ]; then uz=1; break; else uz=0; fi
	break
    done
    if [ "$uz" = "1" ]; then
	echo "The file config.zip already has been extracted"
    else
	echo "Extracting the file config.zip"
	unzip -q config.zip
    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 "Required file cpio (tpyically /bin/cpio) not found on system"
        break
    else
        cpioversion=`$cpiopath --version`
        echo "Using cpio version $cpioversion"
        break
    fi
done

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

if [ "$iok" = "1" ]; then
    echo
    echo "ERROR: One or more required files not found"
    echo "See above messages for details"
    echo
    exit 1
else
    echo "All required files found"
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
./util/tbosdt getiflnetfiles.run
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
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

# 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
    ProductKeySearch=`grep -o -m1 ProductKey=.............. cdroot/isolinux.cfg`
    if [ "$ProductKeySearch" = "" ]; then
	CurrentProductKey=XXXX-YYYY-ZZZZ
    else
	CurrentProductKey=`echo ${ProductKeySearch:11}`
    fi
    if [ "$CurrentProductKey" = "XXXX-YYYY-ZZZZ" ]; then
	if [ -e ifl.ini ]; then
	    ProductKeySearch=`grep -o -m1 ProductKey=.............. ifl.ini`
	    if [ ! "$ProductKeySearch" = "" ]; then
		ProductKeyValue=`echo ${ProductKeySearch:11}`
		ProductKeyValue=`echo $ProductKeyValue | tr "[:lower:]" "[:upper:]"`
    		if [ ! "$ProductKeyValue" = "XXXX-YYYY-ZZZZ" ]; then
        	    for i in 0 1 2 3 5 6 7 8 10 11 12 13
        	    do
            		pkeychar=`echo ${ProductKeyValue:$i:1}`
            		pkeycharvalid=0
            		for j in 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
            		do
                	    if [ "$j" = "$pkeychar" ]; then
                    		pkeycharvalid=1
                    		break
                	    fi
            		done
            		if [ "$pkeycharvalid" = "0" ]; then break; fi
        	    done
        	    if [ "$pkeycharvalid" = "1" ]; then
            		for i in 4 9
            		do
                	    pkeychar=`echo ${ProductKeyValue:$i:1}`
                	    if [ ! "$pkeychar" = "-" ]; then
                    		pkeycharvalid=0
                    		break
                	    fi
            		done
        	    fi
        	    if [ "$pkeycharvalid" = "1" ]; then CurrentProductKey=$ProductKeyValue; fi
    		fi
    	    fi
	fi
    fi
    if [ "$CurrentProductKey" = "XXXX-YYYY-ZZZZ" ]; then
	chroot initrmfs /usr/bin/setproductkey 
    else
	chroot initrmfs /usr/bin/setproductkey $CurrentProductKey
    fi
    if [ -e initrmfs/tmp/ProductKeyValue ]; then
	ProductKey=`cat initrmfs/tmp/ProductKeyValue`
    else
	ProductKey=$CurrentProductKey
    fi
    ProductKeyText="ProductKey=$ProductKey"

    # update isolinux.cfg main boot disk for ProductKey - V2 full only
    if [ -f initrmfs/tbu/utility/gui ] && [ -f initrmfs/tbu/utility/x64 ]; then
	echo "timeout 50" > cdroot/isolinux.cfg
	echo "kbdmap qwerty.ktl" >> cdroot/isolinux.cfg
	echo "prompt 1" >> cdroot/isolinux.cfg
	echo "display menu.txt" >> cdroot/isolinux.cfg
	echo "default 2" >> cdroot/isolinux.cfg
	echo "label 1" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=794 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 2" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=791 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 3" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=788 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 4" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=785 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 4gh" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=791 switchx=yes mem=2G iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	# UEFI grub.cfg file
	chmod +w cdroot/boot/grub/grub.cfg*
	if [ "$ProductKey" = "XXXX-YYYY-ZZZZ" ]; then
	    cp cdroot/boot/grub/grub.cfg-default cdroot/boot/grub/grub.cfg
	else
	    cat cdroot/boot/grub/grub.cfg-default | sed -e "s/XXXX-YYYY-ZZZZ/$ProductKey/" > cdroot/boot/grub/grub.cfg
	fi
    elif [ -f initrmfs/tbu/utility/gui ] && [ ! -f initrmfs/tbu/utility/x64 ]; then
	echo "timeout 50" > cdroot/isolinux.cfg
	echo "kbdmap qwerty.ktl" >> cdroot/isolinux.cfg
	echo "prompt 1" >> cdroot/isolinux.cfg
	echo "display menu.txt" >> cdroot/isolinux.cfg
	echo "default 1" >> cdroot/isolinux.cfg
	echo "label 1" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=773 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 2" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=773 xres=1024 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 3" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=773 xres=800 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 4" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=773 xres=640 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 1fb" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=794 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 2fb" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=791 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 3fb" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=788 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 4fb" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=785 switchx=yes iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 4gh" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=773 mem=2G iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	# UEFI grub.cfg file
	chmod +w cdroot/boot/grub/grub.cfg*
	if [ "$ProductKey" = "XXXX-YYYY-ZZZZ" ]; then
	    cp cdroot/boot/grub/grub.cfg-default cdroot/boot/grub/grub.cfg
	else
	    cat cdroot/boot/grub/grub.cfg-default | sed -e "s/XXXX-YYYY-ZZZZ/$ProductKey/" > cdroot/boot/grub/grub.cfg
	fi
    else
	echo "timeout 50" > cdroot/isolinux.cfg
	echo "kbdmap qwerty.ktl" >> cdroot/isolinux.cfg
	echo "prompt 1" >> cdroot/isolinux.cfg
	echo "display menu.txt" >> cdroot/isolinux.cfg
	echo "default 1" >> cdroot/isolinux.cfg
	echo "label 1" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=0 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 2" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=773 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 3" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=771 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 4" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=769 iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 5" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=ask iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	echo "label 4gh" >> cdroot/isolinux.cfg
	echo " kernel vmlinuz" >> cdroot/isolinux.cfg
	echo " append vga=0 mem=2G iflkmap=us ktl=qwerty initrd=initrmfs.gz iflbflag=0  $ProductKeyText" >> cdroot/isolinux.cfg
	# UEFI grub.cfg file
	chmod +w cdroot/boot/grub/grub.cfg*
	if [ "$ProductKey" = "XXXX-YYYY-ZZZZ" ]; then
	    cp cdroot/boot/grub/grub.cfg-default cdroot/boot/grub/grub.cfg
	else
	    cat cdroot/boot/grub/grub.cfg-default | sed -e "s/XXXX-YYYY-ZZZZ/$ProductKey/" > cdroot/boot/grub/grub.cfg
	fi
    fi

    # rebuild iflnet.iso in chroot
    chroot initrmfs /usr/bin/dialog --no-shadow --infobox "   Please wait..." 3 25
    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

    # do ifl.ini for ProductKey - add to existing file contents if applicable
    if [ ! -e ifl.ini ]; then touch ifl.ini; fi
    grep -v -i "[LICENSE]" ifl.ini > i.ini2
    grep -v -i "ProductKey=" i.ini2 > i.ini3
    echo "[LICENSE]" > i.ini4
    echo "$ProductKeyText" >> i.ini4
    cat i.ini4 i.ini3 > ifl.ini
    rm i.ini* 2> /dev/null

    # optionally get partwork name/key if gui reg version
    if [ "$gui" = "1" ]; then
	if [ -f BOOTITBM.INI ]; then cp -a BOOTITBM.INI initrmfs/tbu/BOOTITBM.INI; fi
	chroot initrmfs /usr/bin/setpartwork
	BIBMProductKey=`cat initrmfs/tmp/ProductKey`
	BIBMUserName=`cat initrmfs/tmp/UserName`
	if [ "$BIBMProductKey" = "" ]; then BIBMProductKeyText="None"; else BIBMProductKeyText=$BIBMProductKey; fi
	if [ "$BIBMUserName" = "" ]; then BIBMUserNameText="None"; else BIBMUserNameText=$BIBMUserName; fi
	if [ -f initrmfs/tbu/BOOTITBM.INI ]; then mv initrmfs/tbu/BOOTITBM.INI BOOTITBM.INI; fi
	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 -n "STEP 3: IFL Product Key: "
	if [ "$ProductKey" = "XXXX-YYYY-ZZZZ" ]; then
    	    echo "None"
	else
    	    echo $ProductKey
	fi
	echo
	echo "STEP 4: BIBM Product Key: $BIBMProductKeyText  BIBM Licensed Name: $BIBMUserNameText"
	echo
	Nextstep=5
	rm initrmfs/tmp/* 2> /dev/null
    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 -n "STEP 3: IFL Product Key: "
	if [ "$ProductKey" = "XXXX-YYYY-ZZZZ" ]; then
	    echo "None"
	else
	    echo $ProductKey
	fi
	echo
	Nextstep=4
    fi
else
    echo
    Nextstep=3
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"
if [ -f initrmfs/tbu/utility/gui ] && [ -f initrmfs/tbu/utility/x64 ]; then
    echo "" > cdroot/menu.txt
    echo "Image For Linux (GUI) Boot Disk - TeraByte, Inc." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "Boot Menu:" >> cdroot/menu.txt
    echo "<1>  1280x1024 frame buffer mode" >> cdroot/menu.txt
    echo "<2>  1024x768 frame buffer mode" >> cdroot/menu.txt
    echo "<3>  800x600 frame buffer mode" >> cdroot/menu.txt
    echo "<4>  640x480 frame buffer mode" >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "For systems that fail to start the GUI after boot, please try" >> cdroot/menu.txt
    echo "another video mode from the list above (e.g. boot: 3)." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "Booting default <2> in 5 seconds. Press <Enter> to boot now." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    if [ "$full" = "1" ]; then
	cat cdroot/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" | sed -e "s/XXXX-YYYY-ZZZZ/$ProductKey/" > cdroot/boot/grub/grub.cfg
    else
	cat cdroot/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" > cdroot/boot/grub/grub.cfg
    fi
elif [ -f initrmfs/tbu/utility/gui ] && [ ! -f initrmfs/tbu/utility/x64 ]; then
    echo "" > cdroot/menu.txt
    echo "Image For Linux (GUI) Boot Disk - TeraByte, Inc." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "Boot Menu:" >> cdroot/menu.txt
    echo "<1>  Best available graphics mode" >> cdroot/menu.txt
    echo "<2>  1024x768 graphics mode" >> cdroot/menu.txt
    echo "<3>  800x600 graphics mode" >> cdroot/menu.txt
    echo "<4>  640x480 graphics mode" >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "For systems that fail to start the GUI after boot, please use" >> cdroot/menu.txt
    echo "frame buffer option 1fb, 2fb, 3fb, or 4fb (e.g. boot: 2fb)." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "Booting default <1> in 5 seconds. Press <Enter> to boot now." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    if [ "$full" = "1" ]; then
	cat cdroot/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" | sed -e "s/XXXX-YYYY-ZZZZ/$ProductKey/" > cdroot/boot/grub/grub.cfg
    else
	cat cdroot/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" > cdroot/boot/grub/grub.cfg
    fi
else
    echo "" > cdroot/menu.txt
    echo "Image For Linux (CUI) Boot Disk - TeraByte, Inc." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "Boot Menu:" >> cdroot/menu.txt
    echo "<1>  80x25 text mode" >> cdroot/menu.txt
    echo "<2>  1024x768 frame buffer mode" >> cdroot/menu.txt
    echo "<3>  800x600 frame buffer mode" >> cdroot/menu.txt
    echo "<4>  640x480 frame buffer mode" >> cdroot/menu.txt
    echo "<5>  Select alternate video mode during boot" >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    echo "Booting default <1> in 5 seconds. Press <Enter> to boot now." >> cdroot/menu.txt
    echo "" >> cdroot/menu.txt
    if [ "$full" = "1" ]; then
	cat cdroot/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" | sed -e "s/XXXX-YYYY-ZZZZ/$ProductKey/" > cdroot/boot/grub/grub.cfg
    else
	cat cdroot/boot/grub/grub.cfg-default | sed -e "s/Network Boot/Boot/" > cdroot/boot/grub/grub.cfg
    fi
fi

# 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
    if [ -f cdboot/rdvmode ]; then
	vmode=`cat cdboot/rdvmode`
    else
	vmode=1
    fi
    echo $Currentkbd > initrmfs/tbu/utility/rdiflkmap
    echo $Currentktl > initrmfs/tbu/utility/rdktl
    if [ "$vmode" != "1" ]; then echo $vmode > 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.zip"; else langfilefinish="_gui_trial.zip"; fi
    elif [ "$gui" = "0" ]; then
	if [ "$full" = "1" ]; then langfilefinish=".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 -n "STEP 3: IFL Product Key: "
	if [ "$ProductKey" = "XXXX-YYYY-ZZZZ" ]; then
	    echo "None"
	else
	    echo $ProductKey
	fi
	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 [ -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 $ProductKeyText
    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 6: Setting up partwork files in the /tbu/iflbuild directory"
	Nextstep=7
    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/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
        if [ ! -f $bibmfile ]; then
	    echo "[LICENSE]" > $bibmfile
	    echo "ProductKey=$BIBMProductKey" >> $bibmfile
	    echo "User=$BIBMUserName" >> $bibmfile
	    echo "[OPTIONS]" >> $bibmfile
	elif [ "$bibmfile" = "BOOTITBM-CUSTOM.INI" ]; then
	    # already done in setpartwork and copied over for BOOTITBM.INI
	    grep -v -i "[LICENSE]" $bibmfile > b.ini2
	    grep -v -i "ProductKey=" b.ini2 > b.ini3
	    grep -v -i "User=" b.ini3 > b.ini4
	    echo "[LICENSE]" > b.ini5
	    echo "ProductKey=$BIBMProductKey" >> b.ini5
	    echo "User=$BIBMUserName" >> b.ini5
	    cat b.ini5 b.ini4 > $bibmfile
	    rm b.ini* 2> /dev/null
	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 [ "$1" = "/edd" ]; 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"
    uname -a | grep -i "x86_64" > /dev/null
    if [ "$?" = "0" ] && [ "$gui" = "1" ]; then
	echo
	echo "IMPORTANT: On 64-bit distributions, 32-bit shared libraries will need to be"
	echo "installed to run IFL (GUI). Please see the KB article at the link below:"
	echo "http://www.terabyteunlimited.com/kb/article.php?id=566"
    fi
fi
echo
