#!/bin/bash
#================
# FILE          : linuxrc
#----------------
# PROJECT       : OpenSuSE KIWI Image System
# COPYRIGHT     : (c) 2006 SUSE LINUX Products GmbH. All rights reserved
#               :
# AUTHOR        : Marcus Schaefer <ms@suse.de>
#               :
# BELONGS TO    : Operating System images
#               :
# DESCRIPTION   : This file is changed to become the real
#               : linuxrc script which is used to prepare the
#               : operating system for the main image
#               :
#               :
# STATUS        : BETA
#----------------
#======================================
# Exports (General)...
#--------------------------------------
export PATH="/sbin:/bin:/usr/sbin:/usr/bin"
export IFS_ORIG=$IFS
export DEBUG=0
export bootid=0

#======================================
# Exports (Booting)
#--------------------------------------
export DOMURD_MODULES="xennet xenblk"
export INITRD_MODULES="reiserfs"
export LOCAL_BOOT=no
export systemIntegrity="clean"

#======================================
# Exports (Configuration)
#--------------------------------------
export VMX_SYSTEM="/config.vmxsystem"
export LIVECD_CONFIG=$VMX_SYSTEM
export OEM_PARTITION_CONFIG="/config.oempartition"

#======================================
# Functions...
#--------------------------------------
. /include
. /repart
. /dump

#======================================
# Beautify Startup
#--------------------------------------
echo "Loading KIWI OEM Boot-System..."
echo "-------------------------------"

#======================================
# 1) Mounting local file systems
#--------------------------------------
mountSystemFilesystems &>/dev/null
closeKernelConsole

#======================================
# 2) Prepare module load support 
#--------------------------------------
touch /etc/modules.conf
touch /lib/modules/*/modules.dep

#======================================
# 3) run udevd
#--------------------------------------
udevStart

#======================================
# 4) Include proc/cmdline information
#--------------------------------------
includeKernelParameters
if \
	[ ! -z $UNIONFS_CONFIG ] || [ "$COMBINED_IMAGE" = "local" ] ||\
	[ ! -z $KIWI_RECOVERY ]
then
	# /.../
	# if the unionfs/combined information is already in place at this
	# stage it comes from the cmdline data which means we are not
	# booting from CD/DVD USB stick but want to boot the local system
	# This also applies if we use an oem system with the recovery
	# feature enabled
	# ----
	export LOCAL_BOOT="yes"
fi

#======================================
# 5) start boot shell
#--------------------------------------
startBlogD
startShell
errorLogStart
openKernelConsole

#======================================
# 6) Including required kernel modules
#--------------------------------------
probeDevices

#======================================
# 7) Check for installation mode...
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then
	OEMInstall
fi

#======================================
# 8) Search boot device...
#--------------------------------------
Echo "Searching for boot device..."
export imageDiskDevice=`searchBIOSBootDevice`

#======================================
# 9) Get filesystem type and boot ID
#--------------------------------------
export imageBootID=1
probeFileSystem $imageDiskDevice$imageBootID
if [ $FSTYPE = "unknown" ];then
	imageBootID=2
	probeFileSystem $imageDiskDevice$imageBootID
	if [ $FSTYPE = "unknown" ];then
		systemException \
			"Couldn't determine filesystem type... abort" \
		"reboot"
	fi
fi

#======================================
# 10) Setup device names...
#--------------------------------------
export imageRootDevice=$imageDiskDevice$imageBootID
export imageRWDevice=$imageDiskDevice"2"
export imageRODevice=$imageDiskDevice"1"
export imageIOWRDevice=$imageDiskDevice"2"
if [ ! -z "$RECOVERY" ];then
	export imageRecoveryDevice=$imageDiskDevice"4"
	export imageRootDevice=$imageDiskDevice"2"
fi
if [ -z "$imageDiskDevice" ];then
	systemException \
		"Couldn't find any boot device... abort" \
	"reboot"
fi
Echo "Searching for kiwiVG volume group..."
if searchVolumeGroup; then
	export haveLVM=yes
	if [ -e /dev/kiwiVG/LVComp ];then
		export imageRootDevice=/dev/kiwiVG/LVComp
	else
		export imageRootDevice=/dev/kiwiVG/LVRoot
	fi
	export imageRWDevice=/dev/kiwiVG/LVRoot
	export imageRODevice=/dev/kiwiVG/LVComp
	export imageIOWRDevice=/dev/kiwiVG/LVRoot
	export imageBootDevice=$imageDiskDevice"2"
	if [ ! -z "$RECOVERY" ];then
		export imageRecoveryDevice=/dev/kiwiVG/LVRecovery
	fi
fi

#======================================
# 11) Check filesystem
#--------------------------------------
Echo "Filesystem of OEM system is: $FSTYPE -> $imageRootDevice"
if isFSTypeReadOnly;then
	setupUnionFS $imageRWDevice $imageRODevice aufs
	bootid=1
fi

#======================================
# 12) Import OEM partition config
#--------------------------------------
if [ $LOCAL_BOOT = "no" ] && [ -f $OEM_PARTITION_CONFIG ];then
	Echo "Including oem partition info file"
	importFile < $OEM_PARTITION_CONFIG
fi

#======================================
# 13) repartition the disk device
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then
	OEMRepart
fi

#======================================
# 14) Resize filesystem to full space
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then
	deviceResize=$imageRootDevice
	fstypeRootFS=$FSTYPE
	if [ ! -z $COMBINED_IMAGE ];then
		deviceResize=$imageIOWRDevice
		KIWI_INITRD_PARAMS="COMBINED_IMAGE=local"
		probeFileSystem $deviceResize
		export KIWI_INITRD_PARAMS
	fi
	if isFSTypeReadOnly && [ -z "$COMBINED_IMAGE" ];then
		deviceResize=$imageIOWRDevice
		KIWI_INITRD_PARAMS="UNIONFS_CONFIG=yes"
		probeFileSystem $deviceResize
		export KIWI_INITRD_PARAMS
	fi
	if [ ! -z "$deviceResize" ] && partitionSize $deviceResize &>/dev/null;then
		if [ ! -z "$OEM_RECOVERY" ];then
			KIWI_INITRD_PARAMS="$KIWI_INITRD_PARAMS LOCAL_BOOT=yes"
			KIWI_INITRD_PARAMS="$KIWI_INITRD_PARAMS RECOVERY=yes"
			export KIWI_INITRD_PARAMS
		fi
		if [ -z "$DONT_PARTITION" ];then
			if [ "$FSTYPE" = "reiserfs" ];then
				Echo "Resize Reiser filesystem to full partition space..."
				resize_reiserfs -q $deviceResize
				INITRD_MODULES="$INITRD_MODULES reiserfs"
			fi
			if [ "$FSTYPE" = "ext2" ];then
				Echo "Resize EXT2 filesystem to full partition space..."
				resize2fs -f -F -p $deviceResize
				Echo "Checking EXT2 filesystem..."
				e2fsck -p $deviceResize
				INITRD_MODULES="$INITRD_MODULES ext2"
			fi
			if [ "$FSTYPE" = "ext3" ];then
				Echo "Resize EXT3 filesystem to full partition space..."
				resize2fs -f -F -p $deviceResize
				Echo "Checking EXT3 filesystem..."
				e2fsck -p $deviceResize
				INITRD_MODULES="$INITRD_MODULES ext3"
			fi
		fi
	fi
	if [ "$OEM_KIWI_INITRD" = "yes" ];then
		if ! echo $KIWI_INITRD_PARAMS | grep -qi LOCAL_BOOT;then
			KIWI_INITRD_PARAMS="$KIWI_INITRD_PARAMS LOCAL_BOOT=yes"
		fi
	fi
	FSTYPE=$fstypeRootFS
fi

#======================================
# 15) Mount system
#--------------------------------------
if ! mountSystem $imageRootDevice;then
	systemException "Failed to mount root filesystem" "reboot"
fi
validateRootTree

#======================================
# 16) Recover system if requested
#--------------------------------------
if [ ! -z "$KIWI_RECOVERY" ];then
	Echo -n "Do you want to start the System-Recovery ? [y/n]: "; read runReco
	if [ ! $runReco = "y" ];then
		systemException "System-Recovery not started" "reboot"
	fi
	Echo "Starting System-Recovery..."
	#======================================
	# 16.1) mount recovery partition
	#--------------------------------------
	mkdir -p /reco-save
	if ! mount $imageRecoveryDevice /reco-save >/dev/null;then
		systemException "Failed to mount recovery device" "reboot"
	fi
	#======================================
	# 16.2) restore root archive
	#--------------------------------------
	Echo "Restoring base operating system..."
	cd /mnt
	rFiles=$(cat /reco-save/recovery.tar.files)
	tar -xvf /reco-save/recovery.tar.gz >/tmp/rFiles &
	rPID=$!
	while kill -0 $rPID &>/dev/null;do
		rReady=$(cat /tmp/rFiles | wc -l)
		Echo -e -n "$rReady files from $rFiles restored...\r"
		sleep 1
	done
	echo
	#======================================
	# 16.3) restore boot files
	#--------------------------------------
	Echo "Restoring boot files..."
	for i in etc/fstab etc/sysconfig/kernel etc/sysconfig/bootloader;do
		if ! cp /reco-save/$i /mnt/$i;then
			systemException "Failed to restore $i" "reboot"
		fi
	done
	for i in `setupBootLoaderFiles`;do
		if ! cp /reco-save/$i /mnt/$i;then
			systemException "Failed to restore $i" "reboot"
		fi
	done
	for i in /reco-save/boot/grub/*;do
		if echo $i | grep -q .system;then
			sysbase=`echo ${i%%.system}`
			sysbase=`echo $sysbase | cut -f3- -d/`
			cp $i /mnt/$sysbase
		fi
	done
	#======================================
	# 16.4) umount recovery and boot
	#--------------------------------------
	umount $imageRecoveryDevice
fi

#======================================
# 17) get installed kernels
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then
	kernelList /mnt
fi

#======================================
# 18) setup /lvmboot
#--------------------------------------
if [ $LOCAL_BOOT = "no" ] && [ "$haveLVM" = "yes" ];then
	mkdir /mnt/lvmboot
	mount $imageBootDevice /mnt/lvmboot
	if [ -z $UNIONFS_CONFIG ];then
		cp -a /mnt/boot/* /mnt/lvmboot/boot
	fi
	rm -rf /mnt/boot
	( cd /mnt && ln -s lvmboot/boot boot )
fi

#======================================
# 19) setup ird/kernel links for union
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then 
	if [ "$OEM_KIWI_INITRD" = "yes" ] || isFSTypeReadOnly;then
		# /.../
		# we are using a special root setup with aufs. In this case
		# we can't use the SuSE Linux initrd but must stick to the
		# kiwi boot system.
		# ----
		mountCalled=no
		if [ "$haveLVM" = "yes" ];then
			pushd /mnt/lvmboot/boot >/dev/null
		elif [ "$OEM_KIWI_INITRD" = "yes" ];then
			pushd /mnt/boot >/dev/null
		else
			kiwiMount $imageRWDevice "/mnt"
			pushd /mnt/boot >/dev/null
			mountCalled=yes
		fi
		IFS="," ; for i in $KERNEL_LIST;do
			if test -z "$i";then
				continue
			fi
			kernel=`echo $i | cut -f1 -d:`
			initrd=`echo $i | cut -f2 -d:`
			rm -f $initrd && ln -s initrd.vmx $initrd
			rm -f $kernel && ln -s linux.vmx  $kernel
			break
		done
		IFS=$IFS_ORIG
		popd >/dev/null
		if [ "$mountCalled" = "yes" ];then
			umount /mnt
		fi
	fi
fi

#======================================
# 20) Create system dependant files
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then
	#======================================
	# setup: /etc/fstab
	#--------------------------------------
	setupDefaultFstab /config
	updateRootDeviceFstab /config $imageRootDevice
	if [ "$haveLVM" = "yes" ];then
		updateLVMBootDeviceFstab /config $imageBootDevice
	fi
	if partitionSize $imageSwapDevice &>/dev/null;then
		updateSwapDeviceFstab /config $imageSwapDevice
	else
		unset $imageSwapDevice
	fi
	if [ -z "$OEM_WITHOUTHOME" ] && [ -z "$DONT_PARTITION" ];then
		if [ `ls /mnt/home/ | wc -l` != 0 ]; then
			Echo "Found non empty home/ directory !"
			Echo "Moving home/ data to home partition $imageHomeDevice"
			mount $imageHomeDevice /mnt/mnt && mv /mnt/home/* /mnt/mnt
			umount /mnt/mnt
		fi
		Echo "Activate home partition $imageHomeDevice in fstab"
		echo "$imageHomeDevice /home ext3 defaults 0 0" >> /config/etc/fstab
	fi
	#======================================
	# setup: bootloader files
	#--------------------------------------
	Echo "Creating boot loader configuration"
	if [ -z "$OEM_BOOT_TITLE" ];then
		export OEM_BOOT_TITLE="OEM"
	fi
	if [ ! -z $OEM_RECOVERY ];then
		OEM_RECOVERY=$imageRecoveryDevice
	fi
	setupBootLoader \
		/mnt /config $bootid $imageRootDevice \
		"$OEM_BOOT_TITLE" $imageSwapDevice
	setupKernelModules /config
fi

#======================================
# 21) copy system dependant files
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then
	setupConfigFiles
fi

#======================================
# 22) copy recovery related files
#--------------------------------------
if [ $LOCAL_BOOT = "no" ] && [ ! -z "$OEM_RECOVERY" ];then
	IFS=$IFS_ORIG
	Echo "Setting up recovery configuration files..."
	mkdir -p /reco-save
	if ! mount $imageRecoveryDevice /reco-save >/dev/null;then
		systemException "Failed to mount recovery device" "reboot"
	fi
	mkdir -p /reco-save/etc/sysconfig
	if ! cp /mnt/etc/fstab /reco-save/etc;then
		systemException "Failed to copy recovery fstab" "reboot"
	fi
	if ! cp /mnt/etc/sysconfig/kernel /reco-save/etc/sysconfig;then
		systemException "Failed to copy recovery sysconfig/kernel" "reboot"
	fi
	if ! cp /mnt/etc/sysconfig/bootloader /reco-save/etc/sysconfig;then
		systemException "Failed to copy recovery sysconfig/bootloader" "reboot"
	fi
	for i in `setupBootLoaderFiles`;do
		bootdir=`dirname $i` && mkdir -p /reco-save/$bootdir
		if ! cp /mnt/$i /reco-save/$i;then
			systemException "Failed to copy recovery $i" "reboot"
		fi
	done
	Echo "Installing boot loader into recovery partition"
	setupBootLoaderRecovery /mnt /reco-save OEM
	umount /reco-save && rmdir /reco-save
	installBootLoaderRecovery
fi

#======================================
# 23) update system dependant files
#--------------------------------------
setupInittab /mnt

#======================================
# 24) setup real root device
#--------------------------------------
echo 256 > /proc/sys/kernel/real-root-dev

#======================================
# 25) umount system filesystems
#--------------------------------------
umountSystemFilesystems

#======================================
# 26) copy initrd files to image
#--------------------------------------
if [ $LOCAL_BOOT = "no" ];then
	importBranding
fi
cp /preinit /mnt
cp /include /mnt

#======================================
# 27) kill boot shell
#--------------------------------------
killShell
killBlogD

#======================================
# 28) Activate new root
#--------------------------------------
activateImage

#======================================
# 29 Unmount initrd / system init
#--------------------------------------
bootImage $@
