Difference between revisions of "Live DVD"

From LinuxMCE
Jump to: navigation, search
(Generated Files)
(dvd-installer.sh)
Line 894: Line 894:
  
 
==dvd-installer.sh==
 
==dvd-installer.sh==
  #!/bin/bash
+
#!/bin/bash
  . /usr/pluto/bin/SQL_Ops.sh
+
. /usr/pluto/bin/Utils.sh
  . /usr/pluto/bin/Config_Ops.sh
+
###########################################################
  . /usr/pluto/bin/GeneralFunctions.sh
+
### Setup global variables
  ###########################################################
+
###########################################################
  ### Setup global variables
+
DISTRO="$(lsb_release -c -s)"
  ###########################################################
+
COMPOS="beta2"
  log_file=/var/log/LinuxMCE_Setup.log
+
DT_MEDIA_DIRECTOR=3
  DISTRO="$(lsb_release -c -s)"
+
LOCAL_REPO_BASE=/usr/pluto/deb-cache
  COMPOS="beta2"
+
LOCAL_REPO_DIR=./
  DT_MEDIA_DIRECTOR=3
+
DT_CORE=1
  LOCAL_REPO_BASE=/usr/pluto/deb-cache
+
DT_HYBRID=2
  LOCAL_REPO_DIR=./
+
mce_wizard_data_shell=/tmp/mce_wizard_data.sh
  DT_CORE=1
+
Messg_File=/tmp/messenger
  DT_HYBRID=2
+
#Setup Pathing
  mce_wizard_data_shell=/tmp/mce_wizard_data.sh
+
export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
  #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"
  ### Setup Functions - Error checking and logging
+
echo "$1"
  ###########################################################
+
exit 1
 
+
fi
  Setup_Logfile () {
+
}
  if [ ! -f ${log_file} ]; then
+
  touch ${log_file}
+
###########################################################
  if [ $? = 1 ]; then
+
### Setup Functions - Reference functions
  echo "`date` - Unable to write to ${log_file} - re-run script as root"
+
###########################################################
  exit 1
+
  fi
+
Create_Wizard_Data-Double_Nic_Shell () {
  else
+
echo "c_deviceType=2 # 1-Core, 2-Hybrid, 3-DiskedMD
  #zero out an existing file
+
c_netIfaceNo=1
  echo > ${log_file}
+
c_netExtName='{extif}'
  fi
+
c_netExtIP=''
  TeeMyOutput --outfile ${log_file} --stdboth --append -- "$@"
+
c_netExtMask=''
  VerifyExitCode "Log Setup"
+
c_netExtGateway=''
  echo "`date` - Logging initiatilized to ${log_file}"
+
c_netExtDNS1=''
  }
+
c_netExtDNS2=''
 
+
c_netExtUseDhcp=1 # 1 - Yes / 0 - No
  VerifyExitCode () {
+
c_runDhcpServer=1 # 1 - Yes / 0 - No
          local EXITCODE=$?
+
c_netIntName='{intif}'
          if [ "$EXITCODE" != "0" ] ; then
+
c_netIntIPN='192.168.80'
          echo "An error (Exit code $EXITCODE) occured during the last action"
+
c_startupType=1 #0 - Start Kde / 1 - Start LMCE
          echo "$1"
+
c_installType=1
                  exit 1
+
c_installMirror='http://archive.ubuntu.com/ubuntu/'
          fi
+
c_netExtKeep='true'
  }
+
c_installUI=0 # 0 - UI1, 1 - UI2M, 2 - UI2A
 
+
c_linuxmceCdFrom=1 # 1 - CD, 2 -ISO
  TeeMyOutput () {
+
c_linuxmceCdIsoPath=''  
 
+
c_ubuntuExtraCdFrom=1
  # Usage:
+
c_ubuntuExtraCdPath=''
  # source TeeMyOutput.sh --outfile <file> [--infile <file>] [--stdout|--stderr|--stdboth] [--append] [--exclude <egrep pattern>] -- "$@"
+
c_ubuntuLiveCdFrom=1
  #  --outfile <file>        the file to tee our output to
+
c_ubuntuLiveCdPath=''
  #  --infile <file>          the file to feed ourselves with on stdin
+
"
  #  --stdout                redirect stdout (default)
+
}
  #  --stderr                redirect stderr
+
  #  --stdboth                redirect both stdout and stderr
+
Create_Wizard_Data-Single_Nic_Shell () {
  #  --append                run tee in append mode
+
echo "c_deviceType=2 # 1-Core, 2-Hybrid, 3-DiskedMD
  #  --exclude <pattern>      strip matching lines from output; pattern is used with egrep
+
c_netIfaceNo=1
  #
+
c_netExtName='{extif}'
  # Environment:
+
c_netExtIP='{extip}'
  #  SHELLCMD="<shell command>" (ex: bash -x)
+
c_netExtMask='{extMask}'
 
+
c_netExtGateway='{extGW}'
  if [[ -n "$TeeMyOutput" ]]; then
+
c_netExtDNS1='{extDNS}'
          return 0
+
c_netExtDNS2=''
  fi
+
c_netExtUseDhcp={extUseDhcp} # 1 - Yes / 0 - No
  Me="TeeMyOutput"
+
c_runDhcpServer={runDhcp} # 1 - Yes / 0 - No
 
+
c_netIntName='{extif}:1'
  # parse parameters
+
c_netIntIPN='192.168.80'
  for ((i = 1; i <= "$#"; i++)); do
+
c_startupType=1 #0 - Start Kde / 1 - Start LMCE
          Parm="${!i}"
+
c_installType=1
          case "$Parm" in
+
c_installMirror='http://archive.ubuntu.com/ubuntu/'
                  --outfile) ((i++)); OutFile="${!i}" ;;
+
c_netExtKeep='true'
                  --infile) ((i++)); InFile="${!i}" ;;
+
c_installUI=0 # 0 - UI1, 1 - UI2M, 2 - UI2A
                  --stdout|--stderr|--stdboth) Mode="${!i#--std}" ;;
+
c_linuxmceCdFrom=1 # 1 - CD, 2 -ISO
                  --append) Append=yes ;;
+
c_linuxmceCdIsoPath=''  
                  --exclude) ((i++)); Exclude="${!i}" ;;
+
c_ubuntuExtraCdFrom=1
                  --) LastParm="$i"; break ;;
+
c_ubuntuExtraCdPath=''
                  *) echo "$Me: Unknown parameter '$Parm'"; exit 1
+
c_ubuntuLiveCdFrom=1
          esac
+
c_ubuntuLiveCdPath=''
  done
+
c_singleNIC=1
 
+
"
  if [[ -z "$OutFile" ]]; then
+
}
          echo "$Me: No outfile"
+
          exit 1
+
###########################################################
  fi
+
### Setup Functions - General functions
 
+
###########################################################
  if [[ -z "$LastParm" ]]; then
+
   
          LastParm="$#"
+
  Pre-InstallNeededPackages () {
  fi
+
echo "Installing necessary prep packages"  
 
+
  # original parameters
+
#Create local deb-cache dir
  for ((i = "$LastParm" + 1; i <= "$#"; i++)); do
+
mkdir -p "${LOCAL_REPO_BASE}/${LOCAL_REPO_DIR}"
          OrigParms=("${OrigParms[@]}" "${!i}")
+
  done
+
#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
  # construct command components
+
apt-get -y -q install dpkg-dev debconf-utils makedev
  case "$Mode" in
+
VerifyExitCode "dpkg-dev and debconf-utils"
          out) OurRedirect=() ;;
+
          err) OurRedirect=("2>&1" "1>/dev/null") ;;
+
# Disable compcache
          both) OurRedirect=("2>&1") ;;
+
if [ -f /usr/share/initramfs-tools/conf.d/compcache ]; then
  esac
+
rm -f /usr/share/initramfs-tools/conf.d/compcache && update-initramfs -u
 
+
fi
  if [[ "$Append" == yes ]]; then
+
}
          TeeParm=(-a)
+
  fi
+
gpgUpdate () {
 
+
# This does an update, while adding gpg keys for any that are missing. This is primarily for medibuntu
  if [[ -n "$InFile" ]]; then
+
# but will work for any source.
          OurRedirect=("${OurRedirect[@]}" "<$InFile")
+
if ping -c 1 google.com; then
  fi
+
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);
  # do our stuff
+
if [ -n $gpgs ]; then for gpg in $gpgs
  export TeeMyOutput=yes
+
do gpg --keyserver pgp.mit.edu --recv-keys $gpg
  ExitCodeFile="/tmp/TeeMyOutputExitCode_$$"
+
gpg --export --armor $gpg | apt-key add -
  trap "rm -rf '$ExitCodeFile'" EXIT
+
done
 
+
apt-get update
  Run()
+
fi
  {
+
fi
          eval exec "${OurRedirect[@]}"
+
}
          $SHELLCMD "$0" "${OrigParms[@]}"
+
          echo $? >"$ExitCodeFile"
+
CreatePackagesFiles () {
  }
+
echo "Creating necessary package files"  
 
+
( cd "${LOCAL_REPO_BASE}"; \
  if [[ -z "$Exclude" ]]; then
+
dpkg-scanpackages -m "${LOCAL_REPO_DIR}" /dev/null | \
          Run | tee "${TeeParm[@]}" "$OutFile"
+
tee "${LOCAL_REPO_DIR}/Packages" | \
  else
+
gzip -9c >"${LOCAL_REPO_DIR}/Packages.gz" )
          Run | grep --line-buffered -v "$Exclude" | tee "${TeeParm[@]}" "$OutFile"
+
}
  fi
+
PreSeed_Prefs () {
 
+
echo "PreSeeding package installation preferences"  
  ExitCode=$(<"$ExitCodeFile")
+
  exit "$ExitCode"
+
#create preseed file
  exit 1 # just in case
+
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
  ### Setup Functions - Reference functions
+
msttcorefonts  msttcorefonts/savedir  string
  ###########################################################
+
msttcorefonts  msttcorefonts/baddldir  note
 
+
msttcorefonts  msttcorefonts/dldir    string
  Create_Wizard_Data-Double_Nic_Shell () {
+
msttcorefonts  msttcorefonts/blurb    note
  echo "c_deviceType=2 # 1-Core, 2-Hybrid, 3-DiskedMD
+
msttcorefonts  msttcorefonts/accepted-mscorefonts-eula boolean true
  c_netIfaceNo=1
+
msttcorefonts  msttcorefonts/present-mscorefonts-eula  boolean false
  c_netExtName='{extif}'
+
sun-java6-bin  shared/accepted-sun-dlj-v1-1    boolean true
  c_netExtIP=''
+
sun-java6-jre  shared/accepted-sun-dlj-v1-1    boolean true
  c_netExtMask=''
+
sun-java6-jre  sun-java6-jre/jcepolicy note
  c_netExtGateway=''
+
sun-java6-jre  sun-java6-jre/stopthread        boolean true
  c_netExtDNS1=''
+
man-db man-db/install-setuid boolean false
  c_netExtDNS2=''
+
debconf debconf/frontend        select  Noninteractive
  c_netExtUseDhcp=1 # 1 - Yes / 0 - No
+
# Choices: critical, high, medium, low
  c_runDhcpServer=1 # 1 - Yes / 0 - No
+
debconf debconf/priority        select  critical
  c_netIntName='{intif}'
+
" > /tmp/preseed.cfg
  c_netIntIPN='192.168.80'
+
  c_startupType=1 #0 - Start Kde / 1 - Start LMCE
+
debconf-set-selections /tmp/preseed.cfg
  c_installType=1
+
VerifyExitCode "debconf-set-selections - preseed data"
  c_installMirror='http://archive.ubuntu.com/ubuntu/'
+
  c_netExtKeep='true'
+
#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
  c_installUI=0 # 0 - UI1, 1 - UI2M, 2 - UI2A
+
sed -i 's/Value:  /Value: /g' /var/cache/debconf/config.dat
  c_linuxmceCdFrom=1 # 1 - CD, 2 -ISO
+
  c_linuxmceCdIsoPath=''  
+
#remove preseed file, no need to clutter things up
  c_ubuntuExtraCdFrom=1
+
rm /tmp/preseed.cfg
  c_ubuntuExtraCdPath=''
+
  c_ubuntuLiveCdFrom=1
+
#Seeding mythweb preferences to not override the LMCE site on install - for some odd reason, mythweb packages don't accept the set-selections
  c_ubuntuLiveCdPath=''
+
touch /etc/default/mythweb
  "
+
echo "[cfg]" >> /etc/default/mythweb
  }
+
echo "enable = false" >> /etc/default/mythweb
 
+
echo "only = false" >> /etc/default/mythweb
  Create_Wizard_Data-Single_Nic_Shell () {
+
echo "username = " >> /etc/default/mythweb
  echo "c_deviceType=2 # 1-Core, 2-Hybrid, 3-DiskedMD
+
echo "password = " >> /etc/default/mythweb  
  c_netIfaceNo=1
+
}
  c_netExtName='{extif}'
+
  c_netExtIP='{extip}'
+
Fix_Initrd_Vmlinux () {
  c_netExtMask='{extMask}'
+
echo "Starting initrd and vmlinuz fix"  
  c_netExtGateway='{extGW}'
+
# Fix a problem with the /initrd.img and /vmlinuz links pointing to a different kernel than the  
  c_netExtDNS1='{extDNS}'
+
# newest (and currently running) one
  c_netExtDNS2=''
+
LATEST_KERNEL=`ls /lib/modules --sort time --group-directories-first|head -1`
  c_netExtUseDhcp={extUseDhcp} # 1 - Yes / 0 - No
+
KERNEL_TO_USE=`uname -r`
  c_runDhcpServer={runDhcp} # 1 - Yes / 0 - No
+
  c_netIntName='{extif}:1'
+
if [ -f "/boot/initrd.img-$LATEST_KERNEL" ]; then
  c_netIntIPN='192.168.80'
+
KERNEL_TO_USE=$LATEST_KERNEL
  c_startupType=1 #0 - Start Kde / 1 - Start LMCE
+
fi
  c_installType=1
+
ln -s -f /boot/initrd.img-$KERNEL_TO_USE /initrd.img
  c_installMirror='http://archive.ubuntu.com/ubuntu/'
+
ln -s -f /boot/vmlinuz-$KERNEL_TO_USE /vmlinuz
  c_netExtKeep='true'
+
}
  c_installUI=0 # 0 - UI1, 1 - UI2M, 2 - UI2A
+
  c_linuxmceCdFrom=1 # 1 - CD, 2 -ISO
+
Nic_Config () {
  c_linuxmceCdIsoPath=''  
+
echo "Starting NIC Discovery and Configuration"  
  c_ubuntuExtraCdFrom=1
+
# Find out, what nic configuration we have. This is needed for later on to fill the database
  c_ubuntuExtraCdPath=''
+
# correctly.
  c_ubuntuLiveCdFrom=1
+
if  [[ `ifconfig -s -a  | awk '$1 != "Iface" && $1 != "lo" && $1 != "pan0" { print $1 }' | wc -l` > 1 ]]; then
  c_ubuntuLiveCdPath=''
+
Create_Wizard_Data-Double_Nic_Shell > ${mce_wizard_data_shell}
  c_singleNIC=1
+
#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
  AddGpgKeyToKeyring () {
+
#We have a default route, use it for finding external interface.
  local gpg_key="$1"
+
extif=`route -n | awk '$1 == "0.0.0.0" { print $8 }'`
 
+
#Use the first available interface as the internal interface.
  wget -q "$gpg_key" -O- | apt-key add -
+
for if in `ifconfig -s -a | awk '$1 != "Iface" && $1 != "lo"  && $1 != "pan0" { print $1 }'`; do
  }
+
if [ "$if" != "$extif" ]
 
+
then
 
+
intif=$if
  ###########################################################
+
break
  ### Setup Functions - General functions
+
fi
  ###########################################################
+
done
 
+
fi
  UpdateUpgrade () {
+
echo "Using $extif for external interface"
  #perform an update and a dist-upgrade
+
sleep 2
  echo "Performing an update and an upgrade to all components" > /tmp/messenger
+
echo "Using $intif for internal interface"
  apt-get -qq update
+
  VerifyExitCode "apt-get update"
+
sed --in-place -e "s,\({extif}\),$extif,g" ${mce_wizard_data_shell}
  apt-get -y -q -f --force-yes upgrade
+
sed --in-place -e "s,\({intif}\),$intif,g" ${mce_wizard_data_shell}
  VerifyExitCode "dist-upgrade"
+
else
  }
+
extif=eth0
 
+
if route -n | grep -q '^0.0.0.0'
  TimeUpdate () {
+
then
  echo "Synchronizing time with an online server" > /tmp/messenger
+
#We have a default route, use it for finding external interface.
  #Update system time to match ntp server
+
extif=`route -n | awk '$1 == "0.0.0.0" { print $8 }'`
  ntpdate ntp.ubuntu.com
+
fi
  }
+
Create_Wizard_Data-Single_Nic_Shell > ${mce_wizard_data_shell}
 
+
echo "Using $extif for single nic install"
  CreateBackupSources () {
+
sed --in-place -e "s,\({extif}\),$extif,g" ${mce_wizard_data_shell}
  if [ ! -e /etc/apt/sources.list.pbackup ]; then
+
  echo "Backing up sources.list file"
+
# set c_netExtIP and friends , as this is used in Configure_Network_Options (i.e. before Network_Setup...)
  cp -a /etc/apt/sources.list /etc/apt/sources.list.pbackup
+
extIP=$(ip addr | grep "$extif" | grep -m 1 'inet ' | awk '{print $2}' | cut -d/ -f1)
  fi
+
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
  AddAptRetries () {
+
ExtUsesDhcp=$(grep "iface $extif " /etc/network/interfaces | grep -cF 'dhcp')
  local changed
+
if [[ $ExtUsesDhcp == 0 ]]
  if [ -f /etc/apt/apt.conf ]; then
+
then
  if ! grep -q "^[^#]*APT::Acquire { Retries" /etc/apt/apt.conf; then
+
  # Not dhcp defined in config file, test if dhclient got us an IP
  echo 'APT::Acquire { Retries "20" }'>>/etc/apt/apt.conf
+
  # /var/run/dhcp3 for newer than 810, /var/run in 810
  changed=0
+
  if [[ (`ls /var/lib/dhcp3/dhclient-*-$extif.lease && [[ $? == 0 ]]` || -e /var/run/dhclient-$extif.pid) && `pgrep -c dhclient` == 1 ]]
  else
+
  then
  echo "APT preference on number of retries already set "
+
  ExtUsesDhcp=1
  changed=1
+
  fi
  fi
+
fi
  else
+
RunDHCP=0
  echo 'APT::Acquire { Retries "20" }'>>/etc/apt/apt.conf
+
if [[ $ExtUsesDhcp == 0 ]]
  fi
+
then
  echo "APT preference on number of retries set"
+
echo "$extif does not use DHCP, setting ExtUseDhcp=0 and RunDHCPServer=1 and detecting current network settings"
  return $changed
+
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.]*')
  Pre-InstallNeededPackages () {
+
ExtDNS=$(grep 'nameserver' /etc/resolv.conf | grep -o '[0-9.]*' -m 1)
  echo "Installing necessary prep packages" > /tmp/messenger
+
fi
 
+
sed --in-place -e "s,\({extMask}\),$ExtMask,g" ${mce_wizard_data_shell}
  #Create local deb-cache dir
+
sed --in-place -e "s,\({extGW}\),$ExtGateway,g" ${mce_wizard_data_shell}
  mkdir -p "${LOCAL_REPO_BASE}/${LOCAL_REPO_DIR}"
+
sed --in-place -e "s,\({extDNS}\),$ExtDNS,g" ${mce_wizard_data_shell}
 
+
sed --in-place -e "s,\({extUseDhcp}\),$ExtUsesDhcp,g" ${mce_wizard_data_shell}
  #Install dpkg-dev and debconf-utils for pre-seed information
+
sed --in-place -e "s,\({runDhcp}\),$RunDHCP,g" ${mce_wizard_data_shell}
  #Install makedev due to mdadm issue later in the install process - logged bug https://bugs.launchpad.net/ubuntu/+source/mdadm/+bug/850213 with ubuntu
+
fi
  apt-get -y -q install dpkg-dev debconf-utils makedev
+
  VerifyExitCode "dpkg-dev and debconf-utils"
+
if [[ ! -r ${mce_wizard_data_shell} ]]; then
 
+
echo "`date` - Wizard Information is corrupted or missing."
 
+
exit 1
  # Disable compcache
+
fi
  if [ -f /usr/share/initramfs-tools/conf.d/compcache ]; then
+
. ${mce_wizard_data_shell}
  rm -f /usr/share/initramfs-tools/conf.d/compcache && update-initramfs -u
+
VerifyExitCode "MCE Wizard Data"
  fi
+
Core_PK_Device="0"
  }
+
#Setup the network interfaces
 
+
echo > /etc/network/interfaces
  CreatePackagesFiles () {
+
echo "auto lo" >> /etc/network/interfaces
  echo "Creating necessary package files" > /tmp/messenger
+
echo "iface lo inet loopback" >> /etc/network/interfaces
  ( cd "${LOCAL_REPO_BASE}"; \
+
echo >> /etc/network/interfaces
  dpkg-scanpackages -m "${LOCAL_REPO_DIR}" /dev/null | \
+
echo "auto $c_netExtName" >> /etc/network/interfaces
  tee "${LOCAL_REPO_DIR}/Packages" | \
+
if [[ $c_netExtUseDhcp  == "1" ]] ;then
  gzip -9c >"${LOCAL_REPO_DIR}/Packages.gz" )
+
echo "    iface $c_netExtName inet dhcp" >> /etc/network/interfaces
  }
+
else
  PreSeed_Prefs () {
+
if [[ "$c_netExtIP" != "" ]] && [[ "$c_netExtName" != "" ]] &&
  echo "PreSeeding package installation preferences" > /tmp/messenger
+
  [[ "$c_netExtMask" != "" ]] && [[ "$c_netExtGateway" != "" ]] ;then
 
+
echo "" >> /etc/network/interfaces
  #create preseed file
+
echo "    iface $c_netExtName inet static" >> /etc/network/interfaces
  echo "debconf debconf/frontend select Noninteractive
+
echo "    address $c_netExtIP" >> /etc/network/interfaces
  # Choices: critical, high, medium, low
+
echo "    netmask $c_netExtMask" >> /etc/network/interfaces
  debconf debconf/priority        select critical
+
echo "    gateway $c_netExtGateway" >> /etc/network/interfaces
  msttcorefonts  msttcorefonts/http_proxy        string
+
fi
  msttcorefonts  msttcorefonts/defoma    note
+
fi
  msttcorefonts  msttcorefonts/dlurl    string
+
echo "" >> /etc/network/interfaces
  msttcorefonts  msttcorefonts/savedir  string
+
echo "auto $c_netIntName" >> /etc/network/interfaces
  msttcorefonts  msttcorefonts/baddldir  note
+
echo "    iface $c_netIntName inet static" >> /etc/network/interfaces
  msttcorefonts  msttcorefonts/dldir    string
+
echo "    address $c_netIntIPN" >> /etc/network/interfaces
  msttcorefonts  msttcorefonts/blurb    note
+
echo "    netmask 255.255.255.0" >> /etc/network/interfaces
  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
+
Setup_Pluto_Conf () {
  sun-java6-jre  shared/accepted-sun-dlj-v1-1    boolean true
+
echo "Seting Up MCE Configuration file"
  sun-java6-jre  sun-java6-jre/jcepolicy note
+
AutostartCore=1
  sun-java6-jre  sun-java6-jre/stopthread        boolean true
+
if [[ "$coreOnly" == "1" ]]; then
  man-db man-db/install-setuid boolean false
+
AutostartMedia="0"
  debconf debconf/frontend        select  Noninteractive
+
else AutostartMedia="1"
  # Choices: critical, high, medium, low
+
fi
  debconf debconf/priority        select  critical
+
case "$DISTRO" in
  " > /tmp/preseed.cfg
+
"intrepid")
 
+
# select UI1
  debconf-set-selections /tmp/preseed.cfg
+
PK_DISTRO="17"
  VerifyExitCode "debconf-set-selections - preseed data"
+
;;
 
+
"lucid")
  #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
+
# select UI2 without alpha blending
  sed -i 's/Value:  /Value: /g' /var/cache/debconf/config.dat
+
PK_DISTRO="18"
 
+
;;
  #remove preseed file, no need to clutter things up
+
esac
  rm /tmp/preseed.cfg
+
 
+
cat <<EOL > /etc/pluto.conf
  #Seeding mythweb preferences to not override the LMCE site on install - for some odd reason, mythweb packages don't accept the set-selections
+
# Pluto config file
  touch /etc/default/mythweb
+
MySqlHost = localhost
  echo "[cfg]" >> /etc/default/mythweb
+
MySqlUser = root
  echo "enable = false" >> /etc/default/mythweb
+
MySqlPassword =
  echo "only = false" >> /etc/default/mythweb
+
MySqlDBName = pluto_main
  echo "username = " >> /etc/default/mythweb
+
DCERouter = localhost
  echo "password = " >> /etc/default/mythweb  
+
MySqlPort = 3306
  }
+
DCERouterPort = 3450
 
+
PK_Device = 1
  Fix_Initrd_Vmlinux () {
+
Activation_Code = 1111
  echo "Starting initrd and vmlinuz fix" > /tmp/messenger
+
PK_Installation = 1
  # Fix a problem with the /initrd.img and /vmlinuz links pointing to a different kernel than the  
+
PK_Users = 1
  # newest (and currently running) one
+
PK_Distro = $PK_DISTRO
  LATEST_KERNEL=`ls /lib/modules --sort time --group-directories-first|head -1`
+
Display = 0
  KERNEL_TO_USE=`uname -r`
+
SharedDesktop = 1
 
+
OfflineMode = false
  if [ -f "/boot/initrd.img-$LATEST_KERNEL" ]; then
+
#<-mkr_b_videowizard_b->
  KERNEL_TO_USE=$LATEST_KERNEL
+
UseVideoWizard = 1
  fi
+
#<-mkr_b_videowizard_e->
  ln -s -f /boot/initrd.img-$KERNEL_TO_USE /initrd.img
+
LogLevels = 1,5,7,8
  ln -s -f /boot/vmlinuz-$KERNEL_TO_USE /vmlinuz
+
#ImmediatelyFlushLog = 1
  }
+
AutostartCore=$AutostartCore
 
+
AutostartMedia=$AutostartMedia
  Nic_Config () {
+
EOL
  echo "Starting NIC Discovery and Configuration" > /tmp/messenger
+
chmod 777 /etc/pluto.conf &>/dev/null
  # Find out, what nic configuration we have. This is needed for later on to fill the database
+
}
  # correctly.
+
  if  [[ `ifconfig -s -a  | awk '$1 != "Iface" && $1 != "lo" && $1 != "pan0" { print $1 }' | wc -l` > 1 ]]; then
+
Setup_NIS () {
  Create_Wizard_Data-Double_Nic_Shell > ${mce_wizard_data_shell}
+
# Put a temporary nis config file that will prevent ypbind to start
  #Use these for the defaults if we cannot automatically determine which to use
+
# Temporary NIS setup, disabling NIS server and client.
  #TODO: Error out and instruct the user to setup a working connection? Or ask them to manually choose?
+
echo "Temporarily modifying the NIS configuration file disabling the NIS server and client"
  extif="eth0"
+
echo "
  intif="eth1"
+
NISSERVER=false
  if route -n | grep -q '^0.0.0.0'; then
+
NISCLIENT=false
  #We have a default route, use it for finding external interface.
+
YPPWDDIR=/etc
  extif=`route -n | awk '$1 == "0.0.0.0" { print $8 }'`
+
YPCHANGEOK=chsh
  #Use the first available interface as the internal interface.
+
NISMASTER=
  for if in `ifconfig -s -a | awk '$1 != "Iface" && $1 != "lo"  && $1 != "pan0" { print $1 }'`
+
YPSERVARGS=
  do
+
YPBINDARGS=
  if [ "$if" != "$extif" ]
+
YPPASSWDDARGS=
  then
+
YPXFRDARGS=
  intif=$if
+
" > /etc/default/nis
  break
+
}
  fi
+
  done
+
Create_And_Config_Devices () {
  fi
+
  echo "Using $extif for external interface" > /tmp/messenger
+
# Create the initial core device using CreateDevice, and the MD for the core in case we create a Hybrid (the default).
  echo "Using $intif for internal interface" > /tmp/messenger
+
# Cycle the mysql server
 
+
#service mysql stop
  sed --in-place -e "s,\({extif}\),$extif,g" ${mce_wizard_data_shell}
+
#killall -9 mysqld_safe
  sed --in-place -e "s,\({intif}\),$intif,g" ${mce_wizard_data_shell}
+
#service mysql start &
  else
+
  extif=eth0
+
#sleep to ensure the mysql server is fully started
  if route -n | grep -q '^0.0.0.0'
+
#sleep 5
  then
+
#Source the SQL_OPS file
  #We have a default route, use it for finding external interface.
+
#. /usr/pluto/bin/SQL_Ops.sh
  extif=`route -n | awk '$1 == "0.0.0.0" { print $8 }'`
+
DEVICE_TEMPLATE_Core=7
  fi
+
DEVICE_TEMPLATE_MediaDirector=28
  Create_Wizard_Data-Single_Nic_Shell > ${mce_wizard_data_shell}
+
## Update some info in the database
  echo "Using $extif for single nic install" > /tmp/messenger
+
Q="INSERT INTO Installation(Description, ActivationCode) VALUES('Pluto', '1111')"
  sed --in-place -e "s,\({extif}\),$extif,g" ${mce_wizard_data_shell}
+
RunSQL "$Q"
 
+
  # set c_netExtIP and friends , as this is used in Configure_Network_Options (i.e. before Network_Setup...)
+
## Create the Core device and set it's description
  extIP=$(ip addr | grep "$extif" | grep -m 1 'inet ' | awk '{print $2}' | cut -d/ -f1)
+
echo "Setting up your computer to act as a 'Core'"
  sed --in-place -e "s,\({extip}\),$extIP,g" ${mce_wizard_data_shell}
+
apt-get install lmce-asterisk -y
 
+
Core_PK_Device=$(/usr/pluto/bin/CreateDevice -d $DEVICE_TEMPLATE_Core | tee /dev/stderr | tail -1)
  # Set use external DHCP and run own dhcp based on extifs current setting
+
Q="UPDATE Device SET Description='CORE' WHERE PK_Device='$Core_PK_Device'"
  ExtUsesDhcp=$(grep "iface $extif " /etc/network/interfaces | grep -cF 'dhcp')
+
RunSQL "$Q"
  if [[ $ExtUsesDhcp == 0 ]]
+
  then
+
if [[ "$coreOnly" != "1" ]]; then
    # Not dhcp defined in config file, test if dhclient got us an IP
+
#Setup media director with core
    # /var/run/dhcp3 for newer than 810, /var/run in 810
+
echo "Setting up your computer to act as a 'Media Director'"
    if [[ (`ls /var/lib/dhcp3/dhclient-*-$extif.lease && [[ $? == 0 ]]` || -e /var/run/dhclient-$extif.pid) && `pgrep -c dhclient` == 1 ]]
+
/usr/pluto/bin/CreateDevice -d $DEVICE_TEMPLATE_MediaDirector -C "$Core_PK_Device"
    then
+
Hybrid_DT=$(RunSQL "SELECT PK_Device FROM Device WHERE FK_DeviceTemplate='$DEVICE_TEMPLATE_MediaDirector' LIMIT 1")
    ExtUsesDhcp=1
+
Q="UPDATE Device SET Description='The core/hybrid' WHERE PK_Device='$Hybrid_DT'"
    fi
+
RunSQL "$Q"
  fi
+
  RunDHCP=0
+
## Set UI interface
  if [[ $ExtUsesDhcp == 0 ]]
+
Q="SELECT PK_Device FROM Device WHERE FK_Device_ControlledVia='$Hybrid_DT' AND FK_DeviceTemplate=62"
  then
+
OrbiterDevice=$(RunSQL "$Q")
  echo "$extif does not use DHCP, setting ExtUseDhcp=0 and RunDHCPServer=1 and detecting current network settings" > /tmp/messenger
+
echo "Updating Startup Scripts"
  RunDHCP=1
+
fi
 
+
# "DCERouter postinstall"
  ExtGateway=$(grep -A 10 "^iface $extif" /etc/network/interfaces | grep '^\s*gateway' -m 1 | grep -o  '[0-9.]*')
+
/usr/pluto/bin/Update_StartupScrips.sh
  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
+
Configure_Network_Options () {
 
+
# Updating hosts file and the Device_Data for the core with the internal and external network
  sed --in-place -e "s,\({extMask}\),$ExtMask,g" ${mce_wizard_data_shell}
+
# addresses - uses Initial_DHCP_Config.sh from the pluto-install-scripts package.
  sed --in-place -e "s,\({extGW}\),$ExtGateway,g" ${mce_wizard_data_shell}
+
echo "Configuring your internal network"
  sed --in-place -e "s,\({extDNS}\),$ExtDNS,g" ${mce_wizard_data_shell}
+
#Source the SQL Ops file
 
+
## Setup /etc/hosts
  sed --in-place -e "s,\({extUseDhcp}\),$ExtUsesDhcp,g" ${mce_wizard_data_shell}
+
cat <<EOL > /etc/hosts
  sed --in-place -e "s,\({runDhcp}\),$RunDHCP,g" ${mce_wizard_data_shell}
+
127.0.0.1 localhost.localdomain localhost
  fi
+
$c_netExtIP dcerouter $(/bin/hostname)
 
+
EOL
  if [[ ! -r ${mce_wizard_data_shell} ]]; then
+
error=false
          echo "`date` - Wizard Information is corrupted or missing." > /tmp/messenger
+
Network=""
  exit 1
+
Digits_Count=0
  fi
+
for Digits in $(echo "$c_netIntIPN" | tr '.' ' ') ;do
  . ${mce_wizard_data_shell}
+
[[ "$Digits" == *[^0-9]* ]]     && error=true
  VerifyExitCode "MCE Wizard Data"
+
[[ $Digits -lt 0 || $Digits -gt 255 ]] && error=true
 
+
if [[ "$Network" == "" ]] ;then
  Core_PK_Device="0"
+
Network="$Digits"
 
+
else
  #Setup the network interfaces
+
Network="${Network}.${Digits}"
  echo > /etc/network/interfaces
+
fi
  echo "auto lo" >> /etc/network/interfaces
+
  echo "iface lo inet loopback" >> /etc/network/interfaces
+
Digits_Count=$(( $Digits_Count + 1 ))
  echo >> /etc/network/interfaces
+
done
  echo "auto $c_netExtName" >> /etc/network/interfaces
+
[[ $Digits_Count -lt 1 || $Digits_Count -gt 3 ]] && error=true
  if [[ $c_netExtUseDhcp  == "1" ]] ;then
+
if [[ "$error" == "true" ]] ;then
  echo "    iface $c_netExtName inet dhcp" >> /etc/network/interfaces
+
Network="192.168.80"
  else
+
Digits_Count="3"
  if [[ "$c_netExtIP" != "" ]] && [[ "$c_netExtName" != "" ]] &&
+
fi
    [[ "$c_netExtMask" != "" ]] && [[ "$c_netExtGateway" != "" ]] ;then
+
  echo "" >> /etc/network/interfaces
+
IntIP="$Network"
  echo "    iface $c_netExtName inet static" >> /etc/network/interfaces
+
IntNetmask=""
  echo "    address $c_netExtIP" >> /etc/network/interfaces
+
for i in `seq 1 $Digits_Count` ;do
  echo "    netmask $c_netExtMask" >> /etc/network/interfaces
+
if [[ "$IntNetmask" == "" ]] ;then
  echo "    gateway $c_netExtGateway" >> /etc/network/interfaces
+
IntNetmask="255"
  fi
+
else
  fi
+
IntNetmask="${IntNetmask}.255"
  echo "" >> /etc/network/interfaces
+
fi
  echo "auto $c_netIntName" >> /etc/network/interfaces
+
done
  echo "    iface $c_netIntName inet static" >> /etc/network/interfaces
+
for i in `seq $Digits_Count 3` ;do
  echo "    address $c_netIntIPN" >> /etc/network/interfaces
+
if [[ $i == "3" ]] ;then
  echo "    netmask 255.255.255.0" >> /etc/network/interfaces
+
IntIP="${IntIP}.1"
  }
+
else
 
+
IntIP="${IntIP}.0"
  Setup_Pluto_Conf () {
+
fi
  echo "Seting Up MCE Configuration file" > /tmp/messenger
+
IntNetmask="${IntNetmask}.0"
  AutostartCore=1
+
done
  AutostartMedia=1
+
 
+
if [[ "$c_netIntName" == "" ]] ;then
  case "$DISTRO" in
+
IntIf="$c_netExtName:0"
  "intrepid")
+
else
  # select UI1
+
IntIf="$c_netIntName"
  PK_DISTRO=17
+
fi
  ;;
+
  "lucid")
+
if [[ "$c_singleNIC" == "1" ]] ;then
  # select UI2 without alpha blending
+
#Disable firewalls on single NIC operation, refs #396
  PK_DISTRO=18
+
echo "We are in single NIC mode -> internal firewalls disabled"
  ;;
+
echo "DisableFirewall=1" >>/etc/pluto.conf
  esac
+
echo "DisableIPv6Firewall=1" >>/etc/pluto.conf
 
+
fi
 
+
  echo "Generating Default Config File" > /tmp/messenger
+
if [[ "$c_netExtUseDhcp" == "0" ]] ;then
  PlutoConf="# Pluto config file
+
NETsetting="$c_netExtName,$c_netExtIP,$c_netExtMask,$c_netExtGateway,$c_netExtDNS1|$IntIf,$IntIP,$IntNetmask"
  MySqlHost = localhost
+
else
  MySqlUser = root
+
NETsetting="$c_netExtName,dhcp|$IntIf,$IntIP,$IntNetmask"
  MySqlPassword =
+
fi
  MySqlDBName = pluto_main
+
  DCERouter = localhost
+
DHCPsetting=$(/usr/pluto/install/Initial_DHCP_Config.sh "$Network" "$Digits_Count")
  MySqlPort = 3306
+
Q="REPLACE INTO Device_DeviceData(FK_Device,FK_DeviceData,IK_DeviceData) VALUES('$Core_PK_Device',32,'$NETsetting')"
  DCERouterPort = 3450
+
RunSQL "$Q"
  PK_Device = 1
+
if [[ "$c_runDhcpServer" == "1" ]]; then
  Activation_Code = 1111
+
Q="REPLACE INTO Device_DeviceData(FK_Device, FK_DeviceData, IK_DeviceData)
  PK_Installation = 1
+
VALUES($Core_PK_Device, 28, '$DHCPsetting')"
  PK_Users = 1
+
RunSQL "$Q"
  PK_Distro = $PK_DISTRO
+
fi
  Display = 0
+
# create empty IPv6 tunnel settings field
  SharedDesktop = 1
+
Q="REPLACE INTO Device_DeviceData(FK_Device,FK_DeviceData,IK_DeviceData) VALUES('$Core_PK_Device',292,'')"
  OfflineMode = false
+
RunSQL "$Q"
  #<-mkr_b_videowizard_b->
+
}
  UseVideoWizard = 1
+
  #<-mkr_b_videowizard_e->
+
addAdditionalTTYStart () {
  LogLevels = 1,5,7,8
+
if [[ "$DISTRO" = "lucid" ]] ; then
  #ImmediatelyFlushLog = 1
+
sed -i 's/23/235/' /etc/init/tty2.conf
  AutostartCore=$AutostartCore
+
sed -i 's/23/235/' /etc/init/tty3.conf
  AutostartMedia=$AutostartMedia
+
sed -i 's/23/235/' /etc/init/tty4.conf
  "
+
# disable plymouth splash for now. Could be replaced by own LMCE splash later
  echo "$PlutoConf" > /etc/pluto.conf
+
#sed -i 's/ splash//' /etc/default/grub
 
+
#Setup vmalloc for video drivers
  chmod 777 /etc/pluto.conf &>/dev/null
+
sed -i 's/GRUB_CMDLINE_LINUX=\"\"/GRUB_CMDLINE_LINUX=\"vmalloc=256m\"/' /etc/default/grub
  }
+
/usr/sbin/update-grub
 
+
else
  Setup_NIS () {
+
echo "start on runlevel 5">>/etc/event.d/tty2
  # Put a temporary nis config file that will prevent ypbind to start
+
echo "start on runlevel 5">>/etc/event.d/tty3
  # Temporary NIS setup, disabling NIS server and client.
+
echo "start on runlevel 5">>/etc/event.d/tty4
  echo "Temporarily modifying the NIS configuration file disabling the NIS server and client"
+
fi
  echo "
+
}
  NISSERVER=false
+
  NISCLIENT=false
+
TempEMIFix () {
  YPPWDDIR=/etc
+
#Until the new id-my-disc package is implemented, this will allow the external_media_identifier to launch
  YPCHANGEOK=chsh
+
ln -s /usr/lib/libdvdread.so.4 /usr/lib/libdvdread.so.3
  NISMASTER=
+
}
  YPSERVARGS=
+
  YPBINDARGS=
+
ReCreatePackagesFiles () {
  YPPASSWDDARGS=
+
echo "Creating necessary package files"
  YPXFRDARGS=
+
pushd /usr/pluto/deb-cache
  " > /etc/default/nis
+
dpkg-scanpackages -m . /dev/null | tee Packages | gzip -c > Packages.gz
  }
+
popd
 
+
}
  Create_And_Config_Devices () {
+
 
+
SetupNetworking () {
  # Create the initial core device using CreateDevice, and the MD for the core in case we create a Hybrid (the default).
+
rm -f /etc/X11/xorg.conf
 
+
rm -f /etc/network/interfaces
  #Cycle the mysql server
+
  #service mysql stop
+
## Reconfigure networking
  #killall -9 mysqld_safe
+
/usr/pluto/bin/Network_Setup.sh
  #service mysql start &
+
/usr/pluto/bin/DHCP_config.sh
 
+
/usr/pluto/bin/Network_Firewall.sh
  #sleep to ensure the mysql server is fully started
+
/etc/init.d/networking restart
  sleep 5
+
/usr/pluto/bin/ConfirmInstallation.sh
 
+
/usr/pluto/bin/Timezone_Detect.sh
  #Source the SQL_OPS file
+
}
  #. /usr/pluto/bin/SQL_Ops.sh
+
 
+
CleanInstallSteps () {
  DEVICE_TEMPLATE_Core=7
+
if [[ -f /etc/pluto/install_cleandb ]]; then
  DEVICE_TEMPLATE_MediaDirector=28
+
# on upgrade, the old keys are already in place, so keep them
 
+
rm -f /etc/ssh/ssh_host_*
 
+
dpkg-reconfigure -pcritical openssh-server
  ## Update some info in the database
+
PostInstPkg=(
  Q="INSERT INTO Installation(Description, ActivationCode) VALUES('Pluto', '1111')"
+
pluto-local-database pluto-media-database pluto-security-database pluto-system-database
  RunSQL "$Q"
+
pluto-telecom-database lmce-asterisk
 
+
)
  ## Create the Core device and set it's description
+
  echo "Setting up your computer to act as a 'Core'" > /tmp/messenger
+
for Pkg in "${PostInstPkg[@]}"; do
  apt-get install lmce-asterisk -y
+
/var/lib/dpkg/info/"$Pkg".postinst configure
  Core_PK_Device=$(/usr/pluto/bin/CreateDevice -d $DEVICE_TEMPLATE_Core | tee /dev/stderr | tail -1)
+
done
  Q="UPDATE Device SET Description='CORE' WHERE PK_Device='$Core_PK_Device'"
+
  RunSQL "$Q"
+
# Mark remote assistance as diabled
 
+
ConfDel remote
  #Setup media director with core
+
arch=$(apt-config dump | grep 'APT::Architecture' | sed 's/APT::Architecture.*"\(.*\)".*/\1/g')
  echo "Setting up your computer to act as a 'Media Director'" > /tmp/messenger
+
Queries=(
  /usr/pluto/bin/CreateDevice -d $DEVICE_TEMPLATE_MediaDirector -C "$Core_PK_Device"
+
"UPDATE Device_DeviceData
  Hybrid_DT=$(RunSQL "SELECT PK_Device FROM Device WHERE FK_DeviceTemplate='$DEVICE_TEMPLATE_MediaDirector' LIMIT 1")
+
SET IK_DeviceData=15
  Q="UPDATE Device SET Description='The core/hybrid' WHERE PK_Device='$Hybrid_DT'"
+
WHERE PK_Device IN (
  RunSQL "$Q"
+
SELECT PK_Device FROM Device WHERE FK_DeviceTemplate IN (7, 28)
 
+
)
  ## Set UI interface
+
AND FK_DeviceData=7
  Q="SELECT PK_Device FROM Device WHERE FK_Device_ControlledVia='$Hybrid_DT' AND FK_DeviceTemplate=62"
+
"
  OrbiterDevice=$(RunSQL "$Q")
+
"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'"
  echo "Updating Startup Scripts" > /tmp/messenger
+
"UPDATE Device_DeviceData SET IK_DeviceData='i386' WHERE FK_DeviceData='112' AND IK_DeviceData='686'"
  # "DCERouter postinstall"
+
)
  /usr/pluto/bin/Update_StartupScrips.sh
+
  }
+
for Q in "${Queries[@]}"; do
 
+
RunSQL "$Q"
  Configure_Network_Options () {
+
done
  # Updating hosts file and the Device_Data for the core with the internal and external network
+
DT_DiskDrive=11
  # addresses - uses Initial_DHCP_Config.sh from the pluto-install-scripts package.
+
DiskDrives=$(RunSQL "SELECT PK_Device FROM Device WHERE FK_DeviceTemplate='$DT_DiskDrive'")
  echo "Configuring your internal network" > /tmp/messenger
+
for DiskDrive in $DiskDrives ;do
  #Source the SQL Ops file
+
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
  ## Setup /etc/hosts
+
RunSQL "DELETE FROM \\`$table\\` WHERE FK_DeviceID = '$DiskDrive_DeviceID' LIMIT 1"
  echo > /etc/hosts
+
done
  echo "127.0.0.1 localhost.localdomain localhost" >> /etc/hosts
+
RunSQL "DELETE FROM Device WHERE PK_Device = '$DiskDrive_DeviceID' LIMIT 1"
  echo "$c_netExtIP dcerouter $(/bin/hostname)"    >> /etc/hosts
+
done
 
+
fi
  error=false
+
}
  Network=""
+
  Digits_Count=0
+
VideoDriverLive () {
 
+
vga_pci=$(lspci -v | grep -i 'VGA')
  for Digits in $(echo "$c_netIntIPN" | tr '.' ' ') ;do
+
prop_driver="vesa"
  [[ "$Digits" == *[^0-9]* ]]           && error=true
+
chip_man=$(echo "$vga_pci" | grep -Eo '(ATI|VIA|nVidia|Intel)')
  [[ $Digits -lt 0 || $Digits -gt 255 ]] && error=true
+
case $chip_man in
 
+
nVidia)
  if [[ "$Network" == "" ]] ;then
+
prop_driver="nvidia"  ;;
  Network="$Digits"
+
  else
+
ATI)
  Network="${Network}.${Digits}"
+
prop_driver="fglrx"
  fi
+
if echo $vga_pci | grep -Ei '(r5|r6|r7)'; then
 
+
prop_driver="radeonhd"; fi
  Digits_Count=$(( $Digits_Count + 1 ))
+
if echo "$vga_pci" | grep -E '((9|X|ES)(1|2?)([0-9])(5|0)0|Xpress)'; then
  done
+
prop_driver="radeon"; fi ;;
  [[ $Digits_Count -lt 1 || $Digits_Count -gt 3 ]] && error=true
+
 
+
Intel)
  if [[ "$error" == "true" ]] ;then
+
prop_driver="intel"
  Network="192.168.80"
+
if echo $vga_pci | grep "i740"; then
  Digits_Count="3"
+
prop_driver="i740"; fi
  fi
+
if echo $vga_pci | grep "i128"; then
 
+
prop_driver="i128"; fi ;;
  IntIP="$Network"
+
  IntNetmask=""
+
VIA)
  for i in `seq 1 $Digits_Count` ;do
+
prop_driver="openchrome" ;
  if [[ "$IntNetmask" == "" ]] ;then
+
if echo $vga_pci | grep -i "Savage"; then
  IntNetmask="255"
+
prop_driver="savage"; fi
  else
+
#if echo $vga_pci | grep -i "s3"; then
  IntNetmask="${IntNetmask}.255"
+
#prop_driver="via"; fi
  fi
+
if echo $vga_pci | grep -i "virge"; then
  done
+
prop_driver="virge"; fi ;;
  for i in `seq $Digits_Count 3` ;do
+
esac
  if [[ $i == "3" ]] ;then
+
  IntIP="${IntIP}.1"
+
### Install driver based on the type of video card used
  else
+
#Install nouveau driver to avoid reboot if nvidia
  IntIP="${IntIP}.0"
+
  fi
+
case $prop_driver in
 
+
nvidia)
  IntNetmask="${IntNetmask}.0"
+
apt-get -yf install xserver-xorg-nouveau-video ;;
  done
+
radeon)
 
+
apt-get -yf install xserver-xorg-video-radeon ;;
  if [[ "$c_netIntName" == "" ]] ;then
+
fglrx)
  IntIf="$c_netExtName:0"
+
apt-get -yf install fglrx ;;
  else
+
radeonhd)
  IntIf="$c_netIntName"
+
apt-get -yf install xserver-xorg-video-radeonhd ;;
  fi
+
intel)
 
+
apt-get -yf install xserver-xorg-video-intel ;;
  if [[ "$c_singleNIC" == "1" ]] ;then
+
i128)
  #Disable firewalls on single NIC operation, refs #396
+
apt-get -yf install xserver-xorg-video-i128 ;;
  echo "We are in single NIC mode -> internal firewalls disabled"
+
i740)
  echo "DisableFirewall=1" >>/etc/pluto.conf
+
apt-get -yf install xserver-xorg-video-i740 ;;
  echo "DisableIPv6Firewall=1" >>/etc/pluto.conf
+
openchrome)
  fi
+
apt-get -yf install xserver-xorg-video-openchrome ;;
 
+
savage)
  if [[ "$c_netExtUseDhcp" == "0" ]] ;then
+
apt-get -yf install xserver-xorg-video-savage ;;
  NETsetting="$c_netExtName,$c_netExtIP,$c_netExtMask,$c_netExtGateway,$c_netExtDNS1|$IntIf,$IntIP,$IntNetmask"
+
via)
  else
+
apt-get -yf install xserver-xorg-video-s3 ;;
  NETsetting="$c_netExtName,dhcp|$IntIf,$IntIP,$IntNetmask"
+
virge)
  fi
+
apt-get -yf install xserver-xorg-video-s3virge ;;
 
+
esac
  DHCPsetting=$(/usr/pluto/install/Initial_DHCP_Config.sh "$Network" "$Digits_Count")
+
if [[ "$chip_man" == "Intel" ]]; then
 
+
apt-get -yf install libva-driver-i965
  Q="REPLACE INTO Device_DeviceData(FK_Device,FK_DeviceData,IK_DeviceData) VALUES('$Core_PK_Device',32,'$NETsetting')"
+
fi
  RunSQL "$Q"
+
VideoDriver="$prop_driver"
  if [[ "$c_runDhcpServer" == "1" ]]; then
+
}
  Q="REPLACE INTO Device_DeviceData(FK_Device, FK_DeviceData, IK_DeviceData)
+
  VALUES($Core_PK_Device, 28, '$DHCPsetting')"
+
InitialBootPrep () {
  RunSQL "$Q"
+
#Setup Runlevel 3
  fi
+
rm -rf /etc/rc3.d/*
  # create empty IPv6 tunnel settings field
+
cp -a /etc/rc2.d/* /etc/rc3.d/
  Q="REPLACE INTO Device_DeviceData(FK_Device,FK_DeviceData,IK_DeviceData) VALUES('$Core_PK_Device',292,'')"
+
ln -sf /etc/init.d/linuxmce /etc/rc5.d/S99linuxmce
  RunSQL "$Q"
+
rm -f /etc/rc3.d/S99kdm /etc/rc3.d/S990start_avwizard
  }
+
 
+
#Setup Runlevel 4
  VideoDriverSetup () {
+
rm -rf /etc/rc4.d/*
  echo "Starting video driver setup" > /tmp/messenger
+
cp -a /etc/rc2.d/* /etc/rc4.d/
 
+
ln -sf /etc/init.d/linuxmce /etc/rc5.d/S99linuxmce
  touch /etc/X11/xorg.conf
+
 
+
#Setup Runlevel 5
  ## Install driver based on the type of video card used
+
rm -rf /etc/rc5.d/*
  if lshwd | grep -qi 'VGA .* (nv)'; then
+
cp -a /etc/rc2.d/* /etc/rc5.d/
  . /usr/pluto/bin/nvidia-install.sh
+
ln -sf /etc/init.d/linuxmce /etc/rc5.d/S99linuxmce
  installCorrectNvidiaDriver
+
  fi
+
#Create inittab config
  }
+
cat <<EOL > /etc/inittab
 
+
# WARNING: Do NOT set the default runlevel to 0 (shutdown) or 6 (reboot).
  addAdditionalTTYStart () {
+
#id:2:initdefault: # KDE
  if [[ "$DISTRO" = "lucid" ]] ; then
+
#id:3:initdefault: # Core
  sed -i 's/23/235/' /etc/init/tty2.conf
+
#id:4:initdefault: # Core + KDE
  sed -i 's/23/235/' /etc/init/tty3.conf
+
id:5:initdefault: # Launch Manager
  sed -i 's/23/235/' /etc/init/tty4.conf
+
EOL
  # disable plymouth splash for now. Could be replaced by own LMCE splash later
+
  sed -i 's/ splash//' /etc/default/grub
+
# Remove KDM startup
  #Setup vmalloc for video drivers
+
echo "/bin/false" > /etc/X11/default-display-manager
  sed -i 's/GRUB_CMDLINE_LINUX=\"\"/GRUB_CMDLINE_LINUX=\"vmalloc=256m\"/' /etc/default/grub
+
# 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.
  /usr/sbin/update-grub
+
  else
+
chattr +i /etc/X11/default-display-manager
  echo "start on runlevel 5">>/etc/event.d/tty2
+
cp /usr/pluto/bin/firstboot /etc/rc5.d/S90firstboot
  echo "start on runlevel 5">>/etc/event.d/tty3
+
chmod 755 /etc/rc5.d/S90firstboot
  echo "start on runlevel 5">>/etc/event.d/tty4
+
echo >> /etc/apt/sources.list
  fi
+
/usr/share/update-notifier/notify-reboot-required
  }
+
}
 
+
  TempEMIFix () {
+
###########################################################
  #Until the new id-my-disc package is implemented, this will allow the external_media_identifier to launch
+
### If running the LIVE dvd boot
  ln -s /usr/lib/libdvdread.so.4 /usr/lib/libdvdread.so.3
+
###########################################################
  }
+
 
+
live_boot=$(ps aux | grep ubiquity | wc -l)
  ReCreatePackagesFiles () {
+
if grep -q "Live session user" /etc/passwd && [[ "$live_boot" -lt "2" ]]; then  
  echo "Creating necessary package files" > /tmp/messenger
+
echo "/bin/false" > /etc/X11/default-display-manager
  pushd /usr/pluto/deb-cache
+
chattr +i /etc/X11/default-display-manager
  dpkg-scanpackages -m . /dev/null | tee Packages | gzip -c > Packages.gz
+
service kdm stop
  popd
+
pkill X
  }
+
ConfSet AVWizardDone 1
 
+
mv /root/new-installer/runners/* /etc/init.d
  SetupNetworking () {
+
rm /root/new-installer/spacemaker
  rm -f /etc/X11/xorg.conf
+
Nic_Config
  rm -f /etc/network/interfaces
+
Setup_NIS
 
+
Configure_Network_Options
  ## Reconfigure networking
+
addAdditionalTTYStart
  /usr/pluto/bin/Network_Setup.sh
+
TempEMIFix
  /etc/init.d/networking restart
+
InitialBootPrep
  /usr/pluto/bin/DHCP_config.sh
+
/etc/init.d/networking restart
  /etc/init.d/networking restart
+
sleep 3
  /usr/pluto/bin/Network_Firewall.sh
+
ConfSet AVWizardDone 0
  /usr/pluto/bin/ConfirmInstallation.sh
+
ConfSet AVWizardOverride 1
  /usr/pluto/bin/Timezone_Detect.sh
+
echo "Starting firstboot script" > $Messg_File
  }
+
ReCreatePackagesFiles
 
+
SetupNetworking
  CleanInstallSteps () {
+
VideoDriverLive
  if [[ -f /etc/pluto/install_cleandb ]]; then
+
echo "Firstboot Script Complete" > $Messg_File
 
+
sleep 2
          # on upgrade, the old keys are already in place, so keep them
+
/usr/pluto/bin/AVWizard_Run.sh
          rm -f /etc/ssh/ssh_host_*
+
/etc/init.d/linuxmce
          dpkg-reconfigure -pcritical openssh-server
+
fi
 
+
          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
+
  }
+
 
+
  CreateDisklessImage () {
+
  echo "Building a disk image for your Diskless Media Directors" > /tmp/messenger
+
  local diskless_log=/var/log/pluto/Diskless_Create-`date +"%F"`.log
+
  nohup /usr/pluto/bin/Diskless_CreateTBZ.sh >> ${diskless_log} 2>&1 &
+
  }
+
 
+
  VideoDriverLive () {
+
  ## Install driver based on the type of video card used
+
  if lshwd | grep -qi 'VGA .* (nv)'; then
+
          apt-get -y -f install xserver-xorg-nouveau-video
+
  elif lshwd | grep -qi 'VGA .* (radeon)'; then
+
          # Check to see if old Radeon card, if so, do not install new driver
+
          if ! lshwd | grep -Pqi 'VGA .*Radeon ((9|X|ES)(1|2?)([0-9])(5|0)0|Xpress) (.*) \(radeon\)'; then
+
                apt-get -y -f install xorg-driver-fglrx
+
          fi
+
  fi
+
  }
+
 
+
 
+
 
+
  InitialBootPrep () {
+
  echo "Preparing initial reboot" > /tmp/messenger
+
 
+
  #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 >/etc/inittab <<"EOF"
+
  # 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
+
  EOF
+
 
+
 
+
 
+
  # Remove KDM startup
+
  echo "/bin/false" >/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
+
  ###########################################################
+
 
+
  liveboot=$(ps aux | grep ubiquity | wc -l)
+
    if [ `whoami` == ubuntu ] && [ "$liveboot" -lt "2" ]; then  
+
        ConfSet AVWizardDone 1
+
        mv /root/new-installer/lmcemaster/runners/* /etc/init.d
+
        Nic_Config
+
        pinger
+
        gpgUpdate
+
        TimeUpdate
+
        Pre-InstallNeededPackages
+
        CreatePackagesFiles
+
        PreSeed_Prefs
+
        Fix_Initrd_Vmlinux
+
        Setup_Pluto_Conf
+
        Setup_NIS
+
        Create_And_Config_Devices
+
        Configure_Network_Options
+
        UpdateUpgrade
+
        VideoDriverSetup
+
        addAdditionalTTYStart
+
        TempEMIFix
+
        InitialBootPrep
+
        /etc/init.d/networking restart
+
        sleep 3
+
          if lspci | grep -qi 'vga' | grep -qi 'nvidia'; then
+
              sed 's/nvidia/nouveau/g' /etc/X11/xorg.conf
+
              sed 's/nvidia/nouveau/g' /etc/X11/xorg.conf.pluto
+
              sed 's/nv/nouveau/g' /etc/X11/xorg.conf
+
              sed 's/nv/nouveau/g' /etc/X11/xorg.conf.pluto
+
          fi 
+
        ConfSet AVWizardDone 0
+
        ConfSet AVWizardOverride 1
+
        echo "Starting firstboot script" > /tmp/messenger
+
        ReCreatePackagesFiles
+
        SetupNetworking
+
        CleanInstallSteps
+
        #CreateDisklessImage
+
        VideoDriverLive
+
        echo "Firstboot Script Complete"
+
        echo ""
+
        echo ""
+
        echo ""
+
        echo "/bin/false" > /etc/X11/default-display-manager
+
        sleep 2
+
        /usr/pluto/bin/AVWizard_Run.sh
+
        /etc/init.d/linuxmce
+
    fi
+
 
+
 
+
 
+
 
+
 
+
  
 
==firstboot==
 
==firstboot==

Revision as of 11:35, 30 March 2012

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, as well as the script dvd-installer.sh. 
 # GeneralFunctions.sh and firstboot are expected as well, either  
 # already in /usr/pluto/bin or the user directory
 # This script is free under GNU2 license.
 ##################################################################
 
 set -e
   
 DDDIR=`mktemp -d 1004-dd.XXXXXXXXXX`
 WORKDIR=`mktemp -d 1004-wrk.XXXXXXXXXX`
 ISODIR=`mktemp -d 1004-iso.XXXXXXXXXX`
 NEWINST="/root/new-installer"
 MASTERDIR="$NEWINST/lmcemaster"
 DDMASTER="$DDDIR$MASTERDIR"
 WORKMASTER="$WORKDIR$MASTERDIR"
 CUSTOMISO="LMCE-1004-beta.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 $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   
    if [ -e $WORKMASTER/runners/0start_avwizard ]; then mv $WORKMASTER/runners/* $WORKDIR/etc/init.d; fi
 #   if [ -e $DDMASTER/runners/0start_avwizard ]; then mv $DDMASTER/runners/* $WORKDIR/etc/init.d; fi
 }
 
 ### TODO attach general functions to Utils.sh or equiv, or add GeneralFucntions.sh to pluto/bin scripts. 
 cp GeneralFunctions.sh $DDDIR/usr/pluto/bin
 ### TODO creating and destroying this file seems like a bad idea, so I am moving it to /usr/pluto/bin
 cp firstboot $DDDIR/usr/pluto/bin
 . $DDDIR/usr/pluto/bin/GeneralFunctions.sh
 confirmRoot
    NotifyMessage "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 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 -
 EOL
  
   
    # Make 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
 
 
 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
 echo "Performing post-install steps. Please be patient." > /target/tmp/messenger
 su - ubuntu -c /cdrom/install/messages.sh &
 chroot /target /root/new-installer/postinst.sh
 EOL
 
 
 ### Make On Screen Display
 cat <<EOL > $ISODIR/install/messages.sh
 #!/bin/bash
 export DISPLAY=:0
 msgchk=/target/tmp/msgchk
 newmsg=/target/tmp/messenger
 if [ ! -f \$msgchk ]; then touch -r \$msgchk; fi
 while true; do if [ \$newmsg -nt \$msgchk ]; then /target/usr/pluto/bin/BootMessage.sh "\`cat \$newmsg\`"; touch -r \$newmsg \$msgchk; fi; done
 EOL
 
 
 ### The main post-installer
 cat <<EOL > $WORKDIR/root/new-installer/postinst.sh
 #!/bin/bash
 . /usr/pluto/bin/GeneralFunctions.sh
 . /root/new-installer/dvd-installer.sh
 export LC_ALL=C
 echo "Please be patient while post-installer finalizes new install" > /tmp/messenger
 service mysql stop
 sleep 3
 mysqld --skip-networking&
 cp /etc/network/interfaces.temp /etc/network/interfaces
 #Execute Functions
 pinger
 gpgUpdate
 TimeUpdate
 Pre-InstallNeededPackages
 CreatePackagesFiles
 PreSeed_Prefs
 Fix_Initrd_Vmlinux
 Nic_Config
 Setup_Pluto_Conf
 Setup_NIS
 Create_And_Config_Devices
 Configure_Network_Options
 UpdateUpgrade
 VideoDriverSetup
 addAdditionalTTYStart
 TempEMIFix
 CreateFirstBoot
 InitialBootPrep
 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
 mv /root/new-installer/lmcemaster/runners/* /etc/init.d
 update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth /lib/plymouth/themes/LinuxMCE/LinuxMCE.plymouth 900
 update-initramfs -u
 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 "Rebooting" > /target/tmp/messenger
 sleep 3
 #rm /target/tmp/messenger
 reboot
 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"
    cp dvd-installer.sh $WORKDIR/root/new-installer
    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
    
    StatusMessage "Downloading tools to the HOST needed for mastering."
    apt-get install -y squashfs-tools syslinux squashfs-tools genisoimage sbm ubuntu-standard casper lupin-casper discover1 laptop-detect os-prober linux-generic grub2 plymouth-x11 ubiquity-frontend-kde libvte-common libvte9 python-glade2 python-vtk
    
    StatusMessage "Configuring temporary chrooted network. Please be patient."
    mkdir -p $DDDIR/etc/udev/rules.d
    cp /etc/udev/rules.d/70-persistent-net.rules $DDDIR/etc/udev/rules.d/
    LC_ALL=C chroot $DDDIR /etc/init.d/networking restart
    LC_ALL=C chroot $DDDIR apt-get update
    
    StatusMessage "Downloading necessary tools for re-mastering in chroot..."
    # TODO remove these packages on dvd post-install. No reason for them to exist
    # Make dummy file for pluto-dcerouter to modify
    if [ ! -e $DDDIR/sbin/losetup ]; then echo > $DDDIR/sbin/losetup; fi
    if [ ! -e $DDDIR/sbin/udevtrigger ]; then echo > $DDDIR/sbin/udevtrigger; fi
    LC_ALL=C chroot $DDDIR apt-get -y -q install casper cryptsetup debconf-utils dialog dmraid ecryptfs-utils gnome-osd libdebconfclient0 libdebian-installer4 libdmraid1.0.0.rc16 libecryptfs0 localechooser-data memtest86+ python-pyicu rdate reiserfsprogs squashfs-tools ubiquity ubiquity-casper ubiquity-ubuntu-artwork ubiquity-frontend-kde user-setup xresprobe xserver-xorg-video-nouveau pluto-proxy-orbiter pluto-asterisk libestools1.2 libmp3lame0 lmce-plymouth-theme --allow-unauthenticated
    
    StatusMessage "Upgrading chroot"
    # Upgrade only necessary if a build has happened since scratch creation.
    # Chances are will want mysql up... which I have experienced nothing but failure with
 
    #LC_ALL=C chroot $DDDIR apt-get -y upgrade --force-yes
    
    # Popularity contest conflicts with ubiquity installer, so we remove if installed.
    # TODO this should not be necessary anymore as we are not loading ubuntu-standard anymore. Just for safety and clean.
    LC_ALL=C chroot $DDDIR apt-get remove -yq popularity-contest
    LC_ALL=C chroot $DDDIR apt-get clean
 
 #####################################
 # Prepping the dvd file system
 #####################################
 
    ### This moves things around and creates the file system to be squashed.
    StatusMessage "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-1920x1200.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='*.[0-9].gz' --exclude='*.deb' --exclude='*.bak'  $VAREXCLUDES-a $DDDIR/var/. $WORKDIR/var/.
    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.crt
    rm -rf $WORKDIR/etc/cups/ssl/server.key
    rm -rf $WORKDIR/etc/ssh/ssh_host_rsa_key
    rm -rf $WORKDIR/etc/ssh/ssh_host_dsa_key.pub
    rm -rf $WORKDIR/etc/ssh/ssh_host_dsa_key
    rm -rf $WORKDIR/etc/ssh/ssh_host_rsa_key.pub
    rm -rf $WORKDIR/etc/gdm/gdm.conf-custom
    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/shadow
    rm -rf $WORKDIR/etc/shadow-
    rm -rf $WORKDIR/etc/gshadow
    rm -rf $WORKDIR/etc/gshadow-
    rm -rf $WORKDIR/etc/wicd/wired-settings.conf
    rm -rf $WORKDIR/etc/wicd/wireless-settings.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
    # 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
    StatusMessage "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
    sleep 1
    
    cp $DDDIR/etc/casper.conf $WORKDIR/etc/
    sleep 1
    
    # 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)
    ###TODO Remove the move
    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"
    # TODO change initrd
    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"
    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*
 #/root/new-installer/postinst.sh
 exit 0
 EOL
    
    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
    
    
    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
 
 # Make executables
 chmod +x $ISODIR/install/postseed.sh
 chmod +x $ISODIR/install/messages.sh
 chmod +x $WORKDIR/root/new-installer/postinst.sh
 chmod +x $WORKDIR/etc/init.d/0start_avwizard
 chmod +x $WORKDIR/etc/init.d/nis
 chmod +x $WORKDIR/etc/init.d/linuxmce
 
 #This places the post installer, which calls on dvd-installer.sh
    echo > $WORKDIR/root/.bashrc
 
    # 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"
    NotifyMessage "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
    sleep 1
    
    NotifyMessage "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
    sleep 2
    
    #add some stuff the log in case of problems so I can troubleshoot it easier
    echo "------------------------------------------------------" >>lmcemaster.log
    echo "Mount information" >>lmcemaster.log
    mount >>lmcemaster.log
    echo "------------------------------------------------------" >>lmcemaster.log
    echo "Casper Script info" >>lmcemaster.log
    ls -l $DDDIR/usr/share/initramfs-tools/scripts/casper-bottom/ >>lmcemaster.log
    echo "------------------------------------------------------" >>lmcemaster.log
    echo "/etc/casper.conf info" >>lmcemaster.log
    cat $DDDIR/etc/casper.conf >>lmcemaster.log
    echo "------------------------------------------------------" >>lmcemaster.log
    echo "/etc/passwd info" >>lmcemaster.log
    cat $WORKDIR/etc/passwd >>lmcemaster.log
    echo "------------------------------------------------------" >>lmcemaster.log
    echo "/etc/group info" >>lmcemaster.log
    cat $WORKDIR/etc/group >>lmcemaster.log
    echo "------------------------------------------------------" >>lmcemaster.log
    echo "Command-line options = $@" >>lmcemaster.log
    echo "------------------------------------------------------" >>lmcemaster.log
    sleep 1
    
    # 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
     ErrorMessage "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
     ErrorMessage "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
     ErrorMessage " 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
    
    sleep 1
    
    # Make the ISO file
    StatusMessage "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
     ErrorMessage "Something has gone horribly wrong. Iso does not exist. Exiting."
    else
     NotifyMessage "Success!!! `ls -hs $CUSTOMISO` is ready to be burned or tested in a virtual machine."
    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
    sleep 1
    umount -lf `mount | grep 1004-dd | grep loop | awk '{print $3}'`
    rm -r $DDDIR
    rm -r $WORKDIR
    rm -r $ISODIR
    exit 0
 }
 
 StatusMessage "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
 ###########################################################
 ### Setup global variables
 ###########################################################
 LogFile="/var/log/pluto/firstboot.log"
 trap 'rm -f /etc/rc5.d/S90firstboot' EXIT
 
 
 ###########################################################
 ### Setup Functions - Error checking and logging
 ###########################################################
 
 Setup_Logfile () {
 if [ -f ${log_file} ]; then
         touch ${log_file}
         if [ $? = 1 ]; then
                 echo "`date` - Unable to write to ${log_file} - re-run script as root"
                 exit 1
         else
                 echo "`date` - Logging initiatilized to ${log_file}"
         fi
 else
         #0 out an existing file
         echo > ${log_file}
         echo "`date` - Setup has run before, clearing old log file at ${log_file}"
 fi
 }
 
 VerifyExitCode () {
         local EXITCODE=$?
         if [ "$EXITCODE" != "0" ] ; then
                 echo "An error (Exit code $EXITCODE) occured during the last action"
                 echo "$1"
                 exit 1
         fi
 }
 
 StatsMessage () {
         printf "`date` - $* \n"
 }
 
 ###########################################################
 ### Setup Functions - General functions
 ###########################################################
 
 ReCreatePackagesFiles () {
 StatsMessage "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
 /etc/init.d/networking restart
 /usr/pluto/bin/DHCP_config.sh
 /etc/init.d/networking restart
 /usr/pluto/bin/Network_Firewall.sh
 /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
 
         . /usr/pluto/bin/SQL_Ops.sh
         . /usr/pluto/bin/Config_Ops.sh
 
         # 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
 }
 
 CreateDisklessImage () {
 StatsMessage "Building a disk image for your Diskless Media Directors"
 local diskless_log=/var/log/pluto/Diskless_Create-`date +"%F"`.log
 nohup /usr/pluto/bin/Diskless_CreateTBZ.sh >> ${diskless_log} 2>&1 &
 }
 
 VideoDriver () {
 ## Install driver based on the type of video card used
 if lshwd | grep -qi 'VGA .* (nv)'; then
         apt-get -y -f install pluto-nvidia-video-drivers
                 VerifyExitCode "Install Pluto nVidia Driver"
 elif lshwd | grep -qi 'VGA .* (radeon)'; then
         # Check to see if old Radeon card, if so, do not install new driver
         if ! lshwd | grep -Pqi 'VGA .*Radeon ((9|X|ES)(1|2?)([0-9])(5|0)0|Xpress) (.*) \(radeon\)'; then
                apt-get -y -f install xorg-driver-fglrx
                            VerifyExitCode "Install Radeon Driver"
         fi
 fi
 }
 
 ###########################################################
 ### Main execution area
 ###########################################################
 
 #Setup logging
 . /usr/pluto/bin/TeeMyOutput.sh --outfile "$LogFile" --stdboth --append -- "$@"
 
 StatsMessage "Starting firstboot script"
 ReCreatePackagesFiles
 SetupNetworking
 CleanInstallSteps
 #CreateDisklessImage
 VideoDriver
 StatsMessage "Firstboot Script Complete"
 reboot



GeneralFunctions.sh

 #!/bin/bash
 
 # Colors and bolds messages
 # '\E begin escape sequence
 # [XX; is the text color
 # XXm' is the background color
 # \033 is the an escape
 # [1m bold     [0m unbold
 # "" around text    around color
 # COLOR         FOREGROUND      BACKGROUND
 # black         30              40
 # red           31              41
 # green         32              42
 # yellow        33              43
 # blue          34              44
 # magenta       35              45
 # cyan          36              46
 # white         37              47
 
 StatusMessage () { 
 echo -e '\E[33;40m'"\033[1m  $* \033[0m" 
 }
 ErrorMessage () { 
 echo -e '\E[33;41m'"\033[1m  $* \033[0m" 
 }
 NotifyMessage () {
 echo -e '\E[32;40m'"\033[1m  $* \033[0m" 
 }
 
 # Looks for a ping reply. Without one restarts networking. Occasionally helpful
 pinger () {
 
 while ! ping -c 1 google.com > /dev/null 2>&1; do /etc/init.d/networking restart; sleep 3; done
 }
 
 # This does an update, while adding gpg keys for any that are missing. This is primarily for medibuntu
 # but will work for any source.
 gpgUpdate () {
 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
 }
 
 confirmRoot () {
 testroot="`whoami`"
 if [ "$testroot" != "root" ]; then
    ErrorMessage "Need to be root to run. Exiting"
    exit 1
 fi
 }


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