Live DVD

From LinuxMCE
Revision as of 10:41, 30 March 2012 by L3mce (Talk | contribs) (firstboot)

(diff) ←Older revision | view current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

This wiki attempts to explain the live DVD creation techniques used to produce a universally installable 1004 LinuxMCE DVD with lmcemaster.sh

This builds off of a loop mounted DD image which must be created separately. I have linked for reference the original code which creates that base image. The DD process was put together by possy to create very very small images for me to download, because my internet connection trickles through a swizzle straw. That process can be found at the bottom under image.sh. I have removed the parts which crush this into a tiny rzip image.


Directory Structure

You will note the script creates 3 temporary folders.

$ISODIR is the file structure of the DVD itself. This contains the casper/ubiquity bits, the sqashed file system, bootloader and preseed data. The only files placed here should relate to the operations of the DVD itself. [[1]]

On the DVD itself $ISODIR becomes /cdrom/

$WORKDIR is the work in progress, that is to say the file structure that will be installed on the target machine from the dvd. This root directory is where we put things, and manipulate them for the most part instead of the host. There are some catch-22s which require us to manipulate the host image prior to its being copied to this directory.

On the DVD itself $WORKDIR becomes /target/

$DDDIR is the chrooted host directory structure we are building the DVD to install from. This file structure is ALSO the host environment on the DVD which Ubiquity functions over top of, and how we will facilitate live booting. This expects a DD image, which is then loop mounted to a temporary directory for manipulation. As little change as possible should be made to this directory. If you destroy/move things around in here, those changes persist, making it difficult or impossible to create more than one DVD from a single image.

On the DVD $DDDIR becomes /root/


The WORKDIR directory will serve as the host environment on the live DVD over which ubiquity is run. The WORKDIR is also the file system which will be installed on the hard drive, and become /target on the DVD after it is installed to the drive. Post operation can occur via the d-i preseed/late_command in the preseed.cfg file. The DDDIR and WORKDIR look identical on the DVD save the addition of the /target directory on the DDDIR, which contains the mounted WORKDIR. Chroot operations can occur to that /target directory as well.

Generated Files

We create a few files throughout this process. This explains what and why.

interfaces.temp This file sets two nics as dhcp so as to find internet when needed, as when it is needed, it is needed. This file is used twice. The chrooted environment needs internet and presumes there are two nics, and doesn't know which one it is on. The post installer needs internet prior to DCE nic configuration and presumes the same. If there is only one nic avail, this still works, though it is hacky and I do not like it. Exists at /target/etc/network

 auto lo
 iface lo inet loopback
 
 auto eth0
 iface eth0 inet dhcp
 
 auto eth1
 iface eth1 inet dhcp


isolinux.cfg this is the boot configuration for isolinux. This sets up the menu, and specifies boot options etc as well as layout options and the preseed file. Colors are in hex format, preceded by an alpha level ATRRGGBB where AT=Alpha Transparency RR=Red GG=Green BB=Blue (example FFFC9306). Exists at /cdrom/isolinux/isolinux.cfg

default vesamenu.c32
prompt 0
timeout 450
totaltimeout 450

menu width 78
menu margin 14
menu rows 6
menu vshift 2
menu timeoutrow 11
menu tabmsgrow 10
menu background splash.png
menu title $LIVECDLABEL
menu color tabms 0 #fffc9306 #fffc9306 std
menu color timeout 0 #ff000000 #fffc9306 std
menu color border 0 #ffffffff #ee000000 std
menu color title 0 #ff00ff00 #ee000000 std
menu color sel 0 #ffffffff #fffc9306 std
menu color unsel 0 #ffffffff #ee000000 std
menu color hotkey 0 #ff00ff00 #ee000000 std
menu color hotsel 0 #ffffffff #85000000 std
#####menu color option  forground #ALPHA/R/G/B  background #ALPHA/R/G/B
#####blue ff98a5e0

label live
  menu label Live - Boot LinuxMCE Live! from DVD
  kernel /casper/vmlinuz
  append preseed/file=/cdrom/preseed.cfg boot=casper initrd=/casper/initrd.gz quiet splash --

label install
  menu label Install LinuxMCE - Start the installer
  kernel /casper/vmlinuz
  append preseed/file=/cdrom/preseed.cfg boot=casper only-ubiquity initrd=/casper/initrd.gz quiet splash --

label xforcevesa
  menu label xforcevesa - boot Live in safe graphics mode
  kernel /casper/vmlinuz
  append preseed/file=/cdrom/preseed.cfg boot=casper xforcevesa initrd=/casper/initrd.gz quiet splash --

label memtest
  menu label memtest - Run memtest
  kernel /isolinux/memtest
  append -

label hd
  menu label hd - boot the first hard disk
  localboot 0x80
append -

preseed.cfg There are a LOT of possible options for this menu. I am currently only disabling language packs, performing autoconfig for the dvd host (not the target mind you), and performing the post-install (note, late_command not currently working). Exists at /cdrom/preseed.cfg and at /cdrom/casper/preseed.cfg

tasksel tasksel/first multiselect
d-i pkgsel/install-language-support boolean false
d-i preseed/early_command string service mysql stop 
d-i netcfg/choose_interface select auto
d-i finish-install/reboot_in_progress note
ubiquity ubiquity/success_command string bash /cdrom/install/postseed.sh 

preseedco.cfg This is the second preseed file for core only installs.

tasksel tasksel/first multiselect
d-i pkgsel/install-language-support boolean false
d-i preseed/early_command string service mysql stop 
d-i netcfg/choose_interface select auto
#d-i finish-install/reboot_in_progress note
ubiquity ubiquity/success_command string bash /cdrom/install/postseedco.sh

postseed.sh This is the local file which mounts the target appropriately to perform the post install, and launches said post install and the local OnScreenDisplay which alerts the installer what is occurring. This is problematic atm. It exists at /cdrom/install/postseed.sh

#!/bin/bash
mount -o bind /dev /target/dev
mount -t proc none /target/proc
mount -t devpts none /target/dev/pts
mount -t proc sysfs /target/sys
#cp /etc/udev/rules.d/70-persistent-net.rules /target/etc/udev/rules.d
su - ubuntu -c /cdrom/install/messages.sh &
coreOnly="0" chroot /target /root/new-installer/postinst.sh
sleep 2
reboot

postseedco.sh This file is called by the preseedco file to specify core only configuration

mount -o bind /dev /target/dev
mount -t proc none /target/proc
mount -t devpts none /target/dev/pts
mount -t proc sysfs /target/sys
#cp /etc/udev/rules.d/70-persistent-net.rules /target/etc/udev/rules.d
su - ubuntu -c /cdrom/install/messages.sh &
coreOnly="1" chroot /target /root/new-installer/postinst.sh
sleep 2
reboot

messages.sh This makes use of BootMessages.sh, which the gnome on-screen display utility. This method prevents the messages from blinking... however defining and calling these messages is proving elusive atm. I can drop to tty and export DISPLAY=:0 and run the script and it works like a dream. Calling it from the script the preseed calls isn't working atm. exists at /cdrom/install/messages.sh

#!/bin/bash
export DISPLAY=:0
OSD_Message() {
	gnome-osd-client --full --dbus "<message id='bootmsg' osd_fake_translucent_bg='off' osd_vposition='center' hide_timeout='10000000' osd_halignment='center'>\$*</message>"
}

msgchk=/target/tmp/msgchk
newmsg=/target/tmp/messenger
touch \$newmsg

if [ ! -f \$msgchk ]; then 
	sudo touch -r \$msgchk 
fi

while true; do
	if [ \$newmsg -nt \$msgchk ]; then
		sleep 1
		OSD_Message "\$(cat \$newmsg)"
		sudo touch -r \$newmsg \$msgchk
	fi

	if [ "\$(cat \$newmsg)" == "Reboot" ]; then
		OSD_Message " "
		break
	fi
done


postinst.sh is the post installer. This is designed to be run from the preseed post, which chroots into the /target directory and performs the post install before rebooting. It is currently being run on reboot, which will itself need to be rebooted when finished. Should it be run chrooted, the mysqld commands must be unhashed for version control. Most functions called here are from #dvd-installer.sh. Exists at /target/root/new-installer/postinst.sh

#!/bin/bash
. /usr/pluto/bin/dvd-installer.sh
echo "/bin/false" > /etc/X11/default-display-manager
export LC_ALL=C
log_file=/var/log/LinuxMCE_Setup.log
Messg_File=/tmp/messenger
echo "Running post-install. Do NOT reboot." > \$Messg_File
service mysql stop
sleep 2
mysqld --skip-networking&
sleep 1
#Execute Functions
echo "Setting up TTY options" > \$Messg_File
addAdditionalTTYStart
echo "Fixing EMI" > \$Messg_File
TempEMIFix
echo "Setting initial boot prep" > \$Messg_File
InitialBootPrep
rm /root/new-installer/spacemaker
echo "Removing ubiquity and casper options" > \$Messg_File
apt-get -y remove --purge --force-yes ubiquity ubiquity-casper ubiquity-ubuntu-artwork ubiquity-frontend-kde casper
echo "Configuring DCERouter" > \$Messg_File
Setup_Pluto_Conf
Create_And_Config_Devices
echo "Updating initramfs" > \$Messg_File
update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth /lib/plymouth/themes/LinuxMCE/LinuxMCE.plymouth 900
update-initramfs -u
echo "Unmounting and shutting down MySQL" > \$Messg_File
umount -lf /dev/pts
umount -lf /sys
umount -lf /proc
service mysql stop
killall -9 mysqld_safe
kill \`lsof |grep mysqld|cut -d" " -f3|sort -u\` ||:
umount -lf /dev
echo "Please wait while your Core reboots" > \$Messg_File
sleep 3
echo "Reboot" > \$Messg_File
#rm /target/tmp/messenger


prepmaster.sh This file prepares the root image for install from DVD.

#!/bin/bash
. /usr/pluto/bin/dvd-installer.sh
mysqld --skip-networking&
sleep 5
gpgUpdate
StatusMessage "Pre-installing needed packages"
Pre-InstallNeededPackages
CreatePackagesFiles
PreSeed_Prefs
Fix_Initrd_Vmlinux
ReCreatePackagesFiles
StatusMessage "Cleaning up install"
#CleanInstallSteps
apt-get remove -yq popularity-contest
apt-get remove -y festival
apt-get remove -y *java*


README.diskdefines Defines the architecture, diskname etc. Exists at /cdrom/README.diskdefines and /cdrom/casper/README.diskdefines

#define DISKNAME  $LIVECDLABEL
#define TYPE  binary
#define TYPEbinary  1
#define ARCH  $ARCH
#define ARCH$ARCH  1
#define DISKNUM  1
#define DISKNUM1  1
#define TOTALNUM  0
#define TOTALNUM0  1

_________________________________________________________________________________________________________________


Moved upstart jobs

I am also moving and rewriting the following files for various reasons/conflicts from /etc/init.d, and using the opportunity to run a couple of commands on boot. I will probably add more to this list as the enormous list of things running for LMCE slow down the operation of the DVD. These files are moved to /root/new-installer/lmcemaster/runners


0start_avwizard - we need to do some work before we try that.

apache2 - no reason for this to run till there is a reason

apparmor

asterisk

bind9

linuxmce - absent avwizard, linuxmce will attempt to run.

mediatomb

nis - ypbind server fails and takes forever to do so. Painful.

smbd

postseed

The Move

The move is the process of creating the required subdirectories in the WORKDIR, and copying over most of the DDDIR. The majority of the move is done with rsync in the /etc folder. cp is used for the home directory to capture hidden files. Then install specific files are removed. During this time, the initrd.gz, vmlinuz, vesamenu32, and isolinux.bin files are created or moved. The plymouth theme is also created at this and the initramfs is generated, and the process is then repeated and updated with the -u option as the shutdown screen from the original was persisting after the make.

The Squash

Both the WORKDIR and the DDDIR file systems are squashed. The file system, again, is the base of the target image. The working DDDIR file system is the FS the DVD is running, and that which casper takes its cues from as to how to implement the backend to the WORKDIR target. Ubiquity is the front end with the KDE installer which installs the root system for kubuntu, using the casper ghosting. Again... key pieces that you want on the target that are specific to our system should go in the work directory.


Main Scripts

lmcemaster.sh

#!/bin/bash
##################################################################
# This script creates an installable DVD iso from a base dd
# image file, specified as IMAGEFILE below. This currently 
# presumes that the video-wizard-videos package is in the same 
# directory. Please contact Jason l3droid@gmail.com with 
# problems/questions. This script is free under GNU2 license.
##################################################################
# About the boot process for the iso produced. Some startup scripts 
# are suspended and one is replaced to kill nbd directories and
# launch the dvd-installer.sh. After the install kde is overwritten
# as the default display manager on exit, as the install brings it 
# back. See http://wiki.linuxmce.org/index.php/Live_DVD for details

set -e

DDDIR=`mktemp -d 1004-dd.XXXXXXXXXX`
WORKDIR=`mktemp -d 1004-wrk.XXXXXXXXXX`
ISODIR=`mktemp -d 1004-iso.XXXXXXXXXX`
NEWINST="/root/new-installer"
DDMASTER="$DDDIR$NEWINST"
WORKMASTER="$WORKDIR$NEWINST"
CUSTOMISO="LMCE-1004-`date +%Y%m%d%H%M`.iso"
LIVECDLABEL="LinuxMCE 10.04 Live CD"
CDBOOTTYPE="ISOLINUX"
LIVECDURL="http://www.linuxmce.org"
IMAGEFILE=1004
VERSION=10
ARCH=i386

### Mount the image and create some required directories in the temporary folders
mount -o loop $IMAGEFILE $DDDIR
mount none -t proc $DDDIR/proc
mount none -t devpts $DDDIR/dev/pts
mount none -t sysfs $DDDIR/sys
mkdir -p $ISODIR/{casper,isolinux,install,.disk}
mkdir -p $DDDIR/usr/sbin
mkdir -p $DDDIR/root/new-installer
mkdir -p $WORKMASTER/runners

trap futureTrap EXIT
futureTrap () {
	mounted=$(mount | grep 1004-dd | grep none | awk '{print $3}')
	for mounts in $mounted; do umount -lf $mounts; done
	umount -lf `mount | grep 1004-dd | grep loop | awk '{print $3}'`
	sleep 1
	rm -r $DDDIR
	rm -r $WORKDIR
	rm -r $ISODIR	
}

echo "LinuxMCE will now be mastered to an iso image."
echo "Creating scripts"
	
#### Set temporary network file
# TODO There has to be a less hacky way to do this. Delay while one or the other timeout is unnecessarily long
# Please note that this file is used during the install process of the dvd so should not be removed even if your
# chroot environment does not require it... which it shouldn't.
cat <<EOL > $DDDIR/etc/network/interfaces.temp
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

auto eth1
iface eth1 inet dhcp
EOL
cp $DDDIR/etc/network/interfaces.temp $DDDIR/etc/network/interfaces


# Create the dvd boot config menu	
	cat <<EOL > $ISODIR/isolinux/isolinux.cfg
default vesamenu.c32
prompt 2
timeout 450
totaltimeout 0

menu width 78
menu margin 14
menu rows 6
menu vshift 2
menu timeoutrow 12
menu tabmsgrow 13
menu background splash.png
menu title $LIVECDLABEL
menu color tabmsg 0 #fffc9306 #00fc9306 std
menu color timeout 0 #ff000000 #00fc9306 std
menu color border 0 #ffffffff #ee000000 std
menu color title 0 #ff00ff00 #ee000000 std
menu color sel 0 #ffffffff #fffc9306 std
menu color unsel 0 #ffffffff #ee000000 std
menu color hotkey 0 #ff00ff00 #ee000000 std
menu color hotsel 0 #ffffffff #85000000 std
#####menu color option  forground #ALPHA/R/G/B  background #ALPHA/R/G/B
#####blue ff98a5e0

label live
  menu label Live - Boot LinuxMCE Live! from DVD
  kernel /casper/vmlinuz
  append preseed/file=/cdrom/preseed.cfg boot=casper initrd=/casper/initrd.gz quiet splash --

label hybrid
  menu label Install LinuxMCE Hybrid - Core + MD
  kernel /casper/vmlinuz
  append preseed/file=/cdrom/preseed.cfg boot=casper only-ubiquity initrd=/casper/initrd.gz quiet splash --

label core
  menu label Install LinuxMCE Core - Headless Core
  kernel /casper/vmlinuz
  append preseed/file=/cdrom/preseedco.cfg boot=casper only-ubiquity initrd=/casper/initrd.gz quiet splash --

label xforcevesa
  menu label xforcevesa - boot Live in safe graphics mode
  kernel /casper/vmlinuz
  append preseed/file=/cdrom/preseed.cfg boot=casper xforcevesa initrd=/casper/initrd.gz quiet splash --

label memtest
  menu label memtest - Run memtest
  kernel /isolinux/memtest
  append -

label hd
  menu label hd - boot the first hard disk
  localboot 0x80
append -
EOL
  
# Make hybrid preseed file
cat <<EOL > $ISODIR/preseed.cfg
tasksel tasksel/first multiselect
d-i pkgsel/install-language-support boolean false
d-i preseed/early_command string service mysql stop 
d-i netcfg/choose_interface select auto
#d-i finish-install/reboot_in_progress note
ubiquity ubiquity/success_command string bash /cdrom/install/postseed.sh
EOL
cp $ISODIR/preseed.cfg $ISODIR/casper

# Make core only preseed file
cat <<EOL > $ISODIR/preseedco.cfg
tasksel tasksel/first multiselect
d-i pkgsel/install-language-support boolean false
d-i preseed/early_command string service mysql stop 
d-i netcfg/choose_interface select auto
#d-i finish-install/reboot_in_progress note
ubiquity ubiquity/success_command string bash /cdrom/install/postseedco.sh
EOL
cp $ISODIR/preseed.cfg $ISODIR/casper

cat <<EOL > $ISODIR/install/postseed.sh
#!/bin/bash
mount -o bind /dev /target/dev
mount -t proc none /target/proc
mount -t devpts none /target/dev/pts
mount -t proc sysfs /target/sys
#cp /etc/udev/rules.d/70-persistent-net.rules /target/etc/udev/rules.d
su - ubuntu -c /cdrom/install/messages.sh &
coreOnly="0" chroot /target /root/new-installer/postinst.sh
sleep 2
reboot
EOL

cat <<EOL > $ISODIR/install/postseedco.sh
#!/bin/bash
mount -o bind /dev /target/dev
mount -t proc none /target/proc
mount -t devpts none /target/dev/pts
mount -t proc sysfs /target/sys
#cp /etc/udev/rules.d/70-persistent-net.rules /target/etc/udev/rules.d
su - ubuntu -c /cdrom/install/messages.sh &
coreOnly="1" chroot /target /root/new-installer/postinst.sh
sleep 2
reboot
EOL

### Make On Screen Display
cat <<EOL > $ISODIR/install/messages.sh
#!/bin/bash
export DISPLAY=:0
OSD_Message() {
	gnome-osd-client --full --dbus "<message id='bootmsg' osd_fake_translucent_bg='off' osd_vposition='center' hide_timeout='10000000' osd_halignment='center'>\$*</message>"
}

msgchk=/target/tmp/msgchk
newmsg=/target/tmp/messenger
touch \$newmsg

if [ ! -f \$msgchk ]; then 
	sudo touch -r \$msgchk 
fi

while true; do
	if [ \$newmsg -nt \$msgchk ]; then
		sleep 1
		OSD_Message "\$(cat \$newmsg)"
		sudo touch -r \$newmsg \$msgchk
	fi

	if [ "\$(cat \$newmsg)" == "Reboot" ]; then
		OSD_Message " "
		break
	fi
done
EOL

### The main post-installer
cat <<EOL > $WORKMASTER/postinst.sh
#!/bin/bash
. /usr/pluto/bin/dvd-installer.sh
echo "/bin/false" > /etc/X11/default-display-manager
export LC_ALL=C
log_file=/var/log/LinuxMCE_Setup.log
Messg_File=/tmp/messenger
echo "Running post-install. Do NOT reboot." > \$Messg_File
service mysql stop
sleep 2
mysqld --skip-networking&
sleep 1
#Execute Functions
echo "Setting up TTY options" > \$Messg_File
addAdditionalTTYStart
echo "Fixing EMI" > \$Messg_File
TempEMIFix
echo "Setting initial boot prep" > \$Messg_File
InitialBootPrep
rm /root/new-installer/spacemaker
echo "Removing ubiquity and casper options" > \$Messg_File
apt-get -y remove --purge --force-yes ubiquity ubiquity-casper ubiquity-ubuntu-artwork ubiquity-frontend-kde casper
echo "Configuring DCERouter" > \$Messg_File
Setup_Pluto_Conf
Create_And_Config_Devices
echo "Updating initramfs" > \$Messg_File
update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth /lib/plymouth/themes/LinuxMCE/LinuxMCE.plymouth 900
update-initramfs -u
echo "Unmounting and shutting down MySQL" > \$Messg_File
umount -lf /dev/pts
umount -lf /sys
umount -lf /proc
service mysql stop
killall -9 mysqld_safe
kill \`lsof |grep mysqld|cut -d" " -f3|sort -u\` ||:
umount -lf /dev
echo "Please wait while your Core reboots" > \$Messg_File
sleep 3
echo "Reboot" > \$Messg_File
#rm /target/tmp/messenger
EOL

#####################################
# Prepping chroot image
#####################################
# TODO this step will probably not be necessary on your end, but make sure you have enough room on your base image to get/extract/install
# Should probably be the first package you install if you wish to preserve a smaller disk size.
echo "Installing video-wizard-videos if necessary"
	
	if [ ! -d $DDDIR/home/videowiz ]; then
		cp video-wizard-videos_1.1_all.deb $DDDIR/usr/pluto
		chroot $DDDIR dpkg -i /usr/pluto/video-wizard-videos_1.1_all.deb
		rm $DDDIR/usr/pluto/video-wizard-videos_1.1_all.deb
	fi
	
echo "Downloading tools to the CHROOT needed for mastering."
mkdir -p $DDDIR/etc/udev/rules.d
	if [ ! -e $DDDIR/sbin/losetup ]; then
		echo > $DDDIR/sbin/losetup
	fi
	if [ ! -e $DDDIR/sbin/udevtrigger ]; then
		echo > $DDDIR/sbin/udevtrigger;
	fi  

####################################
# Configure DCERouter
####################################
cat <<EOL > $DDDIR/root/new-installer/prepmaster.sh
#!/bin/bash
. /usr/pluto/bin/dvd-installer.sh
mysqld --skip-networking&
sleep 5
gpgUpdate
StatusMessage "Pre-installing needed packages"
Pre-InstallNeededPackages
CreatePackagesFiles
PreSeed_Prefs
Fix_Initrd_Vmlinux

ReCreatePackagesFiles
StatusMessage "Cleaning up install"
#CleanInstallSteps
apt-get remove -yq popularity-contest
apt-get remove -y festival
apt-get remove -y *java*
EOL

chmod +x $DDDIR/root/new-installer/prepmaster.sh
LC_ALL=C chroot $DDDIR /root/new-installer/prepmaster.sh
kill $(lsof $DDDIR|grep mysqld|cut -d" " -f3|sort -u) || :
sleep 5

#####################################
# Prepping the dvd file system
#####################################

### This moves things around and creates the file system to be squashed.
echo "Time to move. This may take a while. Go code something..."
	
	# Wipe and prevent the installer from changing the apt sources.list
	if [ ! -f "$DDDIR/usr/share/ubiquity/apt-setup.saved" ]; then
		cp $DDDIR/usr/share/ubiquity/apt-setup $DDDIR/usr/share/ubiquity/apt-setup.saved
	fi

# move images for ubiquity background
cp $DDDIR/lib/plymouth/themes/LinuxMCE/LinuxMCE-logo.png $DDDIR/usr/share/kde4/apps/kdm/themes/ethais/wallpapers/background-1920x1200.png
cp $DDDIR/lib/plymouth/themes/LinuxMCE/LinuxMCE-logo.png $DDDIR/usr/share/kde4/apps/kdm/themes/ethais/wallpapers/background.png

# Creates the CD tree in the work directory
mkdir -p $WORKDIR/{home,dev,etc,proc,tmp,sys,var}
mkdir -p $WORKDIR/mnt/dev
mkdir -p $WORKDIR/media/cdrom
chmod ug+rwx,o+rwt $WORKDIR/tmp
	
# Copying /var and /etc to temp area and excluding extra files
	if [ "$EXCLUDES" != "" ]; then
		for addvar in $EXCLUDES ; do
			VAREXCLUDES="$VAREXCLUDES --exclude='$addvar' "
		done
	fi
	
# We have no users, but still make sure skel is owned by root
LC_ALL=C chroot $DDDIR chown root /etc/skel

# This moves everthing but what is excluded
rsync --exclude='*.log' --exclude='*.log.*' --exclude='*.pid' --exclude='*.bak'  $VAREXCLUDES-a $DDDIR/var/. $WORKDIR/var/.
#--exclude='*.[0-9].gz' --exclude='*.deb' 
rsync $VAREXCLUDES-a $DDDIR/etc/. $WORKDIR/etc/.
	
# This removes everything we want to make fresh
rm -rf $WORKDIR/etc/X11/xorg.conf*
rm -rf $WORKDIR/etc/timezone
rm -rf $WORKDIR/etc/mtab
rm -rf $WORKDIR/etc/fstab
rm -rf $WORKDIR/etc/udev/rules.d/70-persistent*
rm -rf $WORKDIR/etc/cups/ssl/server.*
rm -rf $WORKDIR/etc/ssh/ssh_host*
rm -rf $WORKDIR/etc/gdm/custom.conf
#ls $WORKDIR/var/lib/apt/lists | grep -v ".gpg" | grep -v "lock" | grep -v "partial" | xargs -i rm $WORKDIR/var/lib/apt/lists/{} ;
echo > $WORKDIR/etc/gdm/gdm.conf-custom
rm -rf $WORKDIR/etc/group
rm -rf $WORKDIR/etc/passwd
rm -rf $WORKDIR/etc/*hadow*
rm -rf $WORKDIR/etc/wicd/wir*.conf
rm -rf $WORKDIR/etc/printcap
touch $WORKDIR/etc/printcap

cp $DDDIR/etc/network/interfaces.temp $WORKDIR/etc/network	
# We use copy here to move home directory including hidden files.
cp -r $DDDIR/home/* $WORKDIR/home
cp -rn $DDDIR/root/* $WORKDIR/root
cp -rn $DDDIR/root/.??* $WORKDIR/root
cp $DDDIR/etc/dhcp3/*.conf $WORKDIR/root/new-installer/
# This removes what we don't want in there.
find $WORKDIR/var/run $WORKDIR/var/log $WORKDIR/var/mail $WORKDIR/var/spool $WORKDIR/var/lock $WORKDIR/var/backups $WORKDIR/var/tmp $WORKDIR/var/crash -type f -exec rm {} \;


# Makes sure we have relevant logs available in var
	for i in dpkg.log lastlog mail.log syslog auth.log daemon.log faillog lpr.log mail.warn user.log boot debug mail.err messages wtmp bootstrap.log dmesg kern.log mail.info
		do touch $WORKDIR/var/log/${i}
	done
	
# See if any temp users left over
grep '^[^:]*:[^:]*:[5-9][0-9][0-9]:' $DDDIR/etc/passwd | awk -F ":" '{print "/usr/sbin/userdel -f",$1}'> $WORKDIR/cleantmpusers
. $WORKDIR/cleantmpusers
grep '^[^:]*:[^:]*:[0-9]:' $DDDIR/etc/passwd >> $WORKDIR/etc/passwd
grep '^[^:]*:[^:]*:[0-9][0-9]:' $DDDIR/etc/passwd >> $WORKDIR/etc/passwd
grep '^[^:]*:[^:]*:[0-9][0-9][0-9]:' $DDDIR/etc/passwd >> $WORKDIR/etc/passwd
grep '^[^:]*:[^:]*:[3-9][0-9][0-9][0-9][0-9]:' $DDDIR/etc/passwd >> $WORKDIR/etc/passwd
grep '^[^:]*:[^:]*:[0-9]:' $DDDIR/etc/group >> $WORKDIR/etc/group
grep '^[^:]*:[^:]*:[0-9][0-9]:' $DDDIR/etc/group >> $WORKDIR/etc/group
grep '^[^:]*:[^:]*:[0-9][0-9][0-9]:' $DDDIR/etc/group >> $WORKDIR/etc/group
grep '^[^:]*:[^:]*:[3-9][0-9][0-9][0-9][0-9]:' $DDDIR/etc/group >> $WORKDIR/etc/group
grep '^[^:]*:[^:]*:[5-9][0-9][0-9]:' $DDDIR/etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers1
grep '^[^:]*:[^:]*:[1-9][0-9][0-9][0-9]:' $DDDIR/etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers2
grep '^[^:]*:[^:]*:[1-2][0-9][0-9][0-9][0-9]:' $DDDIR/etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers3

cat $WORKDIR/tmpusers1 $WORKDIR/tmpusers2 $WORKDIR/tmpusers3 > $WORKDIR/tmpusers
	cat $WORKDIR/tmpusers | while read LINE ; do
		echo $LINE | xargs -i sed -e 's/,{}//g' $WORKDIR/etc/group > $WORKDIR/etc/group.new1
		echo $LINE | xargs -i sed -e 's/{},//g' $WORKDIR/etc/group.new1 > $WORKDIR/etc/group.new2
		echo $LINE | xargs -i sed -e 's/{}//g' $WORKDIR/etc/group.new2 > $WORKDIR/etc/group
		rm -rf $WORKDIR/etc/group.new1 $WORKDIR/etc/group.new2
	done
	 
# Make sure the adduser and autologin functions of casper as set according to the mode
[ ! -d $WORKDIR/home ] && mkdir $WORKDIR/home && chmod 755 $DDDIR/usr/share/initramfs-tools/scripts/casper-bottom/*adduser $DDDIR/usr/share/initramfs-tools/scripts/casper-bottom/*autologin
	
# BOOT Type is isolinux
cp $DDDIR/boot/memtest86+.bin $ISODIR/isolinux/memtest
	
# Check and see if they have a custom isolinux already setup.
find $DDDIR/usr -name 'isolinux.bin' -exec cp {} $ISODIR/isolinux/ \;
find $DDDIR/usr -name 'vesamenu.c32' -exec cp {} $ISODIR/isolinux/ \;
	
# Setup isolinux for the livecd
	if [ -e $DDMASTER/splash.png ]; then 
		cp $DDMASTER/splash.png $ISODIR/isolinux
	fi
	if [ -e splash.png ]; then
		cp splash.png $ISODIR/isolinux
	fi
	
	# We need a defines file and copy it to the casper dir
cat <<EOL > $ISODIR/README.diskdefines
#define DISKNAME  $LIVECDLABEL
#define TYPE  binary
#define TYPEbinary  1
#define ARCH  $ARCH
#define ARCH$ARCH  1
#define DISKNUM  1
#define DISKNUM1  1
#define TOTALNUM  0
#define TOTALNUM0  1
EOL

cp $ISODIR/README.diskdefines $ISODIR/casper/README.diskdefines
	
# Make the filesystem.manifest and filesystem.manifest-desktop
echo "Creating filesystem.manifest and filesystem.manifest-desktop"
dpkg-query -W --showformat='${Package} ${Version}\n' > $ISODIR/casper/filesystem.manifest
cp $ISODIR/casper/filesystem.manifest $ISODIR/casper/filesystem.manifest-desktop
cp $DDDIR/etc/casper.conf $WORKDIR/etc/
# Copy the install icon to the live install users desktop
udtop=$(find $DDDIR/usr -name 'ubiquity*.desktop')
cp $udtop $DDDIR/etc/skel/Desktop

echo "Setting up casper and ubiquity options."
rm -f $DDDIR/usr/share/ubiquity/apt-setup
echo "#do nothing" > $DDDIR/usr/share/ubiquity/apt-setup
chmod 755 $DDDIR/usr/share/ubiquity/apt-setup

#####################################
# Rebuild initram and squash
#####################################
# make a new initial ramdisk including the casper scripts and LinuxMCE plymouth theme
KERN=$(ls $DDDIR/lib/modules --sort time|head -1)
LC_ALL=C chroot $DDDIR update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth /lib/plymouth/themes/LinuxMCE/LinuxMCE.plymouth 900
LC_ALL=C chroot $DDDIR mkinitramfs -o /boot/initrd.img-$KERN $KERN
LC_ALL=C chroot $DDDIR update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth /lib/plymouth/themes/LinuxMCE/LinuxMCE.plymouth 900
LC_ALL=C chroot $DDDIR update-initramfs -u
	
echo "Copying your kernel and initrd for the livecd"
cp $DDDIR/boot/vmlinuz-$KERN $ISODIR/casper/vmlinuz
cp $DDDIR/boot/initrd.img-$KERN $ISODIR/casper/initrd.gz


###############################################
# This moves and rewrites some startup scripts
###############################################
echo "Adjusting startup scripts"

if  -f $WORKDIR/etc/init.d/0start_avwizard ; then
	mv $WORKDIR/etc/init.d/0start_avwizard $WORKMASTER/runners
	cat <<EOL > $WORKDIR/etc/init.d/0start_avwizard
#!/bin/bash
### BEGIN INIT INFO 
# Provides:		avwizard
# Required-Start:	check_avwizard
# Required-Stop:	 
# Should-Start:	
# Default-Start:	 2 
# Default-Stop:	1 
# Short-Description: AVWizard
# Description:	 This script starts the AV Wizard
### END INIT INFO #
rm /dev/nbd*
/usr/pluto/bin/dvd-installer.sh
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/0start_avwizard
fi

if  -f $WORKDIR/etc/init.d/apache2 ; then
	mv $WORKDIR/etc/init.d/apache2 $WORKMASTER/runners
	cat <<EOL > $WORKDIR/etc/init.d/apache2
#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          apache2
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     true
# Short-Description: Start/stop apache2 web server
### END INIT INFO
#
# apache2               This init.d script is used to start apache2.
#                       It basically just calls apache2ctl.
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/apache2
fi

if  -f $WORKDIR/etc/init.d/apparmor ; then
	mv $WORKDIR/etc/init.d/apparmor $WORKMASTER/runners
	cat <<EOL > $WORKDIR/etc/init.d/apparmor
#!/bin/sh
# ----------------------------------------------------------------------
#    Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
#     NOVELL (All rights reserved)
#    Copyright (c) 2008, 2009 Canonical, Ltd.
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of version 2 of the GNU General Public
#    License published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, contact Novell, Inc.
# ----------------------------------------------------------------------
# Authors:
#  Steve Beattie <steve.beattie@canonical.com>
#  Kees Cook <kees@ubuntu.com>
#
# /etc/init.d/apparmor
#
### BEGIN INIT INFO
# Provides: apparmor
# Required-Start: mountall
# Required-Stop: umountfs
# Default-Start: S
# Default-Stop:
# Short-Description: AppArmor initialization
# Description: AppArmor init script. This script loads all AppArmor profiles.
### END INIT INFO
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/apparmor
fi

if  -f $WORKDIR/etc/init.d/asterisk ; then
mv $WORKDIR/etc/init.d/asterisk $WORKMASTER/runners
cat <<EOL > $WORKDIR/etc/init.d/asterisk
#!/bin/sh
#
# asterisk      start the asterisk PBX
# (c) Mark Purcell <msp@debian.org>
# (c) Tzafrir Cohen <tzafrir.cohen@xorcom.com>
# (c) Faidon Liambotis <paravoid@debian.org>
#
#   This package is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
### BEGIN INIT INFO
# Provides:          asterisk
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $syslog $network $named mysql postgresql dahdi
# Should-Stop:       $syslog $network $named mysql postgresql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Asterisk PBX
# Description:       Controls the Asterisk PBX
### END INIT INFO
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/asterisk
fi

if  -f $WORKDIR/etc/init.d/bind9 ; then
	mv $WORKDIR/etc/init.d/bind9 $WORKMASTER/runners
	cat <<EOL > $WORKDIR/etc/init.d/bind9
### BEGIN INIT INFO
# Provides:          bind9
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $network $syslog
# Should-Stop:       $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop bind9
# Description:       bind9 is a Domain Name Server (DNS)
#        which translates ip addresses to and from internet names
### END INIT INFO
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/bind9
fi

if  -f $WORKDIR/etc/init.d/linuxmce ; then
	mv $WORKDIR/etc/init.d/linuxmce $WORKMASTER/runners
	cat <<EOL > $WORKDIR/etc/init.d/linuxmce
#!/bin/bash
### BEGIN INIT INFO 
# Provides:		linuxmce
# Required-Start:	$remote_fs $syslog 
# Required-Stop:	 $remote_fs $syslog 
# Should-Start:	$named 
# Default-Start:	 2 
# Default-Stop:	1 
# Short-Description: LinuxMCE 
# Description:	 This script is the entry point to start the LinuxMCE core
#			  It starts a couple of needed services and daemons, loads X (if running with AutoStartMedia)
#			  and executes LMCE_Launch_Manager to start devices and taking care of the rest.
### END INIT INFO #
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/linuxmce
fi

if  -f $WORKDIR/etc/init.d/mediatomb ; then
	mv $WORKDIR/etc/init.d/mediatomb $WORKMASTER/runners
	cat <<EOL > $WORKDIR/etc/init.d/mediatomb
#! /bin/sh
#
# MediaTomb initscript
#
# Original Author: Tor Krill <tor@excito.com>.
# Modified by:     Leonhard Wimmer <leo@mediatomb.cc>
# Modified again by Andres Mejia <mcitadel@gmail.com> to
# base it off of /etc/init.d/skeleton
#
#

### BEGIN INIT INFO
# Provides:          mediatomb
# Required-Start:    $local_fs $network $remote_fs
# Required-Stop:     $local_fs $network $remote_fs
# Should-Start:      $all
# Should-Stop:       $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: upnp media server
### END INIT INFO
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/mediatomb
fi

	if  -f $WORKDIR/etc/init.d/nis ; then
mv $WORKDIR/etc/init.d/nis $WORKMASTER/runners
cat <<EOL > $WORKDIR/etc/init.d/nis
#!/bin/sh
#
# /etc/init.d/nis	 Start NIS (formerly YP) daemons.
#
### BEGIN INIT INFO
# Provides:		 ypbind ypserv ypxfrd yppasswdd
# Required-Start:	 $network $portmap
# Required-Stop:	  $portmap
# Default-Start:	  2 3 4 5
# Default-Stop:		1
# Short-Description:	Start NIS client and server daemons.
# Description:		Start NIS client and server daemons.  NIS is mostly
#				 used to let several machines in a network share the
#				 same account information (eg the password file).
### END INIT INFO
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/nis
fi

if  -f $WORKDIR/etc/init.d/smbd ; then
	mv $WORKDIR/etc/init.d/smbd $WORKMASTER/runners
	cat <<EOL > $WORKDIR/etc/init.d/smbd
#!/bin/sh -e
# upstart-job
#
# Symlink target for initscripts that have been converted to Upstart.
exit 0
EOL
	chmod +x $WORKDIR/etc/init.d/smbd
fi



# Make executables
chmod +x $ISODIR/install/postseed.sh
chmod +x $ISODIR/install/messages.sh
chmod +x $WORKMASTER/postinst.sh

# Make sure skel has root files/hidden files and create 400mb file to be deleted on reboot so aufs has enough room for larger downloads. 
cp -rn $DDDIR/root/* $WORKDIR/etc/skel
cp -rn $DDDIR/root/.??* $WORKDIR/etc/skel
dd if=/dev/zero of=$WORKMASTER/spacemaker count=4 bs=100MB

# Make filesystem.squashfs
	if [ -f lmcemaster.log ]; then
		rm -f lmcemaster.log
		touch lmcemaster.log
	fi
	
	if [ -f $ISODIR/casper/filesystem.squashfs ]; then
		rm -f $ISODIR/casper/filesystem.squashfs
	fi

echo "Time to squash"
SQUASHFSOPTSHIGH="-no-recovery -always-use-fragments"
echo "Adding stage 1 files/folders that the livecd requires."
	
# Add the blank folders and trimmed down /var to the cd filesystem
mksquashfs $WORKDIR $ISODIR/casper/filesystem.squashfs -b 1M -no-duplicates $SQUASHFSOPTSHIGH 2>>lmcemaster.log
echo "Adding stage 2 files/folders that the livecd requires."
mksquashfs $DDDIR $ISODIR/casper/filesystem.squashfs -b 1M -no-duplicates $SQUASHFSOPTSHIGH -e .thumbnails .cache .bash_history Cache boot/grub dev etc home media mnt proc sys tmp var $WORKDIR $EXCLUDES 2>>lmcemaster.log
# Checking the size of the compressed filesystem to ensure it meets the iso9660 spec for a single file
SQUASHFSSIZE=`ls -s $ISODIR/casper/filesystem.squashfs | awk -F " " '{print $1}'`
	if [ "$SQUASHFSSIZE" -gt "3999999" ]; then
		echo "The compressed filesystem is larger than the iso9660 specification allows for a single file. You must try to reduce the amount of data you are backing up and try again."
		echo " Too big for DVD">>lmcemaster.log
		exit 1
	fi
	
# Add filesystem size for lucid
echo "Calculating the installed filesystem size for the installer"
unsquashfs -lls $ISODIR/casper/filesystem.squashfs | grep -v " inodes " | grep -v "unsquashfs:" | awk '{print $3}' | grep -v "," > $DDDIR/tmp/size.tmp
	for i in `cat $DDDIR/tmp/size.tmp`; do 
		a=$(($a+$i))
	done
echo $a > $ISODIR/casper/filesystem.size


###########################################
# Let's make us an iso
###########################################
# TODO this probably is unnecessary, but I don't know what fluffys guts look like.
CREATEISO="`which mkisofs`"
	if [ "$CREATEISO" = "" ]; then
		CREATEISO="`which genisoimage`"
	fi
	
# Check to see if the cd filesystem exists
	if [ ! -f "$ISODIR/casper/filesystem.squashfs" ]; then
		echo "The cd filesystem is missing."
		exit 1
	fi
	
# Checking the size of the compressed filesystem to ensure it meets the iso9660 spec for a single file
SQUASHFSSIZE=`ls -s $ISODIR/casper/filesystem.squashfs | awk -F " " '{print $1}'`
	if [ "$SQUASHFSSIZE" -gt "3999999" ]; then
		echo " The compressed filesystem is larger than the iso9660 specification allows for a single file. You must try to reduce the amount of data you are backing up and try again."
		echo " Too big for DVD.">>lmcemaster.log
		exit 1
	fi
	
# Make ISO compatible with Ubuntu Startup Disk Creator for those who would like to use it for usb boots
echo "Making disk compatible with Ubuntu Startup Disk Creator."
touch $ISODIR/ubuntu
touch $ISODIR/.disk/base_installable
echo "full_cd/single" > $ISODIR/.disk/cd_type
echo $LIVECDLABEL - Release i386 > $ISODIR/.disk/info
echo $LIVECDURL > $ISODIR/.disk/release_notes_url

# Make md5sum.txt for the files on the livecd - this is used during the checking function of the livecd
echo "Creating md5sum.txt for the livecd/dvd"
cd $ISODIR && find . -type f -print0 | xargs -0 md5sum > md5sum.txt

# Remove files that change and cause problems with checking the disk
sed -e '/isolinux/d' md5sum.txt > md5sum.txt.new
sed -e '/md5sum/d' md5sum.txt.new > md5sum.txt
rm -f md5sum.txt.new
	
# Make the ISO file
echo "Creating $CUSTOMISO"
$CREATEISO -r -V "$LIVECDLABEL" -cache-inodes -J -l -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -o ../$CUSTOMISO "./" 2>>../lmcemaster.log 1>>../lmcemaster.log
	
# Create the md5 sum file
echo "Creating $CUSTOMISO.md5"
cd ../
md5sum $CUSTOMISO > $CUSTOMISO.md5
echo " "
	if [ ! -e $CUSTOMISO ]; then
		echo "Something has gone horribly wrong. Iso does not exist. Exiting."
	else
		echo "Success!!! `ls -hs $CUSTOMISO` is ready to be burned or tested in a virtual machine."
		cp $CUSTOMISO /var/www/rsync/snapshots
		cp $CUSTOMISO.md5 /var/www/rsync/snapshots	
	fi

# Cleans and unmounts without displaying an error message as the trap should.
cleanFinish () {
	if [ -e $DDDIR/usr/sbin/invoke-rc.d.orig ]; then
		mv $DDDIR/usr/sbin/invoke-rc.d.orig $DDDIR/usr/sbin/invoke-rc.d.orig
	fi
mounted=$(mount | grep 1004-dd | grep none | awk '{print $3}')
	for mounts in $mounted; do 
		umount -lf $mounts
	done
	umount -lf `mount | grep 1004-dd | grep loop | awk '{print $3}'`
	rm -r $DDDIR
	rm -r $WORKDIR
	rm -r $ISODIR
	exit 0
}

echo "Unmounting and exiting cleanly."
# This will give a clean unmount and not trigger the trap, so the trap can show errors.
# cleanFinish 
exit 0

dvd-installer.sh

#!/bin/bash
. /usr/pluto/bin/Utils.sh
###########################################################
### Setup global variables
###########################################################
DISTRO="$(lsb_release -c -s)"
COMPOS="beta2"
DT_MEDIA_DIRECTOR=3
LOCAL_REPO_BASE=/usr/pluto/deb-cache
LOCAL_REPO_DIR=./
DT_CORE=1
DT_HYBRID=2
mce_wizard_data_shell=/tmp/mce_wizard_data.sh
Messg_File=/tmp/messenger
#Setup Pathing
export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

VerifyExitCode () {
	local EXITCODE=$?
	if [ "$EXITCODE" != "0" ] ; then
		echo "An error (Exit code $EXITCODE) occured during the last action"
		echo "$1"
		exit 1
	fi
}

###########################################################
### Setup Functions - Reference functions
###########################################################

Create_Wizard_Data-Double_Nic_Shell () {
echo "c_deviceType=2 # 1-Core, 2-Hybrid, 3-DiskedMD
c_netIfaceNo=1
c_netExtName='{extif}'
c_netExtIP=
c_netExtMask=
c_netExtGateway=
c_netExtDNS1=
c_netExtDNS2=
c_netExtUseDhcp=1 # 1 - Yes / 0 - No
c_runDhcpServer=1 # 1 - Yes / 0 - No
c_netIntName='{intif}'
c_netIntIPN='192.168.80'
c_startupType=1 #0 - Start Kde / 1 - Start LMCE
c_installType=1
c_installMirror='http://archive.ubuntu.com/ubuntu/'
c_netExtKeep='true'
c_installUI=0 # 0 - UI1, 1 - UI2M, 2 - UI2A
c_linuxmceCdFrom=1 # 1 - CD, 2 -ISO
c_linuxmceCdIsoPath= 
c_ubuntuExtraCdFrom=1
c_ubuntuExtraCdPath=
c_ubuntuLiveCdFrom=1
c_ubuntuLiveCdPath=
"
}

Create_Wizard_Data-Single_Nic_Shell () {
echo "c_deviceType=2 # 1-Core, 2-Hybrid, 3-DiskedMD
c_netIfaceNo=1
c_netExtName='{extif}'
c_netExtIP='{extip}'
c_netExtMask='{extMask}'
c_netExtGateway='{extGW}'
c_netExtDNS1='{extDNS}'
c_netExtDNS2=
c_netExtUseDhcp={extUseDhcp} # 1 - Yes / 0 - No
c_runDhcpServer={runDhcp} # 1 - Yes / 0 - No
c_netIntName='{extif}:1'
c_netIntIPN='192.168.80'
c_startupType=1 #0 - Start Kde / 1 - Start LMCE
c_installType=1
c_installMirror='http://archive.ubuntu.com/ubuntu/'
c_netExtKeep='true'
c_installUI=0 # 0 - UI1, 1 - UI2M, 2 - UI2A
c_linuxmceCdFrom=1 # 1 - CD, 2 -ISO
c_linuxmceCdIsoPath= 
c_ubuntuExtraCdFrom=1
c_ubuntuExtraCdPath=
c_ubuntuLiveCdFrom=1
c_ubuntuLiveCdPath=
c_singleNIC=1
"
}

###########################################################
### Setup Functions - General functions
###########################################################

Pre-InstallNeededPackages () {
	echo "Installing necessary prep packages" 

	#Create local deb-cache dir
	mkdir -p "${LOCAL_REPO_BASE}/${LOCAL_REPO_DIR}"

	#Install dpkg-dev and debconf-utils for pre-seed information
	#Install makedev due to mdadm issue later in the install process - logged bug https://bugs.launchpad.net/ubuntu/+source/mdadm/+bug/850213 with 	ubuntu
	apt-get -y -q install dpkg-dev debconf-utils makedev
	VerifyExitCode "dpkg-dev and debconf-utils"

	# Disable compcache
	if [ -f /usr/share/initramfs-tools/conf.d/compcache ]; then
		rm -f /usr/share/initramfs-tools/conf.d/compcache && update-initramfs -u
	fi
}

gpgUpdate () {
# This does an update, while adding gpg keys for any that are missing. This is primarily for medibuntu
# but will work for any source.
	if ping -c 1 google.com; then
		sed -i 's/#deb/deb/g' /etc/apt/sources.list
		gpgs=$(apt-get update |& grep -s NO_PUBKEY | awk '{ print $NF }' | cut -c 9-16); 
		if [ -n $gpgs ]; then for gpg in $gpgs 
			do gpg --keyserver pgp.mit.edu --recv-keys $gpg
			gpg --export --armor $gpg | apt-key add -
			done 
			apt-get update
		fi
	fi
}

CreatePackagesFiles () {
	echo "Creating necessary package files" 
	( cd "${LOCAL_REPO_BASE}"; \
	dpkg-scanpackages -m "${LOCAL_REPO_DIR}" /dev/null | \
	tee "${LOCAL_REPO_DIR}/Packages" | \
	gzip -9c >"${LOCAL_REPO_DIR}/Packages.gz" )
}
PreSeed_Prefs () {
echo "PreSeeding package installation preferences" 

#create preseed file
echo "debconf debconf/frontend	select Noninteractive
# Choices: critical, high, medium, low
debconf debconf/priority        select critical
msttcorefonts   msttcorefonts/http_proxy        string
msttcorefonts   msttcorefonts/defoma    note
msttcorefonts   msttcorefonts/dlurl     string
msttcorefonts   msttcorefonts/savedir   string
msttcorefonts   msttcorefonts/baddldir  note
msttcorefonts   msttcorefonts/dldir     string
msttcorefonts   msttcorefonts/blurb     note
msttcorefonts   msttcorefonts/accepted-mscorefonts-eula boolean true
msttcorefonts   msttcorefonts/present-mscorefonts-eula  boolean false
sun-java6-bin   shared/accepted-sun-dlj-v1-1    boolean true
sun-java6-jre   shared/accepted-sun-dlj-v1-1    boolean true
sun-java6-jre   sun-java6-jre/jcepolicy note
sun-java6-jre   sun-java6-jre/stopthread        boolean true
man-db		man-db/install-setuid		boolean	false
debconf debconf/frontend        select  Noninteractive
# Choices: critical, high, medium, low
debconf debconf/priority        select  critical
" > /tmp/preseed.cfg

debconf-set-selections /tmp/preseed.cfg
VerifyExitCode "debconf-set-selections - preseed data"

#For some odd reason, set-selections adds a space for Noninteractive and Critical that needs to be removed - debconf doesn't handle extra white space well
sed -i 's/Value:  /Value: /g' /var/cache/debconf/config.dat

#remove preseed file, no need to clutter things up
rm /tmp/preseed.cfg

#Seeding mythweb preferences to not override the LMCE site on install - for some odd reason, mythweb packages don't accept the set-selections
touch /etc/default/mythweb
echo "[cfg]" >> /etc/default/mythweb
echo "enable = false" >> /etc/default/mythweb
echo "only = false" >> /etc/default/mythweb
echo "username = " >> /etc/default/mythweb
echo "password = " >> /etc/default/mythweb 
}

Fix_Initrd_Vmlinux () {
	echo "Starting initrd and vmlinuz fix" 
	# Fix a problem with the /initrd.img and /vmlinuz links pointing to a different kernel than the 
	# newest (and currently running) one
	LATEST_KERNEL=`ls /lib/modules --sort time --group-directories-first|head -1`
	KERNEL_TO_USE=`uname -r`
	
	if [ -f "/boot/initrd.img-$LATEST_KERNEL" ]; then
		KERNEL_TO_USE=$LATEST_KERNEL
	fi
	ln -s -f /boot/initrd.img-$KERNEL_TO_USE /initrd.img
	ln -s -f /boot/vmlinuz-$KERNEL_TO_USE /vmlinuz
}

Nic_Config () {
	echo "Starting NIC Discovery and Configuration" 
	# Find out, what nic configuration we have. This is needed for later on to fill the database
	# correctly.
	if   awk '$1 != "Iface" && $1 != "lo" && $1 != "pan0" { print $1 }' | wc -l` > 1 ; then
		Create_Wizard_Data-Double_Nic_Shell > ${mce_wizard_data_shell}
		#Use these for the defaults if we cannot automatically determine which to use
		#TODO: Error out and instruct the user to setup a working connection? Or ask them to manually choose?
		extif="eth0"
		intif="eth1"
		if route -n | grep -q '^0.0.0.0'; then
			#We have a default route, use it for finding external interface.
			extif=`route -n | awk '$1 == "0.0.0.0" { print $8 }'`
			#Use the first available interface as the internal interface.
			for if in `ifconfig -s -a | awk '$1 != "Iface" && $1 != "lo"  && $1 != "pan0" { print $1 }'`; do
				if [ "$if" != "$extif" ]
				then
					intif=$if
				break
				fi
			done
		fi
		echo "Using $extif for external interface"
		sleep 2
		echo "Using $intif for internal interface"
	
		sed --in-place -e "s,\({extif}\),$extif,g" ${mce_wizard_data_shell}
		sed --in-place -e "s,\({intif}\),$intif,g" ${mce_wizard_data_shell}
	else
		extif=eth0
		if route -n | grep -q '^0.0.0.0'
				then
					#We have a default route, use it for finding external interface.
					extif=`route -n | awk '$1 == "0.0.0.0" { print $8 }'`
		fi
		Create_Wizard_Data-Single_Nic_Shell > ${mce_wizard_data_shell}
		echo "Using $extif for single nic install"
		sed --in-place -e "s,\({extif}\),$extif,g" ${mce_wizard_data_shell}
	
				# set c_netExtIP and friends , as this is used in Configure_Network_Options (i.e. before Network_Setup...)
				extIP=$(ip addr | grep "$extif" | grep -m 1 'inet ' | awk '{print $2}' | cut -d/ -f1)
				sed --in-place -e "s,\({extip}\),$extIP,g" ${mce_wizard_data_shell}
	
				# Set use external DHCP and run own dhcp based on extifs current setting
				ExtUsesDhcp=$(grep "iface $extif " /etc/network/interfaces | grep -cF 'dhcp')
		if  $ExtUsesDhcp == 0 
				then
			   # Not dhcp defined in config file, test if dhclient got us an IP
			   # /var/run/dhcp3 for newer than 810, /var/run in 810
			   if [[ (`ls /var/lib/dhcp3/dhclient-*-$extif.lease &&  $? == 0 ` || -e /var/run/dhclient-$extif.pid) && `pgrep -c dhclient` == 1 ]]
			   then
				   ExtUsesDhcp=1
			   fi
		fi
		RunDHCP=0
		if  $ExtUsesDhcp == 0 
			then
				echo "$extif does not use DHCP, setting ExtUseDhcp=0 and RunDHCPServer=1 and detecting current network settings"
				RunDHCP=1
				ExtGateway=$(grep -A 10 "^iface $extif" /etc/network/interfaces | grep '^\s*gateway' -m 1 | grep -o  '[0-9.]*')
				ExtMask=$(grep -A 10 "^iface $extif" /etc/network/interfaces | grep '^\s*netmask' -m 1 | grep -o '[0-9.]*')
				ExtDNS=$(grep 'nameserver' /etc/resolv.conf | grep -o '[0-9.]*' -m 1)
		fi
		sed --in-place -e "s,\({extMask}\),$ExtMask,g" ${mce_wizard_data_shell}
		sed --in-place -e "s,\({extGW}\),$ExtGateway,g" ${mce_wizard_data_shell}
		sed --in-place -e "s,\({extDNS}\),$ExtDNS,g" ${mce_wizard_data_shell}
		sed --in-place -e "s,\({extUseDhcp}\),$ExtUsesDhcp,g" ${mce_wizard_data_shell}
		sed --in-place -e "s,\({runDhcp}\),$RunDHCP,g" ${mce_wizard_data_shell}
	fi

	if [[ ! -r ${mce_wizard_data_shell} ]]; then
		echo "`date` - Wizard Information is corrupted or missing."
		exit 1
	fi
. ${mce_wizard_data_shell}
	VerifyExitCode "MCE Wizard Data"
	Core_PK_Device="0"
	#Setup the network interfaces
	echo > /etc/network/interfaces
	echo "auto lo" >> /etc/network/interfaces
	echo "iface lo inet loopback" >> /etc/network/interfaces
	echo >> /etc/network/interfaces
	echo "auto $c_netExtName" >> /etc/network/interfaces
	if  $c_netExtUseDhcp  == "1"  ;then
		echo "    iface $c_netExtName inet dhcp" >> /etc/network/interfaces
	else
		if  "$c_netExtIP" != ""  &&  "$c_netExtName" != ""  &&
		    "$c_netExtMask" != ""  &&  "$c_netExtGateway" != ""  ;then
			echo "" >> /etc/network/interfaces
			echo "    iface $c_netExtName inet static" >> /etc/network/interfaces
			echo "    address $c_netExtIP" >> /etc/network/interfaces
			echo "    netmask $c_netExtMask" >> /etc/network/interfaces
			echo "    gateway $c_netExtGateway" >> /etc/network/interfaces
		fi
	fi
	echo "" >> /etc/network/interfaces
	echo "auto $c_netIntName" >> /etc/network/interfaces
	echo "    iface $c_netIntName inet static" >> /etc/network/interfaces
	echo "    address $c_netIntIPN" >> /etc/network/interfaces
	echo "    netmask 255.255.255.0" >> /etc/network/interfaces
}

Setup_Pluto_Conf () {
	echo "Seting Up MCE Configuration file"
	AutostartCore=1
	if  "$coreOnly" == "1" ; then
		AutostartMedia="0"
	else	AutostartMedia="1"
	fi
		case "$DISTRO" in
			"intrepid")
			# select UI1
				PK_DISTRO="17"
			;;
			"lucid")
			# select UI2 without alpha blending
				PK_DISTRO="18"
			;;
		esac

cat <<EOL > /etc/pluto.conf
# Pluto config file
MySqlHost = localhost
MySqlUser = root
MySqlPassword =
MySqlDBName = pluto_main
DCERouter = localhost
MySqlPort = 3306
DCERouterPort = 3450
PK_Device = 1
Activation_Code = 1111
PK_Installation = 1
PK_Users = 1
PK_Distro = $PK_DISTRO
Display = 0
SharedDesktop = 1
OfflineMode = false
#<-mkr_b_videowizard_b->
UseVideoWizard = 1
#<-mkr_b_videowizard_e->
LogLevels = 1,5,7,8
#ImmediatelyFlushLog = 1
AutostartCore=$AutostartCore
AutostartMedia=$AutostartMedia
EOL
	chmod 777 /etc/pluto.conf &>/dev/null
}

Setup_NIS () {
# Put a temporary nis config file that will prevent ypbind to start
# Temporary NIS setup, disabling NIS server and client.
echo "Temporarily modifying the NIS configuration file disabling the NIS server and client"
echo "
NISSERVER=false
NISCLIENT=false
YPPWDDIR=/etc
YPCHANGEOK=chsh
NISMASTER=
YPSERVARGS=
YPBINDARGS=
YPPASSWDDARGS=
YPXFRDARGS=
" > /etc/default/nis
}

Create_And_Config_Devices () {

	# Create the initial core device using CreateDevice, and the MD for the core in case we create a Hybrid (the default).
	# Cycle the mysql server
	#service mysql stop
	#killall -9 mysqld_safe
	#service mysql start &

	#sleep to ensure the mysql server is fully started
	#sleep 5
	#Source the SQL_OPS file
	#. /usr/pluto/bin/SQL_Ops.sh
	DEVICE_TEMPLATE_Core=7
	DEVICE_TEMPLATE_MediaDirector=28
	## Update some info in the database
	Q="INSERT INTO Installation(Description, ActivationCode) VALUES('Pluto', '1111')"
	RunSQL "$Q"

	## Create the Core device and set it's description
	echo "Setting up your computer to act as a 'Core'"
	apt-get install lmce-asterisk -y
	Core_PK_Device=$(/usr/pluto/bin/CreateDevice -d $DEVICE_TEMPLATE_Core | tee /dev/stderr | tail -1)
	Q="UPDATE Device SET Description='CORE' WHERE PK_Device='$Core_PK_Device'"
	RunSQL "$Q"

	if  "$coreOnly" != "1" ; then
		#Setup media director with core
		echo "Setting up your computer to act as a 'Media Director'"
		/usr/pluto/bin/CreateDevice -d $DEVICE_TEMPLATE_MediaDirector -C "$Core_PK_Device"
		Hybrid_DT=$(RunSQL "SELECT PK_Device FROM Device WHERE FK_DeviceTemplate='$DEVICE_TEMPLATE_MediaDirector' LIMIT 1")
		Q="UPDATE Device SET Description='The core/hybrid' WHERE PK_Device='$Hybrid_DT'"
		RunSQL "$Q"

		## Set UI interface
		Q="SELECT PK_Device FROM Device WHERE FK_Device_ControlledVia='$Hybrid_DT' AND FK_DeviceTemplate=62"
		OrbiterDevice=$(RunSQL "$Q")
		echo "Updating Startup Scripts"
	fi
	# "DCERouter postinstall"
	/usr/pluto/bin/Update_StartupScrips.sh
}

Configure_Network_Options () {
	# Updating hosts file and the Device_Data for the core with the internal and external network
	# addresses - uses Initial_DHCP_Config.sh from the pluto-install-scripts package.
	echo "Configuring your internal network"
	#Source the SQL Ops file
	## Setup /etc/hosts
	cat <<EOL > /etc/hosts
127.0.0.1 localhost.localdomain localhost
$c_netExtIP dcerouter $(/bin/hostname)
EOL
	error=false
	Network=""
	Digits_Count=0
		for Digits in $(echo "$c_netIntIPN" | tr '.' ' ') ;do
		[[ "$Digits" == *[^0-9]* ]]	    && error=true
		| $Digits -gt 255  && error=true
			if  "$Network" == ""  ;then
				Network="$Digits"
			else
				Network="${Network}.${Digits}"
			fi

		Digits_Count=$(( $Digits_Count + 1 ))
		done
	| $Digits_Count -gt 3  && error=true
		if  "$error" == "true"  ;then
			Network="192.168.80"
			Digits_Count="3"
		fi

	IntIP="$Network"
	IntNetmask=""
		for i in `seq 1 $Digits_Count` ;do
			if  "$IntNetmask" == ""  ;then
				IntNetmask="255"
			else
				IntNetmask="${IntNetmask}.255"
			fi
		done
		for i in `seq $Digits_Count 3` ;do
			if  $i == "3"  ;then
				IntIP="${IntIP}.1"
			else
				IntIP="${IntIP}.0"
			fi
			IntNetmask="${IntNetmask}.0"
		done

		if  "$c_netIntName" == ""  ;then
			IntIf="$c_netExtName:0"
		else
			IntIf="$c_netIntName"
		fi

		if  "$c_singleNIC" == "1"  ;then
			#Disable firewalls on single NIC operation, refs #396
			echo "We are in single NIC mode -> internal firewalls disabled"
			echo "DisableFirewall=1" >>/etc/pluto.conf
			echo "DisableIPv6Firewall=1" >>/etc/pluto.conf
		fi

		if  "$c_netExtUseDhcp" == "0"  ;then
			NETsetting="$c_netExtName,$c_netExtIP,$c_netExtMask,$c_netExtGateway,$c_netExtDNS1|$IntIf,$IntIP,$IntNetmask"
		else
			NETsetting="$c_netExtName,dhcp|$IntIf,$IntIP,$IntNetmask"
		fi

	DHCPsetting=$(/usr/pluto/install/Initial_DHCP_Config.sh "$Network" "$Digits_Count")
	Q="REPLACE INTO Device_DeviceData(FK_Device,FK_DeviceData,IK_DeviceData) VALUES('$Core_PK_Device',32,'$NETsetting')"
	RunSQL "$Q"
		if  "$c_runDhcpServer" == "1" ; then
			Q="REPLACE INTO Device_DeviceData(FK_Device, FK_DeviceData, IK_DeviceData)
			VALUES($Core_PK_Device, 28, '$DHCPsetting')"
			RunSQL "$Q"
		fi
	# create empty IPv6 tunnel settings field
	Q="REPLACE INTO Device_DeviceData(FK_Device,FK_DeviceData,IK_DeviceData) VALUES('$Core_PK_Device',292,)"
	RunSQL "$Q"
}

addAdditionalTTYStart () {
	if  "$DISTRO" = "lucid"  ; then
		sed -i 's/23/235/' /etc/init/tty2.conf
		sed -i 's/23/235/' /etc/init/tty3.conf
		sed -i 's/23/235/' /etc/init/tty4.conf
		# disable plymouth splash for now. Could be replaced by own LMCE splash later
		#sed -i 's/ splash//' /etc/default/grub
		#Setup vmalloc for video drivers
		sed -i 's/GRUB_CMDLINE_LINUX=\"\"/GRUB_CMDLINE_LINUX=\"vmalloc=256m\"/' /etc/default/grub
		/usr/sbin/update-grub
	else
		echo "start on runlevel 5">>/etc/event.d/tty2
		echo "start on runlevel 5">>/etc/event.d/tty3
		echo "start on runlevel 5">>/etc/event.d/tty4
	fi
}

TempEMIFix () {
	#Until the new id-my-disc package is implemented, this will allow the external_media_identifier to launch
	ln -s /usr/lib/libdvdread.so.4 /usr/lib/libdvdread.so.3
}

ReCreatePackagesFiles () {
	echo "Creating necessary package files"
	pushd /usr/pluto/deb-cache
	dpkg-scanpackages -m . /dev/null | tee Packages | gzip -c > Packages.gz
	popd
}

SetupNetworking () {
	rm -f /etc/X11/xorg.conf
	rm -f /etc/network/interfaces
	
	## Reconfigure networking
	/usr/pluto/bin/Network_Setup.sh
	/usr/pluto/bin/DHCP_config.sh
	/usr/pluto/bin/Network_Firewall.sh
	/etc/init.d/networking restart
	/usr/pluto/bin/ConfirmInstallation.sh
	/usr/pluto/bin/Timezone_Detect.sh
}

CleanInstallSteps () {
	if  -f /etc/pluto/install_cleandb ; then
		# on upgrade, the old keys are already in place, so keep them
		rm -f /etc/ssh/ssh_host_*
		dpkg-reconfigure -pcritical openssh-server
		PostInstPkg=(
		pluto-local-database pluto-media-database pluto-security-database pluto-system-database
		pluto-telecom-database lmce-asterisk
		)

	for Pkg in "${PostInstPkg[@]}"; do
		/var/lib/dpkg/info/"$Pkg".postinst configure
	done

	# Mark remote assistance as diabled
		ConfDel remote
		arch=$(apt-config dump | grep 'APT::Architecture' | sed 's/APT::Architecture.*"\(.*\)".*/\1/g')
		Queries=(
		"UPDATE Device_DeviceData
			SET IK_DeviceData=15
			WHERE PK_Device IN (
				SELECT PK_Device FROM Device WHERE FK_DeviceTemplate IN (7, 28)
				)
				AND FK_DeviceData=7
		"
		"UPDATE Device_DeviceData SET IK_DeviceData='LMCE_CORE_u0804_$arch' WHERE IK_DeviceData='LMCE_CORE_1_1'"
		"UPDATE Device_DeviceData SET IK_DeviceData='LMCE_MD_u0804_i386'   WHERE IK_DeviceData='LMCE_MD_1_1'"
		"UPDATE Device_DeviceData SET IK_DeviceData='0' WHERE FK_DeviceData='234'"
		"UPDATE Device_DeviceData SET IK_DeviceData='i386' WHERE FK_DeviceData='112' AND IK_DeviceData='686'"
		)

	for Q in "${Queries[@]}"; do
		RunSQL "$Q"
	done
	DT_DiskDrive=11
	DiskDrives=$(RunSQL "SELECT PK_Device FROM Device WHERE FK_DeviceTemplate='$DT_DiskDrive'")
	for DiskDrive in $DiskDrives ;do
		DiskDrive_DeviceID=$(Field 1 "$DiskDrive")
		for table in 'CommandGroup_Command' 'Device_Command' 'Device_CommandGroup' 'Device_DeviceData' 'Device_DeviceGroup' 'Device_Device_Related' 'Device_EntertainArea' 'Device_HouseMode' 'Device_Orbiter' 'Device_StartupScript' 'Device_Users' ;do
		RunSQL "DELETE FROM \\`$table\\` WHERE FK_DeviceID = '$DiskDrive_DeviceID' LIMIT 1"
		done
		RunSQL "DELETE FROM Device WHERE PK_Device = '$DiskDrive_DeviceID' LIMIT 1"
	done
fi
}

VideoDriverLive () {
	vga_pci=$(lspci -v | grep -i 'VGA')
	prop_driver="vesa"
	chip_man=$(echo "$vga_pci" | grep -Eo '(ATI|VIA|nVidia|Intel)')
	case $chip_man in
		nVidia)
			prop_driver="nvidia"  ;;

		ATI)
			prop_driver="fglrx"
			if echo $vga_pci | grep -Ei '(r5|r6|r7)'; then
				prop_driver="radeonhd"; fi
			if echo "$vga_pci" | grep -E '((9|X|ES)(1|2?)([0-9])(5|0)0|Xpress)'; then
				prop_driver="radeon"; fi ;;

		Intel)
			prop_driver="intel"
			if echo $vga_pci | grep "i740"; then
				prop_driver="i740"; fi
			if echo $vga_pci | grep "i128"; then
				prop_driver="i128"; fi ;;

		VIA)
			prop_driver="openchrome" ;
			if echo $vga_pci | grep -i "Savage"; then
				prop_driver="savage"; fi
			#if echo $vga_pci | grep -i "s3"; then
				#prop_driver="via"; fi 
			if echo $vga_pci | grep -i "virge"; then
				prop_driver="virge"; fi ;;
	esac

	### Install driver based on the type of video card used
	#Install nouveau driver to avoid reboot if nvidia

	case $prop_driver in
		nvidia)
			apt-get -yf install xserver-xorg-nouveau-video ;;
		radeon)	
			apt-get -yf install xserver-xorg-video-radeon ;;
		fglrx)
			apt-get -yf install fglrx ;;
		radeonhd)
			apt-get -yf install xserver-xorg-video-radeonhd ;;
		intel)
			apt-get -yf install xserver-xorg-video-intel ;;
		i128)
			apt-get -yf install xserver-xorg-video-i128 ;;
		i740)
			apt-get -yf install xserver-xorg-video-i740 ;;
		openchrome)
			apt-get -yf install xserver-xorg-video-openchrome ;;
		savage)
			apt-get -yf install xserver-xorg-video-savage ;;
		via)
			apt-get -yf install xserver-xorg-video-s3 ;;
		virge)
			apt-get -yf install xserver-xorg-video-s3virge ;;
	esac
	if  "$chip_man" == "Intel" ; then
		apt-get -yf install libva-driver-i965
	fi
	VideoDriver="$prop_driver"
}

InitialBootPrep () {
	#Setup Runlevel 3
	rm -rf /etc/rc3.d/*
	cp -a /etc/rc2.d/* /etc/rc3.d/
	ln -sf /etc/init.d/linuxmce /etc/rc5.d/S99linuxmce
	rm -f /etc/rc3.d/S99kdm /etc/rc3.d/S990start_avwizard

	#Setup Runlevel 4
	rm -rf /etc/rc4.d/*
	cp -a /etc/rc2.d/* /etc/rc4.d/
	ln -sf /etc/init.d/linuxmce /etc/rc5.d/S99linuxmce
	
	#Setup Runlevel 5
	rm -rf /etc/rc5.d/*
	cp -a /etc/rc2.d/* /etc/rc5.d/
	ln -sf /etc/init.d/linuxmce /etc/rc5.d/S99linuxmce
	
	#Create inittab config
	cat <<EOL > /etc/inittab
# WARNING: Do NOT set the default runlevel to 0 (shutdown) or 6 (reboot).
#id:2:initdefault: # KDE
#id:3:initdefault: # Core
#id:4:initdefault: # Core + KDE
id:5:initdefault: # Launch Manager
EOL

	# Remove KDM startup
	echo "/bin/false" > /etc/X11/default-display-manager
	# In general I don't think chattr is a great idea... but this will prevent it from EVER being overwritten again without chattr -i first.
	
chattr +i /etc/X11/default-display-manager
	cp /usr/pluto/bin/firstboot /etc/rc5.d/S90firstboot
	chmod 755 /etc/rc5.d/S90firstboot
	echo >> /etc/apt/sources.list
	/usr/share/update-notifier/notify-reboot-required
}

###########################################################
### If running the LIVE dvd boot
###########################################################

live_boot=$(ps aux | grep ubiquity | wc -l)
	if grep -q "Live session user" /etc/passwd &&  "$live_boot" -lt "2" ; then 
		echo "/bin/false" > /etc/X11/default-display-manager
		chattr +i /etc/X11/default-display-manager
		service kdm stop
		pkill X
		ConfSet AVWizardDone 1
		mv /root/new-installer/runners/* /etc/init.d
		rm /root/new-installer/spacemaker
		Nic_Config
		Setup_NIS
		Configure_Network_Options
		addAdditionalTTYStart
		TempEMIFix
		InitialBootPrep
		/etc/init.d/networking restart
		sleep 3
		ConfSet AVWizardDone 0
		ConfSet AVWizardOverride 1
		echo "Starting firstboot script" > $Messg_File
		ReCreatePackagesFiles
		SetupNetworking
		VideoDriverLive
		echo "Firstboot Script Complete" > $Messg_File
		sleep 2
		/usr/pluto/bin/AVWizard_Run.sh
		/etc/init.d/linuxmce
	fi

firstboot

#!/bin/bash
. /usr/pluto/bin/dvd-installer.sh
###########################################################
### Setup global variables
###########################################################
LogFile="/var/log/pluto/firstboot.log"
trap trapit EXIT
trapit () {
rm -f /etc/rc5.d/S90firstboot
sed -i 's/pchd/dhcp/g' /etc/network/interfaces
}

###########################################################
### Main execution area
###########################################################
#cp /etc/network/interfaces.temp /etc/network/interfaces
#rm /etc/network/interfaces.temp
#Setup logging
. /usr/pluto/bin/TeeMyOutput.sh --outfile "$LogFile" --stdboth --append -- "$@"

StatusMessage "Starting firstboot script"

#rm /root/new-installer/spacemaker
dpkg --configure -a
apt-get upgrade
mv /root/new-installer/runners/* /etc/init.d
Nic_Config
Setup_NIS
StatusMessage "Configuring Networking"
Configure_Network_Options
mv /var/cache/apt/archives/* /usr/pluto/deb-cache
mkdir /var/cache/apt/archives/partial
ReCreatePackagesFiles
SetupNetworking 
#StatusMessage "Configuring DCERouter"
#Create_And_Config_Devices
StatusMessage "Prepping Video"
CheckVideoDriver
CleanInstallSteps
cp /root/new-installer/*.conf /etc/dhcp3
#Lets own KDE so we can use it
chattr -i /etc/X11/default-display-manager
me=$(grep ':1000:1000:' /etc/passwd | cut -d':' -f1)
chown -R $me.$me /home/$me/.kde
StatusMessage "Changed ownership of KDE to '$me'"
NotifyMessage "Firstboot Script Complete! Rebooting"
StatusMessage "The next screen you see should be AVWizard"
sed -i 's/pchd/dhcp/g' /etc/network/interfaces
rm -f /etc/rc5.d/firstboot
sleep 3
reboot

image.sh

 #!/bin/bash
 #
 # Create an image which can be dd'ed onto
 # a harddisk, and, after adding a boot loader
 # using grub, be ready for consumption.
 #
 set -e 
 
 IMAGEFILE=`tempfile -p 1004`
 dd if=/dev/zero of=$IMAGEFILE count=4 bs=1GB
 mkfs.ext2 -F $IMAGEFILE
 TEMPDIR=`mktemp -d 1004-dir.XXXXXXXXXX`
 mount -o loop $IMAGEFILE $TEMPDIR
 debootstrap --arch=i386 --include=mysql-server,rsync lucid $TEMPDIR
 echo dcerouter > $TEMPDIR/etc/hostname
 LC_ALL=C chroot $TEMPDIR mkdir -p /var/run/network /lib/plymouth/themes
 cat <<EOF > $TEMPDIR/etc/apt/sources.list
 deb http://deb.linuxmce.org/ubuntu/ lucid  beta2 
 deb http://deb.linuxmce.org/ubuntu/ 20dev_ubuntu  main
 #deb http://packages.medibuntu.org/ lucid free non-free
 EOF
 
 cat <<EOF > $TEMPDIR/etc/apt/sources.list.d/ubuntu.org
 deb mirror://mirrors.ubuntu.com/mirrors.txt lucid main restricted universe multiverse
 deb mirror://mirrors.ubuntu.com/mirrors.txt lucid-updates main restricted universe multiverse
 deb mirror://mirrors.ubuntu.com/mirrors.txt lucid-security main restricted universe multiverse
 deb http://debian.slimdevices.com/ stable  main 
 EOF
 
 cat <<EOF >$TEMPDIR/etc/apt/sources.list.d/fluffy.list
 deb http://127.0.0.1/builder-lucid/ ./ 
 deb ftp://mirror.hetzner.de/ubuntu/packages lucid main restricted universe multiverse
 deb ftp://mirror.hetzner.de/ubuntu/packages lucid-updates main restricted universe multiverse
 deb ftp://mirror.hetzner.de/ubuntu/security lucid-security main restricted universe multiverse
 EOF
 
 #create preseed file
 cat <<EOF | LC_ALL=C chroot $TEMPDIR debconf-set-selections
 debconf debconf/frontend  select Noninteractive
 # Choices: critical, high, medium, low
 debconf debconf/priority        select critical
 msttcorefonts   msttcorefonts/http_proxy        string
 msttcorefonts   msttcorefonts/defoma    note
 msttcorefonts   msttcorefonts/dlurl     string
 msttcorefonts   msttcorefonts/savedir   string
 msttcorefonts   msttcorefonts/baddldir  note
 msttcorefonts   msttcorefonts/dldir     string
 msttcorefonts   msttcorefonts/blurb     note
 msttcorefonts   msttcorefonts/accepted-mscorefonts-eula boolean true
 msttcorefonts   msttcorefonts/present-mscorefonts-eula  boolean false
 sun-java6-bin   shared/accepted-sun-dlj-v1-1    boolean true
 sun-java6-jre   shared/accepted-sun-dlj-v1-1    boolean true
 sun-java6-jre   sun-java6-jre/jcepolicy note
 sun-java6-jre   sun-java6-jre/stopthread        boolean true
 man-db		man-db/install-setuid		boolean	false
 EOF
 
 mv $TEMPDIR/usr/sbin/invoke-rc.d $TEMPDIR/usr/sbin/invoke-rc.d.orig
 
 cat <<EOF > $TEMPDIR/usr/sbin/invoke-rc.d
 #!/bin/bash
 exit 0
 EOF
 chmod +x $TEMPDIR/usr/sbin/invoke-rc.d
 
 
 mount -o bind /dev $TEMPDIR/dev
 mount -t proc none $TEMPDIR/proc
 mount -t devpts none $TEMPDIR/dev/pts
 
 LC_ALL=C chroot $TEMPDIR apt-get update
 LC_ALL=C chroot $TEMPDIR apt-get dist-upgrade -y --allow-unauthenticated
 LC_ALL=C chroot $TEMPDIR apt-get install linux-image-generic libc-dev-bin linux-libc-dev libc6-dev linux-headers-generic manpages-dev screen -y
 LC_ALL=C chroot $TEMPDIR apt-get clean
 
 cat <<EOF > $TEMPDIR/usr/sbin/invoke-rc.d
 #!/bin/bash
 exit 0
 EOF
 chmod +x $TEMPDIR/usr/sbin/invoke-rc.d
 
 mv $TEMPDIR/usr/bin/screen $TEMPDIR/usr/bin/screen.orig
 
 cat <<EOF > $TEMPDIR/usr/bin/screen
 #!/bin/bash
 exit 0
 EOF
 chmod +x $TEMPDIR/usr/bin/screen
 mysqldPID=`LC_ALL=C chroot $TEMPDIR mysqld --skip-networking&`
 echo MySQL PID: $mysqldPID
 chmod 755 $TEMPDIR/var/lib/mysql
 
 LC_ALL=C chroot $TEMPDIR apt-get install lmce-hybrid -y --allow-unauthenticated
 LC_ALL=C chroot $TEMPDIR apt-get clean
 
 # Add the minimal KDE meta package, which will also install Xorg.
 LC_ALL=C chroot $TEMPDIR apt-get install kde-minimal -y --allow-unauthenticated
 LC_ALL=C chroot $TEMPDIR apt-get clean
 
 # 
 LC_ALL=C chroot $TEMPDIR apt-get install pluto-x-scripts pluto-orbiter -y --allow-unauthenticated
 LC_ALL=C chroot $TEMPDIR apt-get clean
 
 # Asterisk stuff
 LC_ALL=C chroot $TEMPDIR apt-get install lmce-asterisk -y --allow-unauthenticated
 LC_ALL=C chroot $TEMPDIR apt-get clean
 
 # Additional stuff wanted by l3top
 LC_ALL=C chroot $TEMPDIR apt-get install ubuntu-standard casper lupin-casper discover1 laptop-detect os-prober linux-generic grub2 plymouth-x11 ubiquity-frontend-kde initramfs-tools -y --allow-unauthenticated
 LC_ALL=C chroot $TEMPDIR apt-get clean
 
 rm $TEMPDIR/usr/sbin/invoke-rc.d
 mv $TEMPDIR/usr/sbin/invoke-rc.d.orig $TEMPDIR/usr/sbin/invoke-rc.d
 
 rm $TEMPDIR/usr/bin/screen
 mv $TEMPDIR/usr/bin/screen.orig $TEMPDIR/usr/bin/screen
 
 # We now have the problem, that Pluto/LinuxMCEs startup scripts get executed WITHOUT the
 # use of invoke-rc.d - instead, they use screen.
 # 
 
 umount $TEMPDIR/dev/pts
 umount $TEMPDIR/proc
 kill `lsof $TEMPDIR|grep mysqld|cut -d" " -f3|sort -u` || :
 sleep 3 
 # kill $mysqldPID || :
 umount $TEMPDIR/dev
 
 # Show the current usage
 du -h --max-depth=1 $TEMPDIR |& grep -v "du: cannot access"
 
 # Get rid of existing network assignments
 rm -f  $TEMPDIR/etc/udev/rules.d/70-persistent-net-rules
 # Remove fluffy and our providers Ubuntu mirror from the sources.list
 rm -f $TEMPDIR/etc/apt/sources.list.d/fluffy.list
 
 # and no longer use the local ubuntu mirror.
 cat $TEMPDIR/etc/apt/sources.list.d/ubuntu.org >> $TEMPDIR/etc/apt/sources.list
 # Make sure fluffy is not in the list of available repositories
 LC_ALL=C chroot $TEMPDIR apt-get update
 
 # Clean up debconf back to dialog
 echo debconf debconf/frontend select Dialog | LC_ALL=C chroot $TEMPDIR debconf-set-selections 
 
 # Let's unmount everything, and run fsck to make sure the image 
 # is nice and clean.
 
 umount $TEMPDIR
 fsck.ext2 $IMAGEFILE