#! /bin/sh

VERSION="14"
EXTERNAL_VERSION="4"
## 0.14
# - Added ubuntu 24.04 support

## 0.13
# - Added efibootmgr package to live os resource

## 0.12
# - Added live ISO support (22.04 and later)

## 0.11
# - Added efibootmgr, libefiboot1 and libefivar packages

## 0.10
# - Removed warning when importing .iso version 20.04

## 0.9
# - Added uuidgen package to handle static ip in Ubuntu 18.04 and 19.04 deployment

## 0.8
# - Removed warning when importing .iso version 17.04, 18.04 and 19.04
# - Renamed default log file name to ubuntu_resource_tool_03.log
# - Renamed the script name in usage to ubuntu_resource_tool_03.sh
# - Improve logs

## 0.7
# - Added nvme device

## 0.6
# - boot folder inside lvm

## 0.5
# - Renamed default log file name to  ubuntu_resource_tool_01.log
# - Added resource VERSION file
# - Added log of the os release running this tool

## 0.4
# - Added version to the os resource

## 0.3
# - Removed warning when importing .iso version different from 16.04

## 0.2
# - Added better error handling and reporting

## 0.1
# - Added -c switch to copy resource iso file to output_folder
# - Prefix the file iwth OS_Resource.....iso
# - added logging functions

#############REMBO.SH####
##!/bin/sh
##this file should be inserted inside the rbo.seed
#
#export SQUASH_MOUNT_POINT=/mnt/squashfs
#export installerDir="/mnt/rbo"
#mount_squash() {
#
#	mkdir /mnt/squashfs
#	
#	mount -o loop -t squashfs /rbo_repos/filesystem.squashfs $SQUASH_MOUNT_POINT
#	
#	mount -t proc /proc $SQUASH_MOUNT_POINT/proc/
#	
#	mount -t sysfs /sys $SQUASH_MOUNT_POINT/sys/
#	
#	mount -o bind /dev $SQUASH_MOUNT_POINT/dev/
#}
#
#create_squash_alias() {
#	local command_name="$1"
#	
#	for path_dir in `echo $PATH|tr ':' ' '`; do
#		if [ -e "$path_dir/$command_name" ]; then
#			echo "$path_dir/$command_name already exists" >> /tmp/pre_instprescript.log 2>&1
#			#TODO check if the command is present in the squash
#			mv $path_dir/$command_name ${path_dir}/${command_name}_b
#		fi
#	done
#	
#	echo "creating alias $command_name" >> /tmp/pre_instprescript.log 2>&1
#	
#	echo "#!/bin/sh" > /bin/$command_name
#	echo "chroot $SQUASH_MOUNT_POINT $command_name \"\\$@\"" >> /bin/$command_name
#	#put all alias under /bin becuase it is writable
#	chmod +x /bin/$command_name
#}
#
#mount_OSD() {
#	mkdir ${installerDir}
#   	echo "trying sd...." >> /tmp/pre_instprescript.log 2>&1
#	for osd_dev in /dev/sd[a-z][0-9]*; do
#		mount $osd_dev ${installerDir}
#		if [ -d "${installerDir}/Deploy" ]; then
#			echo "found Deploy under $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#			return 0
#		else
#			umount ${installerDir}
#		fi
#	done
#	echo "trying dm-...." >> /tmp/pre_instprescript.log 2>&1
#   #Try lvm partitions
#	for osd_dev in /dev/dm-[0-9]; do
#		echo "Try mount $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#		mount $osd_dev ${installerDir}
#		if [ -d "${installerDir}/Deploy" ]; then
#			echo "found Deploy under $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#			return 0
#		else
#			umount ${installerDir}
#		fi
#	done
#	echo "trying nvme...." >> /tmp/pre_instprescript.log 2>&1
#   	#Try lvm partitions
#	for osd_dev in /dev/nvme[0-9]n[1-9]p[1-9]; do
#		echo "Try mount $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#		mount $osd_dev ${installerDir}
#		if [ -d "${installerDir}/Deploy" ]; then
#			echo "found Deploy under $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#			return 0
#		else
#			umount ${installerDir}
#		fi
#	done
#	echo "Error: Deploy dir not found" >> /tmp/pre_instprescript.log 2>&1
#	return 85
#}
#
##Retrive the rboscript file path from the kernel parameter 
##prepend "${installerDir}" that is the mount point
#run_pre_script() {
#	local prescript="$1"
#	for var in $(cat /proc/cmdline); do
#		if [ "${var#${prescript}}" != "${var}" ]; then
#			rboscript="${var#${prescript}=}"	
#			if [ "${rboscript#http}" != "${rboscript}" ]; then
#				echo "downloading script $rboscript" >> /tmp/pre_instprescript.log 2>&1
#				wget_b -O /tmp/${rboscript##*/} --timeout=10 --tries=3 ${rboscript}
#				rboscript=/tmp/${rboscript##*/}
#			else
#				rboscript="${installerDir}/${var#rboscript=}"	
#			fi
#			
#			echo "running script $rboscript" >> /tmp/pre_instprescript.log 2>&1
#			if [ -e "${rboscript}" ]; then
#				chmod +x ${rboscript}
#				. ${rboscript}
#			else
#				echo "Script $rboscript Not found" >> /tmp/pre_instprescript.log 2>&1	
#			fi	
#		fi
#	done
#}
#
#patch_tar_command() {
#	local tar_command="tar"
#	for path_dir in `echo $PATH|tr ':' ' '`; do
#		if [ -e "$path_dir/$tar_command" ]; then
#			echo "$path_dir/$tar_command found" >> /tmp/pre_instprescript.log 2>&1
#			mv $path_dir/$tar_command ${path_dir}/${tar_command}_b
#		fi
#	done
#
#	echo "#!/bin/sh" > /bin/$tar_command
#	echo "mount --rbind /mnt $SQUASH_MOUNT_POINT/mnt" 			>> /bin/$tar_command
#	echo "mount --rbind /tmp $SQUASH_MOUNT_POINT/tmp" 					>> /bin/$tar_command
#	echo "chroot $SQUASH_MOUNT_POINT $tar_command \"\\$@\"" 	>> /bin/$tar_command
#	echo "chroot $SQUASH_MOUNT_POINT umount /mnt" 						>> /bin/$tar_command
#	echo "chroot $SQUASH_MOUNT_POINT umount -R /tmp" 						>> /bin/$tar_command
#	
#	chmod +x /bin/$tar_command
#
#}
#
#add_rbo_commands_to_path(){
#	export PATH=$PATH:/rbo_repos/rbo_commands
#	echo "New path variable is $PATH" >> /tmp/pre_instprescript.log 2>&1
#}
#
#install_udeb(){
#	local udeb_name="$1"
#	for udeb_path in $(find "/rbo_repos/pool" -name "$udeb_name"); do
#		if [ $udeb_path != ${udeb_path%%.udeb} ];then
#			echo "running command: udpkg --force-configure -i $udeb_path " >> /tmp/pre_instprescript.log 2>&1	
#			udpkg --force-configure -i $udeb_path
#		fi
#	done
#}
#
#install_deb(){
#	local deb_name="$1"
#	for deb_path in $(find "/rbo_repos/rbo_debs" -name "$deb_name"); do
#		if [ $deb_path != ${deb_path%%.deb} ];then
#			command="udpkg --force-configure -i $deb_path"
#			echo "running command: $command " >> /tmp/pre_instprescript.log 2>&1
#			$command
#		fi
#	done
#}
#
#add_rbo_library(){
#	for rbolib in $(find /rbo_repos/rbo_libs -name "*.so*"); do
#			path_no_file=${rbolib%/*}
#			file_path_no_rbo_repo=${rbolib##/tmp}
#			#echo "rbolib 					= ${rbolib}" 
#			#echo "path_no_file		 = ${path_no_file}" 
#			#echo "file_path_no_rbo_repo   = ${file_path_no_rbo_repo}" 
#			 
#			if [ ! -e "${file_path_no_rbo_repo}" ]; then
#				echo "create link ln -s ${rbolib} ${file_path_no_rbo_repo}"
#				ln -s ${rbolib} ${file_path_no_rbo_repo}
#			fi
#	done
#}
#
#patch_libraries(){
#	for rbolibpathname in $(find "/rbo_repos/rbo_libs" -name "*so*"); do
#		relative_libpathname=${rbolibpathname#"/rbo_repos/rbo_libs"}
#		libpath=${relative_libpathname%/*}
#		if [ ! -e "$relative_libpathname" ] && [ -e "$libpath" ]; then
#			echo "copy $rbolibpathname to $relative_libpathname" >> /tmp/pre_instprescript.log 2>&1
#			cp "$rbolibpathname" "$relative_libpathname"
#		fi
#	done
#}
#
#register_mouse_driver() {
#	install_udeb "mouse-modules-$(uname -r)-di_*___ARCH__.udeb"
#	for file_name in "$(ls /lib/modules/$(uname -r)/kernel/drivers/input/mouse/*)"; do
#		echo "Intalling mouse module $file_name" >> /tmp/pre_instprescript.log 2>&1	
#		insmod "$file_name"
#	done
#}
#
#setup_device_mapper() {
#	for init_script in /lib/partman/init.d/*kernelmodules*; do
#		echo "running init script ${init_script}"
#		${init_script}
#	done
#
#	for init_script in /lib/partman/init.d/*lvm-devices*; do
#		echo "running init script ${init_script}"
#		${init_script}
#	done
#}
##########MAIN START HERE
#echo "mount squash..." >> /tmp/pre_instprescript.log 2>&1
#
#register_mouse_driver
#
#run_pre_script "rboinitscript"
#
#mount_squash
#
#install_udeb "hdparm-udeb_*___ARCH__.udeb"
#install_udeb "parted-udeb_*___ARCH__.udeb"
#install_deb "libuuid1_*___ARCH__.deb"
#install_deb "libefiboot1_*___ARCH__.deb"
#install_deb "libefivar*___ARCH__.deb"
#install_deb "ubuntu-standard_*___ARCH__.deb"
#install_deb "uuid-runtime_*___ARCH__.deb"
#install_deb "efibootmgr_*___ARCH__.deb"
#
#setup_device_mapper
#
#patch_libraries
#
#echo "creating alias..." >> /tmp/pre_instprescript.log 2>&1
#create_squash_alias "lsblk"
#create_squash_alias "fdisk"
#create_squash_alias "sfdisk"
#create_squash_alias "find"
#create_squash_alias "grep"
#
#patch_tar_command
#
#add_rbo_commands_to_path
#
#add_rbo_library
#
#
#do_deploy_mount="1"
#for var in $(cat /proc/cmdline); do
#	if [ "${var#kfhook}" != "${var}" ]; then
#		do_deploy_mount="0"
#	fi
#done
#
#if [ "$do_deploy_mount" -eq "0" ]; then
#    echo "No mount Deploy we are in deploy" >> /tmp/pre_instprescript.log 2>&1
#else
#    echo "mounting Deploy dir..." >> /tmp/pre_instprescript.log 2>&1
#	mount_OSD
#fi
#
#echo "running pre script..." >> /tmp/pre_instprescript.log 2>&1
#run_pre_script "rboprescript"
#
#export DONTTOUCHDEV2=/dev/ram*
#
#echo "running rboscript..." >> /tmp/pre_instprescript.log 2>&1
#run_pre_script "rboscript"
#
#echo "DONE."
#############REMBO.SH####

#############REMBO.SH_LIVE####
##!/bin/sh
##this file will be launched by rboServer/user-data
#
#export installerDir="/mnt/rbo"
#
#mount_OSD() {
#if [ -d "/cdrom" ]; then
##this could be the virtual installer on a local filesystem
##mounted on /cdrom by casper script
#echo "trying cdrom..." >> /tmp/pre_instprescript.log 2>&1
#ln -s /cdrom ${installerDir}
#if [ -d "${installerDir}/Deploy" ]; then
#echo "found Deploy under /cdrom" >> /tmp/pre_instprescript.log 2>&1
#return 0
#else
#rm ${installerDir}
#fi
#fi
#mkdir ${installerDir}
#echo "trying sd...." >> /tmp/pre_instprescript.log 2>&1
#for osd_dev in /dev/sd[a-z][0-9]*; do
#mount $osd_dev ${installerDir}
#if [ -d "${installerDir}/Deploy" ]; then
#echo "found Deploy under $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#return 0
#else
#umount ${installerDir}
#fi
#done
#echo "trying dm-...." >> /tmp/pre_instprescript.log 2>&1
##Try lvm partitions
#for osd_dev in /dev/dm-[0-9]; do
#echo "Try mount $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#mount $osd_dev ${installerDir}
#if [ -d "${installerDir}/Deploy" ]; then
#echo "found Deploy under $osd_dev">> /tmp/pre_instprescript.log 2>&1
#return 0
#else
#umount ${installerDir}
#fi
#done
#echo "trying nvme...." >> /tmp/pre_instprescript.log 2>&1
##Try lvm partitions
#for osd_dev in /dev/nvme[0-9]n[1-9]p[1-9]; do
#echo "Try mount $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#mount $osd_dev ${installerDir}
#if [ -d "${installerDir}/Deploy" ]; then
#echo "found Deploy under $osd_dev" >> /tmp/pre_instprescript.log 2>&1
#return 0
#else
#umount ${installerDir}
#fi
#done
#echo "Error: Deploy dir not found" >> /tmp/pre_instprescript.log 2>&1
#return 85
#}
#
#install_deb(){
#	local deb_name="$1"
#	for deb_path in $(find "/rbo_debs" -name "$deb_name"); do
#		if [ $deb_path != ${deb_path%%.deb} ]; then
#			command="dpkg -i $deb_path"
#			echo "running command: $command " >> /tmp/pre_instprescript.log 2>&1
#			$command
#		fi
#	done
#}
#
##Retrieve the rboscript file path from the kernel parameter
##prepend "${installerDir}" that is the mount point
#run_rboscript() {
#for var in $(cat /proc/cmdline); do
#	if [ "${var#rboscript=}" != "${var}" ]; then
#		rboscript="${var#rboscript=}"
#		if [ "${rboscript#http}" != "${rboscript}" ]; then
#			echo "downloading script $rboscript" >> /tmp/pre_instprescript.log 2>&1
#			wget -O /tmp/${rboscript##*/} --timeout=10 --tries=3 ${rboscript}
#			rboscript=/tmp/${rboscript##*/}
#		else
#			rboscript="${installerDir}/${var#rboscript=}"
#		fi
#	fi
#done
#
#if [ -e "${rboscript}" ]; then
#echo "running script $rboscript" >> /tmp/pre_instprescript.log 2>&1
#chmod +x ${rboscript}
#. ${rboscript}
#else
#echo "Script $rboscript Not found" >> /tmp/pre_instprescript.log 2>&1
#fi
#}
#
##########MAIN START HERE
#do_deploy_mount="1"
#for var in $(cat /proc/cmdline); do
#	if [ "${var#kfhook}" != "${var}" ]; then
#		do_deploy_mount="0"
#	fi
#done
#
#if [ "$do_deploy_mount" -eq "0" ]; then
#   echo "No mount Deploy we are in deploy" >> /tmp/pre_instprescript.log 2>&1
#else
#   echo "mounting Deploy dir..." >> /tmp/pre_instprescript.log 2>&1
#	mount_OSD
#fi
#
#install_deb "efibootmgr_*_amd64.deb"
#
#export DONTTOUCHDEV2=/dev/ram*
#
#echo "running rboscript..." >> /tmp/pre_instprescript.log 2>&1
#run_rboscript
#
#echo "DONE." >> /tmp/pre_instprescript.log 2>&1
#############REMBO.SH_LIVE####

#https://ubuntu.com/server/docs/install/autoinstall-quickstart -> The crypted password is just “ubuntu”
#############USER_DATA####
##cloud-config
#autoinstall:
#  version: 1
#  identity:
#    hostname: ubuntu-server
#    password: "$6$exDY1mhS4KUYCE/2$zmn9ToZwTKLhCw.b4/b.ZRTIZM30JZ4QrOQ2aOXJ8yk96xpcCof0kxKwuX1kqLG/ygbJ1f8wxED22bTL4F46P0"
#    username: ubuntu
#  early-commands:
#    - chmod 777 /rembo.sh
#    - /rembo.sh
#############USER_DATA####

#############WGET####
##!/bin/sh
#
#FOUND_O_OPT=0
#DESTINATION_PATH=""
#SOURCE_URL=""
#RBO_REPOSITORY_FOLDER="/rbo_repos"
#echo "$@" >> /tmp/wget_rbo.log 
#for param in $@; do
#	if [ "$param" = "-O" ]; then
#		FOUND_O_OPT=1
#	elif [ $FOUND_O_OPT -eq 1 ]; then
#		DESTINATION_PATH=$param
#		FOUND_O_OPT=0
#	fi
#	#SOURCE_URL=$param
#	if [ $(echo $param | sed "s/http:\\/\\/\\([0-9|.]*\\)\\(:[0-9]*\\)\\?//") != $param ]; then
#		SOURCE_URL=$param
#	fi
#done
#
#FILE_PATH=$(echo $SOURCE_URL | sed "s/http:\\/\\/\\([0-9|.]*\\)\\(:[0-9]*\\)\\?//")
#
#REPOS_FILE_PATH="${RBO_REPOSITORY_FOLDER}/${FILE_PATH}"
#
####Get the file name
#
#if [ -e "${REPOS_FILE_PATH}" ]; then
#	if [ "$DESTINATION_PATH" == "-" ]; then
#		cat "${REPOS_FILE_PATH}"
#	elif [ "$DESTINATION_PATH" == "" ]; then
#		cp "${REPOS_FILE_PATH}" "." 
#	else
#		cp "${REPOS_FILE_PATH}" "${DESTINATION_PATH}"
#	fi
#else
#	wget_b $@
#fi
#
##if [ "$DESTINATION_PATH" != "" ]; then
##	#FILE_NAME=${DESTINATION_PATH##*/}
##	FILE_NAME=${SOURCE_URL##*/}
##	echo "$FILE_NAME" >> /tmp/wget_rbo.log 
##	echo "$DESTINATION_PATH" >> /tmp/wget_rbo.log
##	if [ "${FILE_NAME%*udeb}" != "${FILE_NAME}" ]; then
##		#Handle *.udeb files
##		if [ -e "${RBO_REPOSITORY_FOLDER}/${FILE_NAME}" ]; then
##			#File Found in repos
##			#echo "${RBO_REPOSITORY_FOLDER}/${FILE_NAME}"
##			cp ${RBO_REPOSITORY_FOLDER}/${FILE_NAME} $DESTINATION_PATH
##		else
##			echo 'ERROR 404'
##			exit 8
##		fi
##   else
## 		#Handle NO *.udeb files
##		SOURCE_PATH_URL=$(echo $SOURCE_URL | sed "s/http:\\/\\/\\([0-9|.]*\\)\\(:[0-9]*\\)\\?//")
##		if [ -e ${RBO_REPOSITORY_FOLDER}${SOURCE_PATH_URL} ]; then
##			if [ "${DESTINATION_PATH}" == "-" ]; then
##				cat ${RBO_REPOSITORY_FOLDER}${SOURCE_PATH_URL}
##			else
##				cp ${RBO_REPOSITORY_FOLDER}${SOURCE_PATH_URL} ${DESTINATION_PATH}
##			fi
##		else
##			if [ "${FILE_NAME%*preseed}" != "${FILE_NAME}" ]; then
##				wget_b $@
##			fi 
##		fi
##	fi 
##fi
#############WGET####

DO_NOT_EXTRACT_LIBRARY=""
LOG_FILE="ubuntu_resource_tool_04.log"
TAG_WGET="#############WGET####"
INITRD_IMG="initrd.img"
INITRD="initrd"
WORKING_DIR="wd"
RBO_INITRD_DIR="rbo_initrd"
ISO_MOUNT_FOLDER="/mnt/rbo_iso"
RBO_REPOSITORY_FOLDER="rbo_repos"
ISO_FILE=""
RBO_PRESEED_FILE_NAME="rbo.preseed"
CURRENT_FILE_PATH="$0"
BASE_DIR="."
COMMANDS_DIR=${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/rbo_commands
LIBS_DIR=${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/rbo_libs
EXTRACT_DEB_DIR="/tmp/rbo_deb"
COPY_TO_FOLDER=""

###utils###
logging_general(){
    trace_line="$1"
    log_it="$2"
    echo $trace_line
    if [ "$log_it" != "" ]; then
        echo $trace_line >> ${LOG_FILE} 2>&1	
    fi

}

log_to_stdout_and_trace(){
	trace_line="$1"
	logging_general "$trace_line" 1
}

log_to_stdout(){
    trace_line="$1"
	logging_general "$trace_line"
}

remove_file_if_exists(){
	FTR=$1
	if [ -f "${FTR}" ]; then
		log_to_stdout_and_trace "Removing ${FTR}" 
		rm -f "${FTR}"
	fi
}

test_file_exists_and_exit(){
	FE=$1
	if [ ! -f "${FE}" ]; then
		log_to_stdout_and_trace "error: file ${FE} does not exist"
		log_to_stdout_and_trace "Be sure that the provided .iso is Ubuntu Legacy Server (up to 2004) or Ubuntu Server Live iso (from 2204 on)"
		exit 127
	elif [ ! -s "${FE}" ]; then
		log_to_stdout_and_trace "error: file ${FE} exists but has size 0"
		log_to_stdout_and_trace "Be sure that the provided .iso is Ubuntu Legacy Server (up to 2004) or Ubuntu Server Live iso (from 2204 on)"
		exit 128
	fi
}
###utils###

###backup initrd.gz
backup_initrdgz(){
	test_file_exists_and_exit "${ISO_MOUNT_FOLDER}/${NET_BOOT_ISO_PATH}/${INITRDGZ}"
	log_to_stdout_and_trace "Copy ${ISO_MOUNT_FOLDER}/${NET_BOOT_ISO_PATH}/${INITRDGZ} to $PWD"
	#cp ${INITRDGZ} ${INITRDGZ}.bckp
	cp ${ISO_MOUNT_FOLDER}/${NET_BOOT_ISO_PATH}/${INITRDGZ} "$PWD"
}

###create_working_dir
setup_working_dir(){
	local working_dir="$1"
	if [ -d "$working_dir" ]; then
		log_to_stdout_and_trace "$working_dir already exists"
	else
		mkdir -p "${working_dir}"
	fi
	log_to_stdout_and_trace "Changing current dir to ${working_dir}"
	cd "${working_dir}"
}

#### unzip initrd.gz
unzip_initrd(){

	remove_file_if_exists  ${INITRD}

	gunzip ${INITRDGZ}

	local res=$?

	if [ $res -ne 0 ]; then
		log_to_stdout_and_trace "Error $res unzipping $INITRDGZ"
    fi

}

#### cpio initrd
cpio_initrd(){
	log_to_stdout_and_trace "cpio ../${INITRD}"
	cpio -id < ../${INITRD}
	local res=$?
	if [ $res -ne 0 ]; then
		log_to_stdout_and_trace "Error $res cpio ${INITRD}"
    fi
	remove_file_if_exists ../${INITRD}
	cd ..
}

###########EXTARCT LIBRARY FROM DEBS INSIDE ISO FILE ###########

extract_dep(){
	local debname="$1"
	local tmpdir="$EXTRACT_DEB_DIR"
	if [ -e "$EXTRACT_DEB_DIR" ]; then
		rm -fr "$EXTRACT_DEB_DIR"
	fi

	dpkg -x "$debname" "$EXTRACT_DEB_DIR"
}

copy_deb_library(){
	local libfullpath=$1
	local libname=$2
	local libpath=${libfullpath%/*}
	log_to_stdout_and_trace "libfullpath is $libfullpath" 
	log_to_stdout_and_trace "libpath is $libpath"
	log_to_stdout_and_trace "libname is $libname"

	if [ "$libname" = "$libfullpath" ]; then
		log_to_stdout_and_trace "copying '$libname' to '$LIBS_DIR'"
		cp "$libname" "$LIBS_DIR"
	else
		log_to_stdout_and_trace "copying '$LIBS_DIR/$libfullpath' to '$LIBS_DIR/$libpath'"
		if [ ! -e "$LIBS_DIR/$libpath" ]; then
			mkdir -p "$LIBS_DIR/$libpath"
		fi
		cp "$EXTRACT_DEB_DIR/$libfullpath" "$LIBS_DIR/$libpath"
	fi
}

check_in_dep(){
	local deb_path="$1"
	local lib_name="$2"
	dpkg -c "$deb_path"| while read a b c d e f 
	do
		#echo "Path is : ${f%${lib_name}*} (${lib_name})"
		if [ "$f" != "${f%${lib_name}*}" ]; then
			#f is in the form of either fullpathname -> filename or fullpathname
			log_to_stdout_and_trace "Path is $f"
			log_to_stdout_and_trace "Path is : ${f%${lib_name}*} (${lib_name})"	
			libfullpath=${f% ->*}
			libname=${f#* -> }
			extract_dep "$deb_path"
			copy_deb_library "$libfullpath" "$libname"
			RET=0
			break
		fi
	done
	RET=1 
}


extract_library_from_deb(){
	local libname="$1"
	for deb_path in $(find "$ISO_MOUNT_FOLDER/pool/main" -name "*.deb"); do
			printf "$deb_path\r"
			check_in_dep "$deb_path" "$libname"
			if [ "$RET" = "0" ]; then
				log_to_stdout_and_trace "RET is ok $RET"	
				break
			fi
	done
	log_to_stdout_and_trace "RET is $RET"
	echo ""
}

copy_deb(){
	local deb_package="$1"
	log_to_stdout_and_trace "Searching deb package: '$deb_package'"
	packages_path=$(find $ISO_MOUNT_FOLDER/pool/main -name "$deb_package")
	if [ ! -z "$packages_path" ]; then
		mkdir -p "${repo_folder}/rbo_debs"
		num_found=$(echo $packages_path | awk '{print split($0, array, " ")}')
		for ii in $(seq $num_found); do
			pkg_path=$(echo $packages_path | awk -F ' ' -v awk_ii=$ii '{print $awk_ii}')
			pkg_name=$(echo $pkg_path | awk -F '/' '{print $NF}')
			cp "$pkg_path" "${repo_folder}/rbo_debs/${pkg_name}"
			log_to_stdout_and_trace "-->  $pkg_name ...copied"
		done
	else
		log_to_stdout_and_trace "Package '$deb_package' not found"
	fi
}

###########
copy_udebs(){
	log_to_stdout_and_trace "Copying udebs...."
	find $ISO_MOUNT_FOLDER/pool -name *.udeb | while read udeb; do
		abs_path=${udeb%/*}
		#echo "abs_path is ${abs_path}"
		rel_path=${abs_path#"$ISO_MOUNT_FOLDER"}
		#echo "rel_path is ${rel_path}"
		#echo "making ${repo_folder}${rel_path}"
		mkdir -p "${repo_folder}${rel_path}"
		#echo "$udeb ${repo_folder}${rel_path}"
		cp "$udeb" "${repo_folder}${rel_path}"
	done

}


copy_utility_files() {
	log_to_stdout_and_trace "Copying Utility files...."

	if [ ! -d $ISO_MOUNT_FOLDER/dists ]; then
		log_to_stdout_and_trace "'dists' folder not found"
	else
		cp -r $ISO_MOUNT_FOLDER/dists "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}"
	fi	
	cp $ISO_MOUNT_FOLDER/README.diskdefines "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}"
}

copy_squashfs() {
	 log_to_stdout_and_trace "Copying squash file...."

	if [ ! -e $ISO_MOUNT_FOLDER/install/filesystem.squashfs ]; then
		 log_to_stdout_and_trace "squashfs file '$ISO_MOUNT_FOLDER/install/filesystem.squashfs' not found"
	else
		cp $ISO_MOUNT_FOLDER/install/filesystem.squashfs "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/filesystem.squashfs"
	fi
}

copy_debs_to_squashfs() {
	echo "Copying .deb files to squashfs repository folder"
	local target_folder=$1
	mkdir $target_folder/rbo_debs
	cp $ISO_MOUNT_FOLDER/pool/main/e/efibootmgr/efibootmgr_*_amd64.deb $target_folder/rbo_debs
}

patch_squashfs() {
	log_to_stdout_and_trace "Patching squash file...."
	if [ ! -e $ISO_MOUNT_FOLDER/casper/ubuntu-server-minimal.squashfs ]; then
		log_to_stdout_and_trace "squashfs file '$ISO_MOUNT_FOLDER/casper/ubuntu-server-minimal.squashfs' not found"
		exit 3
	else
		mkdir -p casperISO/casper
		rsync -r --exclude="ubuntu-server-minimal.squashfs" --exclude="ubuntu-server-minimal.ubuntu-server.installer.generic-hwe.squashfs" $ISO_MOUNT_FOLDER/casper/*.squashfs ./casperISO/casper
		mkdir casperISO/.disk
		cp $ISO_MOUNT_FOLDER/.disk/info ./casperISO/.disk
		unsquashfs -d "squashfs-wd" $ISO_MOUNT_FOLDER/casper/ubuntu-server-minimal.squashfs
		extract_rembo_sh_live "${CURRENT_FILE_PATH}"
		write_version_file "squashfs-wd"
		copy_debs_to_squashfs "squashfs-wd"
		echo blacklist floppy> "squashfs-wd/etc/modprobe.d/blacklist-floppy.conf"
		mksquashfs "squashfs-wd" "./casperISO/casper/ubuntu-server-minimal.squashfs"
		extract_data_files  "${CURRENT_FILE_PATH}"
		log_to_stdout_and_trace "extract_rembo_sh_live and extract_data_files done."
		rm -rf "squashfs-wd"
		make_iso "Installer" "casperISO"
		mv $INSTALLER_ISO ..
		cd ..
	fi
}

#Add preseed file to initrd
add_preseed_file() {
	echo "# Suggest LVM by default." 																> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	partman-auto/init_automatically_partition	string some_device_lvm" 			  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	partman-auto/init_automatically_partition	seen false" 						  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# Install the Ubuntu Server seed." 													  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "tasksel	tasksel/force-tasks	string server"											  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# Only install basic language packs. Let tasksel ask about tasks." 					  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	pkgsel/language-pack-patterns	string" 										  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# No language support packages." 														  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	pkgsel/install-language-support	boolean false" 									  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# Only ask the UTC question if there are other operating systems installed." 			  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	clock-setup/utc-auto	boolean true" 											  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# Verbose output and no boot splash screen."											  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	debian-installer/quiet	boolean false" 											  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	debian-installer/splash	boolean false" 											  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# Install the debconf oem-config frontend (if in OEM mode)." 							  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	oem-config-udeb/frontend	string debconf" 									  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# Wait for two seconds in grub"														  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i	grub-installer/timeout	string 2" 												  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "#d-i live-installer/net-image string http://__IP_ADDRESS__/install/filesystem.squashfs"	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i passwd/make-user boolean false" 					  									>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i passwd/root-login boolean false" 					  									>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# To create a normal user account." 					  									>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i passwd/user-fullname string Ubuntu User" 											  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i passwd/username string ubuntu" 					  									>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "# Normal user's password, either in clear text" 											>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i passwd/user-password password insecure" 											  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i passwd/user-password-again password insecure" 									  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i user-setup/allow-password-weak boolean true" 										  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i user-setup/encrypt-home boolean false" 					 						 	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i clock-setup/utc boolean false" 					 						 			>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i time/zone string US/Eastern" 					 						 				>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i clock-setup/ntp boolean false" 					 						 			>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "" 																					  	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "d-i partman/early_command string \\" 														>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "chmod 777 /rbo_repos/rembo.sh;\\" 														>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "/rbo_repos/rembo.sh;" 																	>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
#	echo "sleep 9999;" 																				>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "" 																						>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "#d-i preseed/early_command string \\"														>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}
	echo "#echo early_preseed > /tmp/pre.txt;" 													>> ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/${RBO_PRESEED_FILE_NAME}

}

extract_rembo_sh() {
	local current_file_path="$1"
	log_to_stdout_and_trace "extract_rembo_sh"	
	FOUND_REMBO_SH="0"
	cat "${current_file_path}" | while read LINE 
	do
		if [ "$FOUND_REMBO_SH" = "0" ] && [ "$LINE" = "$TAG" ]; then
			FOUND_REMBO_SH="1"
		elif [ "$FOUND_REMBO_SH" = "1" ] && [ "$LINE" = "$TAG" ]; then
			break
		elif [ "$FOUND_REMBO_SH" = "1" ] && [ "$LINE" != "$TAG" ]; then
			rembo_line=${LINE###}
			rembo_line=$(echo $rembo_line | sed -r "s/(.*)__ARCH__(.*)/\1${RBO_ARCH}\2/g")
			echo "${rembo_line}">> "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/rembo.sh"
		fi
	done
}

extract_rembo_sh_live() {
	local current_file_path="$1"
	log_to_stdout_and_trace "extract_rembo_sh_live"	
	FOUND_REMBO_SH="0"
	cat "${current_file_path}" | while read LINE 
	do
		if [ "$FOUND_REMBO_SH" = "0" ] && [ "$LINE" = "$TAG" ]; then
			FOUND_REMBO_SH="1"
		elif [ "$FOUND_REMBO_SH" = "1" ] && [ "$LINE" = "$TAG" ]; then
			break
		elif [ "$FOUND_REMBO_SH" = "1" ] && [ "$LINE" != "$TAG" ]; then
			rembo_line=${LINE###}
			echo "${rembo_line}">> "squashfs-wd/rembo.sh"
		fi
	done
}

extract_data_files() {
	local current_file_path="$1"
	log_to_stdout_and_trace "extract_data_files"	
	FOUND_USER_DATA="0"
	UD_TAG="#############USER_DATA####"
	mkdir "./casperISO/rboServer"
	cat "${current_file_path}" | while read LINE 
	do
		if [ "$FOUND_USER_DATA" = "0" ] && [ "$LINE" = "$UD_TAG" ]; then
			FOUND_USER_DATA="1"
		elif [ "$FOUND_USER_DATA" = "1" ] && [ "$LINE" = "$UD_TAG" ]; then
			break
		elif [ "$FOUND_USER_DATA" = "1" ] && [ "$LINE" != "$UD_TAG" ]; then
			rembo_line=${LINE###}
			echo "${rembo_line}">> "./casperISO/rboServer/user-data"
		fi
	done
	touch "./casperISO/rboServer/meta-data"
}

replace_wget() {
	find . -name wget | while read wget_path
	do
		if [ "${wget_path#*${RBO_REPOSITORY_FOLDER}}" != "${wget_path}" ]; then
			continue
		fi
		mv "$wget_path" "${wget_path}_b"
		log_to_stdout_and_trace "Replacing ${wget_path} with ${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/wget"
		cp "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/wget" "$wget_path"
	done
}

replace_udpkg() {

	mv "${RBO_INITRD_DIR}/usr/bin/udpkg" "${RBO_INITRD_DIR}/usr/bin/udpkg_b"

	#create the udpkg 
	echo "#!/bin/sh" > "${RBO_INITRD_DIR}/usr/bin/udpkg"
	echo "echo \$@ >> /tmp/pre_instprescript.log 2>&1" >> "${RBO_INITRD_DIR}/usr/bin/udpkg"
	echo "udpkg_b \$@">> "${RBO_INITRD_DIR}/usr/bin/udpkg"

	chmod 777 "${RBO_INITRD_DIR}/usr/bin/udpkg"
}


extract_rembo_wget() {
	local current_file_path="$1"
	log_to_stdout_and_trace "extract_rembo_wget"
	FOUND_REMBO_SH="0"
	cat "${current_file_path}" | while read LINE 
	do
		if [ "$FOUND_REMBO_SH" = "0" ] && [ "$LINE" = "$TAG_WGET" ]; then
			FOUND_REMBO_SH="1"
		elif [ "$FOUND_REMBO_SH" = "1" ] && [ "$LINE" = "$TAG_WGET" ]; then
			break
		elif [ "$FOUND_REMBO_SH" = "1" ] && [ "$LINE" != "$TAG_WGET" ]; then
			echo "${LINE###}" >> "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/wget"
		fi
	done
	chmod +x "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}/wget"
	replace_wget

	
}

copy_command(){
	local command="$1"

	for path_dir in `echo $PATH|tr ':' ' '`; do
		if [ -e "$path_dir/$command" ]; then
			log_to_stdout_and_trace "$path_dir/$command found copying to ${COMMANDS_DIR}/$command" 
			cp "$path_dir/$command" "${COMMANDS_DIR}/$command"
			return	
		fi
	done
	log_to_stdout_and_trace "Command '$command' not found"
}

copy_commands(){
	log_to_stdout_and_trace "Copy commands...."
	if [ ! -e "${COMMANDS_DIR}" ]; then
		mkdir "${COMMANDS_DIR}"
	fi
	copy_command "hdparm"
}

copy_library(){
	local library="$1"
	if [ -e "/lib/x86_64-linux-gnu/$library" ]; then
		log_to_stdout_and_trace "/lib/x86_64-linux-gnu/$library found copying to ${LIBS_DIR}/$library" 
		cp "/lib/x86_64-linux-gnu/$library" "${LIBS_DIR}/$library"
	else
		log_to_stdout_and_trace "Library '/lib/x86_64-linux-gnu/$library' not found"
	fi
}

copy_libraries(){
	if [ ! -e "${LIBS_DIR}" ]; then
		mkdir ${LIBS_DIR}
	fi
	#Needed by RelayDownloader64.bin
	copy_library "libnsl.so.1"
}

write_version_file(){
	local target_folder=$1
	log_to_stdout_and_trace "Writing version file ${VERSION} (v${EXTERNAL_VERSION})"
	echo ${VERSION} > "${target_folder}/VERSION"
	if [ $ISLIVEISO -eq "0" ]; then 
		iso_info=$(cat "${ISO_MOUNT_FOLDER}/README.diskdefines" | grep -e DISKNAME)
	else
		iso_info=$(cat "${ISO_MOUNT_FOLDER}/.disk/info")
	fi
	echo ${iso_info} >> "${target_folder}/VERSION"
	OS_RELEASE=$(cat /etc/issue)
	echo "OS release bundle machine ${OS_RELEASE}" >> "${target_folder}/VERSION"
	echo "external_version=${EXTERNAL_VERSION}" >> "${target_folder}/VERSION"
}

###patch the initrd
patch_initrd(){
	
	local repo_folder="${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}"
	if [ ! -d "${repo_folder}" ]; then
		mkdir "${repo_folder}"
	fi

	write_version_file "${RBO_INITRD_DIR}/${RBO_REPOSITORY_FOLDER}"

	copy_utility_files
	
	copy_udebs
	
	copy_squashfs

	#copy utility commands from machine
	#copy_commands

	#copy libraries from machine
	if [ -z "$DO_NOT_EXTRACT_LIBRARY" ]; then
		extract_library_from_deb "libnsl.so.1"
	fi

	#copy deb packages
	copy_deb "libuuid1_*_${RBO_ARCH}.deb"
	copy_deb "libefiboot1_*_${RBO_ARCH}.deb"
	copy_deb "libefivar*_${RBO_ARCH}.deb"
	copy_deb "ubuntu-standard_*_${RBO_ARCH}.deb"
	copy_deb "uuid-runtime_*_${RBO_ARCH}.deb"
	copy_deb "efibootmgr_*_${RBO_ARCH}.deb"

	#create preseed file
	add_preseed_file

	extract_rembo_sh "${CURRENT_FILE_PATH}"

	#replace wget
	extract_rembo_wget "${CURRENT_FILE_PATH}"

	#Only for debug
	#replace_udpkg
}

### recreate_initrdgz
recreate_initrdgz(){
	local current_dir="$PWD"	
	cd "${RBO_INITRD_DIR}"
	log_to_stdout_and_trace "Current dir is $PWD"
	log_to_stdout_and_trace "Generating ${INITRD} ..."
	find . | cpio --create --format='newc' > ../${INITRD}
	local res=$?
	if [ $res -ne 0 ]; then
         log_to_stdout_and_trace "Error creating ${INITRD}"
    fi
	
	log_to_stdout_and_trace "Generated ${INITRD} done"
	cd ..
	
	remove_file_if_exists ${INITRDGZ}
		
	log_to_stdout_and_trace "Generating ${INITRDGZ} ..."
	gzip ${INITRD} >> ${LOG_FILE} 2>&1	
	log_to_stdout_and_trace "Generated ${INITRDGZ} done"

	local res=$?
	if [ $res -ne 0 ]; then
         log_to_stdout_and_trace "Error creating ${INITRDGZ}"
    fi
	mv ${INITRDGZ} ../${INITRDGZ}
    
    cd ..
    
    log_to_stdout_and_trace "Current dir is $PWD"
}

unpack_initrd(){
	local current_dir=$PWD
	unzip_initrd
	setup_working_dir ${RBO_INITRD_DIR}
	cpio_initrd
	cd "${current_dir}"

}

check_iso_file(){
	RETVAL=0
	log_to_stdout_and_trace "checking iso file $ISO_FILE ..."
	if [ ! -e $ISO_FILE ]; then
		RETVAL=1 
		log_to_stdout_and_trace "Iso file path '$ISO_FILE' not valid"
	fi
		
}

mount_iso_file() {

	if [ ! -d $ISO_MOUNT_FOLDER ]; then
		mkdir -p $ISO_MOUNT_FOLDER
	fi
	log_to_stdout_and_trace "mounting iso file $ISO_FILE to $ISO_MOUNT_FOLDER"
	if [ ! -e "$ISO_FILE" ]; then
		log_to_stdout_and_trace "Error iso file $ISO_FILE not found"
		exit 23
	fi
	mount -o loop,ro $ISO_FILE $ISO_MOUNT_FOLDER 
	error_code=$? 
	if [ "$error_code" -ne "0" ]; then
		 log_to_stdout_and_trace "Error '$error_code' mounting iso $ISO_FILE on $ISO_MOUNT_FOLDER "	
		 if [ -e "$ISO_FILE" ]; then
		 	log_to_stdout_and_trace "$ISO_FILE exits probably already mounted going on..."	
		 else
			exit 24
		 fi
		 
	fi
}

rename_rbo_initrd() {

    log_to_stdout_and_trace "current dir is $PWD"
	mv ${RBO_INITRD_DIR} "initrd"
}

clean_up() {
	log_to_stdout_and_trace "current dir is $PWD"
	rm -fr ${WORKING_DIR}
}

umount_iso_file(){
	log_to_stdout_and_trace "umount iso folder  $ISO_MOUNT_FOLDER" 
	if [ -d $ISO_MOUNT_FOLDER ]; then
		umount ${ISO_MOUNT_FOLDER}
		rmdir $ISO_MOUNT_FOLDER
	fi
}

generate_initrd_gz(){

	local iso_file="$1"

	setup_working_dir "${BASE_DIR}"

	setup_working_dir "${WORKING_DIR}"

	backup_initrdgz

	unpack_initrd

	patch_initrd
	
	recreate_initrdgz

	clean_up

}

generate_squashfs() {
	local iso_file="$1"
	setup_working_dir "${BASE_DIR}"
	setup_working_dir "${WORKING_DIR}"
	patch_squashfs
	clean_up
}

addGrub2Files() {
	#this is only for live resource
	log_to_stdout_and_trace "adding grub2 boot files"
	dpkg-deb --fsys-tarfile $ISO_MOUNT_FOLDER/pool/main/s/shim-signed/shim-signed*.deb | tar x ./usr/lib/shim/shimx64.efi -O > "isofolder/shimx64.efi"
	test_file_exists_and_exit "isofolder/shimx64.efi"
	dpkg-deb --fsys-tarfile $ISO_MOUNT_FOLDER/pool/main/g/grub2-signed/grub-efi-amd64-signed*.deb | tar x ./usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed -O > "isofolder/grubx64.efi"
	test_file_exists_and_exit "isofolder/grubx64.efi"
}

prepare_iso_folder(){
	log_to_stdout_and_trace "prepare_iso_folder" 
	log_to_stdout_and_trace "mkdir $PWD/isofolder"
	mkdir "isofolder"
	test_file_exists_and_exit "${ISO_MOUNT_FOLDER}/${NET_BOOT_ISO_PATH}/${KERNEL}"
	cp "${ISO_MOUNT_FOLDER}/${NET_BOOT_ISO_PATH}/${KERNEL}" "isofolder/vmlinuz"
	if [ $ISLIVEISO -eq "0" ]; then
		mv "${INITRDGZ}" "isofolder/${INITRD_IMG}"
		cp "${ISO_MOUNT_FOLDER}/README.diskdefines" "isofolder/"
	else
		cp "${INITRDGZ}" "isofolder/${INITRD_IMG}"
		cp $INSTALLER_ISO "isofolder/"
		cp "${ISO_MOUNT_FOLDER}/.disk/info" "isofolder/"
		addGrub2Files
	fi
	echo "internal_version=${VERSION}" > "isofolder/version.txt"
	echo "external_version=${EXTERNAL_VERSION}" >> "isofolder/version.txt"
}

cleanup_iso_folder(){
	log_to_stdout_and_trace "cleanup_iso_folder"

	log_to_stdout_and_trace "remove $PWD/isofolder" 
	if [ -d "isofolder" ]; then
		rm -fr "isofolder"
	fi
	
	if [ -d "$EXTRACT_DEB_DIR" ]; then
		log_to_stdout_and_trace "remove $EXTRACT_DEB_DIR" 
		rm -fr "$EXTRACT_DEB_DIR"
	fi
	
	if [ -f "$INSTALLER_ISO" ]; then
		log_to_stdout_and_trace "remove $INSTALLER_ISO" 
		rm -fr "$INSTALLER_ISO"
	fi
}

get_iso_file_name(){
	local targetItem="$1"
	if [ $ISLIVEISO -eq "0" ]; then
		fname=$(cat ${ISO_MOUNT_FOLDER}/README.diskdefines | grep -e '^#define DISKNAME' | awk '{print $3"_"$4 }')
		arch=$(cat ${ISO_MOUNT_FOLDER}/README.diskdefines  | grep -e '^#define ARCH ' | awk '{print $3 }')
	else
		fname=$(cat ${ISO_MOUNT_FOLDER}/.disk/info | awk '{print $1"_"$2}')
		arch=$RBO_ARCH
	fi
	if [ $targetItem = "Resource" ]; then
		ISO_NAME="OS_${targetItem}_${fname}_${arch}.iso"
	elif [ $targetItem = "Installer" ]; then
		ISO_NAME="os_installer_live.iso"
		INSTALLER_VERSION="${fname}_${arch}"
	fi
}

make_iso(){
	local targetItem="$1"	#this can be Resource or Installer
	local sourceFolder="$2"
	log_to_stdout_and_trace "make_iso $targetItem"
	get_iso_file_name $targetItem
	if [ $ISLIVEISO -eq "0" ]; then
		if [ -e "$ISO_NAME" ]; then
			rm "$ISO_NAME"
		fi
	elif [ $targetItem = "Installer" ]; then
		echo $INSTALLER_VERSION> $sourceFolder/version.txt
	fi
	#Check if the genisoimage package is installed. This package can be absent on a Ubuntu-Server machine
	LC_ALL=C dpkg -s genisoimage | grep -q -e "ok installed";
	if [ $? -ne 0 ]; then
		log_to_stdout_and_trace "Error: package genisoimage is missing. Install it and run the script again"
		exit 101
	fi
	
	genisoimage -lJR -o "$ISO_NAME" "$sourceFolder"

	if [ $targetItem = "Resource" ]; then
		copy_to_folder "$ISO_NAME"
	elif [ $targetItem = "Installer" ]; then
		INSTALLER_ISO=$ISO_NAME
	fi
}

validate_iso_file(){
	RET=1
	local iso_mount=$1
	log_to_stdout_and_trace "Validating iso file..."
	if [ -e "$iso_mount/README.diskdefines" ]; then
		ISLIVEISO=0
		log_to_stdout_and_trace "Ubuntu Legacy iso detected"
		grep_info=$(cat ${iso_mount}/README.diskdefines |grep -e DISKNAME|grep -e Ubuntu-Server  |grep -E '.*[1,2][0-9].[0-9]{1,2}.*' | awk '{print $4}') 
	elif [ -e "$iso_mount/.disk/info" ]; then
		ISLIVEISO=1
		log_to_stdout_and_trace "Ubuntu Live iso detected"
		grep_info=$(cat ${iso_mount}/.disk/info |grep -e Ubuntu-Server  |grep -E '.*[1,2][0-9].[0-9]{1,2}.*' | awk '{print $2}')
		echo "${grep_info}" | grep -q -e "16.04" -e "17.04" -e "18.04" -e "19.04" -e "20.04"
		if [ $? -eq 0 ]; then
			log_to_stdout_and_trace "Ubuntu Legacy Server iso is needed for version up to 2004"
			exit 76
		fi
	else
		log_to_stdout_and_trace "Valid Ubuntu Server iso not found, please provide an Ubuntu Legacy Server (up to 2004) or Ubuntu Live iso (from 2204 on)"
		exit 77
	fi
	
	if [ "${grep_info}" = "" ]; then
		log_to_stdout_and_trace "Ubuntu Server iso not found, please provide an Ubuntu Legacy Server (up to 2004) or Ubuntu Live Server iso (from 2204 on)"
		exit 78
	fi

	RET=0
	log_to_stdout_and_trace "Ubuntu Version $grep_info"

	#check if the version is supported
	echo "${grep_info}" | grep -q -e "16.04" -e "17.04" -e "18.04" -e "19.04" -e "20.04" -e "22.04" -e "24.04"
	if [ $? -ne 0 ]; then
		log_to_stdout_and_trace "version $grep_info not supported, continuing anyway.. "
	fi
}

get_arch(){
	local iso_mount=$1
	log_to_stdout_and_trace "get arch for $iso_mount..."
	RET=""
	grep_arch=$(cat $iso_mount/README.diskdefines |grep -e "ARCH " | sed -r 's/#define(\s+)ARCH(\s+)(.*)/\3/')

	if [ "${grep_arch}" = "i386" ]; then
		log_to_stdout_and_trace "32bit iso "
		RBO_ARCH="i386"
		RET=$grep_arch
	fi
	if [ "${grep_arch}" = "amd64" ]; then
		log_to_stdout_and_trace "64bit iso "
		RBO_ARCH="amd64"
		RET=$grep_arch
	fi
}

setup_variables(){
	if [ $ISLIVEISO -eq "0" ]; then
		TAG="#############REMBO.SH####"
		KERNEL="linux"
		INITRDGZ="initrd.gz"
		local rbo_arch=""
		get_arch ${ISO_MOUNT_FOLDER}
		rbo_arch=$RET
		if [ "$rbo_arch" = "i386" ]; then
			NET_BOOT_ISO_PATH="install/netboot/ubuntu-installer/i386"
		elif [ "$rbo_arch" = "amd64" ]; then
			NET_BOOT_ISO_PATH="install/netboot/ubuntu-installer/amd64"
		else
			log_to_stdout_and_trace "ARCH $rbo_arch unknown"
			exit 5
		fi
	else
		TAG="#############REMBO.SH_LIVE####"
		KERNEL="vmlinuz"
		NET_BOOT_ISO_PATH="casper"
		INITRDGZ="${ISO_MOUNT_FOLDER}/${NET_BOOT_ISO_PATH}/$INITRD"
		RBO_ARCH="amd64"
	fi

	log_to_stdout_and_trace "NET_BOOT_ISO_PATH is $NET_BOOT_ISO_PATH"
}

download_iso_file(){
	dwnld_url=$1
	
	ISO_FILE="$BASE_DIR/ubuntu.iso"
	if [ -e "$ISO_FILE" ]; then
		log_to_stdout_and_trace "iso file already exists "
	else 
	
		log_to_stdout_and_trace "downloading iso file wget -O ${ISO_FILE} $dwnld_url...."
		wget -O "${ISO_FILE}" $dwnld_url
		RET=$?
		if [ $RET -ne 0 ]; then
			log_to_stdout_and_trace "Error downloading iso file from url $dwnld_url" 
			exit $RET
		fi
	fi
}

init_base_dir(){

	if [ -d "${BASE_DIR}/${WORKING_DIR}" ]; then
		log_to_stdout "Working directory already exists, cleanup ${BASE_DIR}/${WORKING_DIR}"
		rm -fr "${BASE_DIR}/${WORKING_DIR}"
	fi

	if [ ! -d $BASE_DIR ]; then
		mkdir -p "$BASE_DIR"
	fi
}

copy_to_folder(){
	source_iso_file="$1"

	if [ "$COPY_TO_FOLDER" != "" ]; then
		log_to_stdout_and_trace "copying file $source_iso_file to $COPY_TO_FOLDER"
		if [ ! -d "$COPY_TO_FOLDER" ]; then
			mkdir -p "$COPY_TO_FOLDER"
		fi
		if [ -d "$COPY_TO_FOLDER" ]; then
			mv -f "$source_iso_file" "$COPY_TO_FOLDER"
			if [ $? -ne 0 ]; then
				log_to_stdout_and_trace "Copy to folder received error $?"
			else
				log_to_stdout_and_trace "Resource successfully copied to folder ${COPY_TO_FOLDER}"
			fi
		else
			log_to_stdout_and_trace "Folder $COPY_TO_FOLDER do not exists"
		fi
	fi
}

usage(){
	log_to_stdout "Usage: ubuntu_resource_tool_04.sh [-w working_dir] [-c copy_to_folder] [-l log_file_path] {path_to_server_iso}"
	exit 100
}

prepare_initialize(){

	if [ "${CURRENT_FILE_PATH#./}" != "${CURRENT_FILE_PATH}" ]; then
		#if relative path append current path
		CURRENT_FILE_PATH="${PWD}/$0"    
	fi

	if [ ! -e "${CURRENT_FILE_PATH}" ]; then
		log_to_stdout_and_trace "Cannot detect current filepath ${CURRENT_FILE_PATH}\n"
		exit 99
	fi
	log_to_stdout "CURRENT_FILE_PATH is ${CURRENT_FILE_PATH}"

}

log_running_os_release(){
	OS_RELEASE=$(cat /etc/issue)

	log_to_stdout_and_trace "OS running release is ${OS_RELEASE}"
}

setup_log_file(){
	if [ "${LOG_FILE}" != "${LOG_FILE#*/*}" ]; then
		#test if path exists
		if [ "${LOG_FILE}" != "${LOG_FILE%*/}" ]; then
			log_to_stdout "Error: log file must be a file path"
			exit 44
		fi
		LOG_DIR="${LOG_FILE%/*}"
		if [ ! -d "${LOG_DIR}" ]; then
			mkdir -p "${LOG_DIR}"
		fi
	else
		LOG_FILE="$PWD/${LOG_FILE}"
	fi
	echo "log file is $LOG_FILE"	
}

################# MAIN STARTS HERE #######################

prepare_initialize

if [ $# -lt 1 ]; then
	 usage
else	
	#PARSE COMMAND LINE
	download_url=""

	while getopts "l:c:w:d:h?" opt; do

	case $opt in
		w)
			BASE_DIR=$OPTARG
			log_to_stdout "working dir is $BASE_DIR"
			;;
		c)
			COPY_TO_FOLDER="$OPTARG"
			;;
		l)
			LOG_FILE="$OPTARG"
			;;
		h|\?)
			usage
			;;
		d)
			download_url=$OPTARG
			log_to_stdout "download_url is $download_url"
			;;
		:)
			log_to_stdout "Option -$OPTARG requires an argument." 
			exit 1
			;;
	esac
	
	done

	shift $((OPTIND-1))
	
	setup_log_file

	if [ "$download_url" != "" ]; then
		init_base_dir "${BASE_DIR}"
		download_iso_file $download_url
	else
		if [ "$1" = "" ]; then
			log_to_stdout_and_trace "Put the iso file path as last argument"
			exit 2
		else
			init_base_dir "${BASE_DIR}"
			ISO_FILE="$1"
			log_to_stdout_and_trace "Iso file is $1"
		fi
	fi

	
	###################
	log_running_os_release

	check_iso_file "$ISO_FILE"

	mount_iso_file

	validate_iso_file ${ISO_MOUNT_FOLDER}

	if [ $RET != "0" ]; then 
		umount_iso_file
		exit $RET
	fi

	setup_variables

	if [ $ISLIVEISO -eq "0" ]; then 
		generate_initrd_gz "$ISO_FILE"
	else
		generate_squashfs "$ISO_FILE"
	fi
	
	prepare_iso_folder 

	make_iso "Resource" "isofolder"

	umount_iso_file

	cleanup_iso_folder

fi	
