#!/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 includes functions for the OEM
#               : installation mode. Installation means a dump of
#               : the virtual disk file onto a preselected disk
#               :
#               :
# STATUS        : BETA
#----------------
#
#======================================
# OEMInstall
#--------------------------------------
function OEMInstall {
	# /.../
	# Installation mode: find a usable disk to install the image
	# on. The install image is a virtual disk. The system will be
	# rebooted at the end of this function
	# ----
	#======================================
	# Check for install mode indicator file
	#--------------------------------------
	if [ ! -f $VMX_SYSTEM ];then
		return
	fi
	#======================================
	# Search boot device...
	#--------------------------------------
	Echo "Searching for boot device..."
	imageDiskDevice=`searchBIOSBootDevice`

	#======================================
	# Search CD/DVD/USB stick and mount it
	#--------------------------------------
	USBStickDevice
	if [ $stickFound = 0 ];then
		Echo "Search for USB stick failed, checking CD/DVD drive"
		CDMount
		export OEMInstallType=CD
	else
		Echo "Found Stick: $stickRoot -> $stickSerial"
		mkdir -p /cdrom && mount $stickRoot"2" /cdrom
		export OEMInstallType=USB
	fi
	#======================================
	# Search and ask for the install device
	#--------------------------------------
	IFS=$IFS_ORIG
	Echo "Searching harddrive for $OEMInstallType installation"
	hwinfo=/usr/sbin/hwinfo
	if [ "$OEMInstallType" = "USB" ];then
		deviceDisks=`$hwinfo --disk |\
			grep "Device File:" | cut -f2 -d: |\
			cut -f1 -d"(" | sed -e s"@$imageDiskDevice@@"`
	else
		deviceDisks=`$hwinfo --disk |\
			grep "Device File:" | cut -f2 -d: |\
			cut -f1 -d"("`
	fi
	export deviceDisks=`echo $deviceDisks`
	if [ -z "$deviceDisks" ];then
		systemException \
			"No device(s) for installation found... abort" \
		"reboot"
	fi
	Echo "Found following disk device(s)"
	count=0
	for i in $deviceDisks;do
		Echo -b "Disk $count -> $i"
		deviceArray[$count]=$i
		count=`expr $count + 1`
	done
	if [ "$count" = "1" ];then
		#======================================
		# Found one single disk... use it
		#--------------------------------------
		instDisk=${deviceArray[0]}
	else
		#======================================
		# Found multiple disks... ask for it
		#--------------------------------------
		while true;do
			Echo -n "Enter device name to select disk for installation: "
			read deviceInput
			count=0
			for instDisk in $deviceDisks;do
				if [ ${deviceArray[$count]} = $deviceInput ];then
					break 2
				fi
				count=`expr $count + 1`
			done
			Echo "Given device is not in the list !"
		done
	fi
	Echo "Entering installation mode for disk: $instDisk"
	#======================================
	# Import vmx configuration file
	#--------------------------------------
	importFile < $VMX_SYSTEM
	#======================================
	# Install disk system
	#--------------------------------------
	# install virtual disk image from the CD/DVD onto the
	# real disk. All data on the disk will be lost
	# ----
	imageZipped="uncompressed"
	imageDevice=$instDisk
	field=0
	#======================================
	# Evaluate OEM install file
	#--------------------------------------
	IFS=";" ; for n in $IMAGE;do
	case $field in
		0) field=1 ;; 
		1) imageName=$n   ; field=2 ;;
		2) imageVersion=$n; field=3 ;;
		3) imageZipped=$n ;
	esac
	done
	if [ "$imageZipped" = "compressed" ];then
		imageName="/cdrom/$imageName.gz"
		imageMD5="$imageName.md5"
	else
		imageName="/cdrom/$imageName"
		imageMD5="$imageName.md5"
	fi
	IFS=" "
	#======================================
	# Check MBR ID's...
	#--------------------------------------
	mbrI="cat $imageName"
	if [ "$imageZipped" = "compressed" ];then
		mbrI="gzip -cd $imageName"
	fi
	mbrM=`dd if=$instDisk  bs=1 count=4 skip=$((0x1b8))|hexdump -n4 -e '"0x%x"'`
	mbrI=`$mbrI | dd bs=1 count=4 skip=$((0x1b8))|hexdump -n4 -e '"0x%x"'`
	if [ $mbrM = $mbrI ];then
		systemException \
			"Base system already installed" \
		"reboot"
	fi	
	#======================================
	# read MD5 information...
	#--------------------------------------
	read sum1 blocks blocksize zblocks zblocksize < $imageMD5
	#======================================
	# Get available disk space
	#--------------------------------------
	haveKByte=`partitionSize $imageDevice`
	#======================================
	# Get required disk space, setup I/O
	#--------------------------------------
	needBytes=`du --bytes $imageName | cut -f1`
	needKByte=`expr $needBytes / 1024`
	needMByte=`expr $needKByte / 1024`
	if test "$imageZipped" = "compressed"; then
		needBytes=`gzip -l $imageName|tail -n1|sed -e "s@ \+@:@g"|cut -f3 -d:`
		needKByte=`expr $needBytes / 1024`
		needMByte=`expr $needKByte / 1024`
	fi
	#======================================
	# Check disk space...
	#--------------------------------------
	haveMByte=`expr $haveKByte / 1024`
	needMByte=`expr $needKByte / 1024`
	Echo "Have size: $imageDevice -> $haveMByte MB"
	Echo "Need size: $imageName -> $needMByte MB"
	if [ $needMByte -gt $haveMByte ];then
		systemException \
			"Not enough space available for this image" \
		"reboot"
	fi
	#======================================
	# Dump image on disk
	#--------------------------------------
	dump="cat $imageName"
	if test "$imageZipped" = "compressed"; then
		dump="gzip -cd $imageName"
	fi
	if [ -x /usr/bin/dcounter ];then
		errorLogStop
		dump="$dump | dcounter -s $needMByte"
	fi
	Echo -n "Loading $imageName [$imageDevice] "
	if ! eval $dump | dd bs=32k of=$imageDevice &>/dev/null; then
		systemException \
			"Failed to install image: $imageName -> $imageDevice" \
		"reboot"
	fi
	echo
	if [ -x /usr/bin/dcounter ];then
		errorLogContinue
	fi
	#======================================
	# Check the md5sum of the raw disk
	#--------------------------------------
	Echo "Download complete, checking data..."
	dd if=$imageDevice bs=1024 |\
		head --bytes=$((blocks * blocksize)) |\
		md5sum - > /etc/ireal.md5
	read sum2 dumy < /etc/ireal.md5
	if [ $sum1 != $sum2 ];then
		systemException \
			"Image checksum test failed" \
		"reboot"
	fi
	Echo "Image checksum test: fine :-)"
	#======================================
	# Umount CD/DVD USB
	#--------------------------------------
	umount /cdrom
	#======================================
	# Reread partition table
	#--------------------------------------
	blockdev --rereadpt $imageDevice
	deviceTest=$imageDevice"1"
	if ! waitForStorageDevice $deviceTest;then
		systemException \
			"Partition $deviceTest doesn't appear... fatal !" \
		"reboot"
	fi
	#======================================
	# Reboot system
	#--------------------------------------
	if [ "$OEMInstallType" = "CD" ];then
		Echo "NOTE: Please remove the installation CD before reboot !"
		CDEject
	else
		Echo "NOTE: Please unplug the USB stick before reboot !"
	fi
	systemException \
		"System installation has finished" \
	"reboot"
}
