#!/bin/bash -l
DIALOG=${DIALOG=dialog}
CONFIG="/etc/image-installer.conf"
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
tempfile2=`tempfile 2>/dev/null` || tempfile2=/tmp/test2$$
tempfiler1=`tempfile 2>/dev/null` || tempfiler1=/tmp/test2$$
tempfiler2=`tempfile 2>/dev/null` || tempfiler2=/tmp/test2$$
ARCHIVETYPE=""
trap "rm -f ${tempfile}" 0 1 2 5 15
trap "rm -f ${tempfile2}" 0 1 2 5 15
trap "rm -f ${tempfiler1}" 0 1 2 5 15
trap "rm -f ${tempfiler2}" 0 1 2 5 15

if [ "`id -u`" != "0" ] ; then
	echo "Image Installer must run as user 'root'"
	exit 1
fi

ALLDRIVES=`cat /proc/partitions | egrep '(x?[hsv]d[a-z]$|mmcblk[0-9]{1,2}$|nvme[0-9]{1,2}n[1-9]{1,2}$)' | awk '{print $NF}'`

function debug {
	if [ ${DEBUG} == "1" ] ; then
	echo -e -n "$@"
	fi
}

function gen_templlist {
	CNT=1
	cd ${BASEMOUNT}
	for IMG in `find . -maxdepth 1 -type f -iname \*.img -o -iname \*.dd -o -iname \*.gz -o -iname \*.bz2 -o -iname \*.xz |grep -v "^\.$" |sed -e s@"\./"@""@g`
	do
	echo ${IMG} ${CNT} off	
	CNT=`expr ${CNT} + 1`
	done
}

function gen_disklist {
	CNT=1
	for DISK in ${ALLIDEDRIVES} ${ALLSCSIDRIVES} ${ALLDRIVES}
	do
	
		WRK=${DISK}
		echo ${WRK} ${CNT} off
		CNT=`expr ${CNT} + 1`
	
	done
}

function prepare_setup {	
	if [ -f ${CONFIG} ]; then
		. ${CONFIG}
		if [ -n "${BASEMOUNT}" ]; then
			mkdir -p "${BASEMOUNT}"
			case ${IMAGELOCATION} in
				NFS)
					mount -t nfs ${IMAGELOCATION_NFS} ${BASEMOUNT}
					
				;;
				DIR)
					mount -o bind ${IMAGELOCATION_DIR} ${BASEMOUNT}
				;;
				*)
					echo "IMAGELOCTION: ${IMAGELOCATION} not supported"
					exit 1
				;;
			esac
		else
			echo "no base mountpoint in config"
			exit 1
		fi
	else
		echo "configuration file not found"
		exit 1
	fi
}

function get_archiver {
#	echo "ARCHIVE: $1"
	GZ=`echo ${1} | grep -E '(.gz$)'`
	BZ=`echo ${1} | grep -E '(.bz2$)'`
	XZ=`echo ${1} | grep -E '(.xz$)'`
	IMG=`echo ${1} | grep -E '(.img$|.dd$)'`

	if [ -n "${GZ}" ] ; then
		echo ARCHIVETYPE="GZ" > $tempfile
		echo "$(type -p zcat 2>/dev/null) $1"
	elif [ -n "${BZ}" ] ; then
		echo ARCHIVETYPE="BZ2" > $tempfile
		echo "$(type -p bzcat 2>/dev/null) $1"
	elif [ -n "${XZ}" ] ; then
		echo ARCHIVETYPE="XZ" > $tempfile
		echo "$(type -p xzcat 2>/dev/null) $1"
	elif [ -n "${IMG}" ] ; then
		echo ARCHIVETYPE="PLAIN" > $tempfile
		echo "$(type -p cat 2>/dev/null) $1"
	else
		echo ARCHIVETYPE="UNKNOWN" > $tempfile
		exit 77
	fi
}

function get_size_from_archive {
        GZ=`echo ${1} | grep -E '(.gz$)'`
        BZ=`echo ${1} | grep -E '(.bz2$)'`
        XZ=`echo ${1} | grep -E '(.xz$)'`
        IMG=`echo ${1} | grep -E '(.img$|.dd$)'`
	
	if [ -n "${GZ}" ] ; then
		echo "$(gunzip -l $1 | tail -n1 | awk '{print $2}')"
	elif [ -n "${BZ}" ] ; then
		echo 0
	elif [ -n "${XZ}" ] ; then
		echo "$(xz -vl $1 | tail -n1|awk '{print $(NF-2)}')"
	elif [ -n "${IMG}" ] ; then
		echo "$(du -b $1 | tail -n1|awk '{print $1}')"
	fi
}


function umount_base {
	cd /
	umount ${BASEMOUNT}
}

################### start up the stuff #############################
prepare_setup

######## IMAGE SELECT ##########
${DIALOG} --backtitle "${TITLE}" \
	--title "Image selection" --clear \
	--radiolist "Please select image to install: " 20 75 10 `gen_templlist` 2> ${tempfile2}
retval=$?
imagefile=`cat ${tempfile2}`
case ${retval} in 
	0)
		clear
		if [ -z "`cat ${tempfile2}`" ]; then
			umount_base
			echo "no image selected"
			exit 1
		fi
		;;
	1)
		umount_base
		echo "cancel pressed in image selection dialog"
		exit 1
		;;
	255)
		gen_templlist
		umount_base
		echo "esc pressed in image selection dialog"
		exit 255
		;;
esac

######### DISK SELECT ##########
${DIALOG} --backtitle "${TITLE}" \
	--title "Disk Partitioner" --clear \
	--radiolist "Please select disk for installation: " 20 75 10 `gen_disklist` 2> ${tempfile}
	
retval=$?

targetdisk=`cat ${tempfile}`


case ${retval} in 
	0)
		# write image to target disk
		clear
		FSIZE=`get_size_from_archive ${BASEMOUNT}/${imagefile}`
		ARCCMD=`get_archiver ${BASEMOUNT}/${imagefile}`
		if [ "${ARCHIVETYPE}" == "BZ2" ] ; then
			${ARCCMD} | pv | dd of=/dev/${targetdisk}
		else
			(${ARCCMD} | pv -n -s ${FSIZE} | dd of=/dev/${targetdisk}) 2>&1 | \
			${DIALOG} --backtitle "$TITLE" \
			--title "Writing image" \
			--gauge "Running dd command (from ${imagefile} to /dev/${targetdisk}), please wait..." 10 70 0
			retval=$?
			clear
			if [ "${retval}" == "0" ] ; then
				${DIALOG} --backtitle "$TITLE" \
				--title "Imaging completed" \
				--yesno "Write completed, reboot now?" 5 32
				retval=$?
				case ${retval} in
					0)
						#yes
						umount_base
						reboot
					;;
					1)
						#no
						clear
					;;
				esac
			else
				${DIALOG} --backtitle "$TITLE" \
				--title "Imaging failed" \
				--msgbox "Write failed, exiting..." 5 28 && clear
			fi
		fi
		umount_base
		;;
	1)
		umount_base
		echo "cancel pressed in disk selection dialog"
		exit 1
		;;
	255)
		umount_base
		echo "esc pressed in disk selection dialog"
		exit 255
		;;
esac
exit 0
