#!/bin/bash

GENCROSS_TMPDIR=/tmp/gencross
DIALOG_CMD=${GENCROSS_TMPDIR}/dialog

GENCROSS=$0
TARCH=
HARCH=$(unset ARCH ; portageq envvar ARCH)
CTARGET=
BCAT="sys-devel"  ; BPKG="binutils"      ; BVER="[latest]"
GCAT="sys-devel"  ; GPKG="gcc"           ; GVER="[latest]"
KCAT="sys-kernel" ; KPKG="linux-headers" ; KVER="[latest]"
LCAT=""           ; LPKG=""              ; LVER="[latest]"
STAGE="-s4"
UOPTS="" # Options passed to emerge by crossdev
EX_GCC="no"
EX_GDB="no"

KARCH=
TOOLCHAIN=  # Toolchain selected
SYSROOT=
ROOT=
PORTAGE_CONFIGROOT=
GENMERGE=
GENMAKE=

# Usage: $1 = title
dialog_init() { echo "dialog --backtitle \"gencross utility\" --title \"$1\"" > ${DIALOG_CMD} ; }

# Usage: $1 = extra opts
dialog_extraopts() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}' '$1
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: $1 = text, $2 = height, $3 = width, $4 = menu-height
dialog_menu() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}" --menu \"$1\" $2 $3 $4"
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: $1 = text, $2 = height, $3 = width
dialog_msgbox() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}" --msgbox \"$1\" $2 $3"
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: $1 = text, $2 = height, $3 = width, $4 = list-height
dialog_checklist() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}" --checklist \"$1\" $2 $3 $4"
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: $1 = text, $2 = height, $3 = width
dialog_yesno() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}" --yesno \"$1\" $2 $3"
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: $1 = file, $2 = height, $3 = width
dialog_textbox() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}" --textbox \"$1\" $2 $3"
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: $1 = text, $2 = height, $3 = width, [ $4 = init ]
dialog_inputbox() {
	local CMD=`cat ${DIALOG_CMD}`
	if [ -z "$4" ] ; then
		CMD=${CMD}" --inputbox \"$1\" $2 $3 "
	else
		CMD=${CMD}" --inputbox \"$1\" $2 $3 $4 "
	fi
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: $1 = tags+items+[status] 
dialog_tag_item() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}" $1"
	echo ${CMD} > ${DIALOG_CMD}
}

# Usage: save the output in ${GENCROSS_TMPDIR}/$1
dialog_save_output() {
	local CMD=`cat ${DIALOG_CMD}`
	CMD=${CMD}" 2>${GENCROSS_TMPDIR}/$1"
	echo ${CMD} > ${DIALOG_CMD}
}

dialog_launch() { sh -c "`cat ${DIALOG_CMD}`" ; }

check_portage_overlay() {
	local POLSTDOUT_FILE=${GENCROSS_TMPDIR}/POLOUT
	local POLSTDERR_FILE=${GENCROSS_TMPDIR}/POLERR
	portageq envvar PORTDIR_OVERLAY 1>${POLSTDOUT_FILE} 2>${POLSTDERR_FILE}
	local POLSTDOUT=`cat ${POLSTDOUT_FILE}`
	local POLSTDERR=`cat ${POLSTDERR_FILE}`
	POLSTDERR=${POLSTDERR#*\'}
	POLSTDERR=${POLSTDERR%\'*}
	if [ -z ${POLSTDOUT} ] ; then
		if [ -z ${POLSTDERR} ] ; then
			# PORTDIR_OVERLAY is not set
			echo "PORTDIR_OVERLAY=/usr/local/portage" >> /etc/make.conf
			mkdir -p /usr/local/portage
			dialog_init "Portage Overlay"
			dialog_msgbox "\nPORTDIR_OVERLAY is not set.\nSet PORTDIR_OVERLAY=/usr/local/portage" 8 45
			dialog_launch
		else
			# PORTDIR_OVERLAY is set, but dir is not there
			mkdir -p ${POLSTDERR}
			dialog_init "Portage Overlay"
			dialog_msgbox "\nPORTDIR_OVERLAY(${POLSTDERR}) dir doesn't exit originally and has been created." 9 45
			dialog_launch
		fi
#	else
		# PORTDIR_OVERLAY is set
#		dialog_init "Portage Overlay"
#		dialog_msgbox "\nThe PORTDIR_OVERLAY has been set as:\n${POLSTDOUT}" 8 42
#		dialog_launch
	fi
}

# $1 = arch of "arch-vendor-OS-libc"
# Determine TARCH(target architecture)
# retuen value: ${TARCH}
determine_tarch() {
	case $1 in
		alpha*)     TARCH=alpha;;
		arm*)       TARCH=arm;;
		hppa*)      TARCH=hppa;;
		parisc)     TARCH=hppa;;
		ia64*)      TARCH=ia64;;
		i?86*)      TARCH=x86;;
		x86)        TARCH=x86;;
		m68*)       TARCH=m68k;;
		mips*)      TARCH=mips;;
		powerpc64*) TARCH=ppc64;;
		ppc64)      TARCH=ppc64;;
		powerpc*)   TARCH=ppc;;
		ppc)        TARCH=ppc;;
		sparc*)     TARCH=sparc;;
		s390*)      TARCH=s390;;
		sh*)        TARCH=sh;;
		x86_64*)    TARCH=amd64;;
		amd64)      TARCH=amd64;;
	esac
}

# $1 = ${TARCH}
# return value" ${KARCH}
determine_karch() {
	case $1 in
		alpha)     KARCH=alpha;;
		amd64)     KARCH=x86_64;;
		arm)       KARCH=arm;;
		hppa)      KARCH=parisc;;
		ia64)      KARCH=ia64;;
		mips)      KARCH=mips;;
		ppc)       KARCH=ppc;;
		ppc64)     KARCH=ppc;;
		s390)      KARCH=s390;;
		sh)        KARCH=sh;;
		sparc)     KARCH=sparc;;
		x86)       KARCH=i386;;
	esac
}

# retuen value: ${CTARGET}, ${LCAT}, ${LPKG}, ${TARCH}
determine_ctarget() {
	# Select arch
	dialog_init "CPU Architecture"
	dialog_extraopts "--no-cancel"
	dialog_extraopts "--default-item i686"
	dialog_menu "Select a target architecture" 16 35 10
	dialog_tag_item "alpha \"\""
	dialog_tag_item "arm \"\""
	dialog_tag_item "armeb \"\""
	dialog_tag_item "hppa \"\""
	dialog_tag_item "i386 \"\""
	dialog_tag_item "i486 \"\""
	dialog_tag_item "i586 \"\""
	dialog_tag_item "i686 \"\""
	dialog_tag_item "ia64 \"\""
	dialog_tag_item "m68k \"\""
	dialog_tag_item "mips \"\""
	dialog_tag_item "mipsel \"\""
	dialog_tag_item "mips64 \"\""
	dialog_tag_item "mips64el \"\""
	dialog_tag_item "powerpc \"\""
	dialog_tag_item "powerpc64 \"\""
	dialog_tag_item "s390 \"\""
	dialog_tag_item "s390x \"\""
	dialog_tag_item "sh \"\""
	dialog_tag_item "sh4 \"\""
	dialog_tag_item "sh64 \"\""
	dialog_tag_item "sparc \"\""
	dialog_tag_item "sparc64 \"\""
	dialog_tag_item "x86_64 \"\""
	dialog_save_output "ARCH"
	dialog_launch

	# Select vendor
	dialog_init "Hardware Platform or Vendor"
	dialog_extraopts "--no-cancel"
	dialog_extraopts "--default-item gentoo"
	dialog_menu "Select a vendor\nNote:softfloat for non-FPU CPU" 11 35 4
	dialog_tag_item "gentoo \"\""
	dialog_tag_item "pc \"\""
	dialog_tag_item "softfloat \"\""
	dialog_tag_item "unknown \"\""
	dialog_save_output "VENDOR"
	dialog_launch

	# Select OS
	dialog_init "Operating System"
	dialog_extraopts "--no-cancel"
	dialog_extraopts "--default-item linux"
	dialog_menu "Select an OS" 8 22 2
	dialog_tag_item "linux \"\""
	dialog_tag_item "uclinux \"\""
	dialog_save_output "OS"
	dialog_launch

	# Select libc
	dialog_init "C Library"
	dialog_extraopts "--no-cancel"
	dialog_extraopts "--default-item uclibc"
	dialog_menu "Select a C Library" 9 22 3
	dialog_tag_item "gnu \"\""
	dialog_tag_item "klibc \"\""
	dialog_tag_item "uclibc \"\""
	dialog_save_output "LIBC"
	dialog_launch

	# Determine CTARGET from previous inputs
	CTARGET=`cat ${GENCROSS_TMPDIR}/ARCH`-`cat ${GENCROSS_TMPDIR}/VENDOR`-`cat ${GENCROSS_TMPDIR}/OS`-`cat ${GENCROSS_TMPDIR}/LIBC`

	# Determine catagory/name(LCAT/LPKG) for libc
	case `cat ${GENCROSS_TMPDIR}/LIBC` in
		gnu)    LCAT="sys-libs" ; LPKG="glibc"  ;;
		klibc)  LCAT="dev-libs" ; LPKG="klibc"  ;;
		uclibc) LCAT="sys-libs" ; LPKG="uclibc" ;;
	esac

	# Determine ${TARCH} (target architecture)
	determine_tarch `cat ${GENCROSS_TMPDIR}/ARCH`
}

# Change the version of the package in the toolchain to be built.
# $1 = package name (binutils, gcc, linux-headers, or libc)
# return value: ${BVER}, or ${GVER}, or ${KVER}, or ${LVER}
package_version() {
	local PORTDIR=`portageq envvar PORTDIR`
	local PKGDIR=
	local TAGSITEMS=
	# Determine package dir from $1
	# e.g. if $1=uclibc, set PKGDIR=/usr/portage/sys-libs/uclibc
	case $1 in
		${BPKG}) PKGDIR=${PORTDIR}/${BCAT}/${BPKG};;
		${GPKG}) PKGDIR=${PORTDIR}/${GCAT}/${GPKG};;
		${KPKG}) PKGDIR=${PORTDIR}/${KCAT}/${KPKG};;
		${LPKG}) PKGDIR=${PORTDIR}/${LCAT}/${LPKG};;
	esac
	# Search ebuilds in the PKGDIR.
	# If the ebuid contains ${TARCH} or ~${TARCH}, add to (tag item) pairs.
	for ebuild in ${PKGDIR}/${1}-* ; do
		local PKGMASK=yes
		local PKGVER=${ebuild##/*/}
		PKGVER=${PKGVER%.*}
		local KEYWORDS=`grep KEYWORDS ${ebuild}`
		KEYWORDS=${KEYWORDS#*\"}
		KEYWORDS=${KEYWORDS%\"*}
		for k in ${KEYWORDS} ; do
			if [ ${k} = ${TARCH} ] ; then
				TAGSITEMS=${TAGSITEMS}${PKGVER}' '${TARCH}' '
				PKGMASK=no
			elif [ ${k} = "~${TARCH}" ] ; then
				TAGSITEMS=${TAGSITEMS}${PKGVER}' '"~${TARCH}"' '
				PKGMASK=no
			fi
		done
		[ ${PKGMASK} = yes ] && TAGSITEMS=${TAGSITEMS}${PKGVER}' '"-"' '
	done
	TAGSITEMS="[latest] N/A "${TAGSITEMS}
	dialog_init "${1} Version"
	dialog_extraopts "--no-cancel"
	dialog_menu "Select a version for $1" 16 45 10
	dialog_tag_item "${TAGSITEMS}"
	dialog_save_output "ANS"
	dialog_launch

	local ANS=`cat ${GENCROSS_TMPDIR}/ANS`
	case ${1} in
		${BPKG}) BVER=${ANS#*-};;
		${GPKG}) GVER=${ANS#*-};;
		${KPKG}) KVER=${ANS#linux-headers-};;
		${LPKG}) LVER=${ANS#*-};;
	esac
}

# return value: ${BVER}, ${GVER}, ${KVER}, ${LVER}
determine_version() {
	local OKVER=no
	local CHGVER=no
	local DFTITEM=${BPKG}
	BVER="[latest]"
	GVER="[latest]"
	KVER="[latest]"
	LVER="[latest]"
	while [ ${OKVER} = no ] ; do
		dialog_init "Toolchain Package Version"
		dialog_extraopts "--ok-label \"Enter\""
		dialog_extraopts "--cancel-label \"OK\""
		dialog_extraopts "--default-item ${DFTITEM}"
		[ ${CHGVER} = "no" ] && dialog_extraopts "--defaultno"
		dialog_menu "Select the package of which the version is to be changed. Press < OK  > to leave if done." 12 55 4
		dialog_tag_item "${BPKG} \"${BVER}\""
		dialog_tag_item "${GPKG} \"${GVER}\""
		dialog_tag_item "${KPKG} \"${KVER}\""
		dialog_tag_item "${LPKG} \"${LVER}\""
		dialog_save_output "ANS"
		dialog_launch

		case `cat ${GENCROSS_TMPDIR}/ANS` in
			${BPKG}) CHGVER=yes;DFTITEM=${BPKG};package_version ${BPKG};;
			${GPKG}) CHGVER=yes;DFTITEM=${GPKG};package_version ${GPKG};;
			${KPKG}) CHGVER=yes;DFTITEM=${KPKG};package_version ${KPKG};;
			${LPKG}) CHGVER=yes;DFTITEM=${LPKG};package_version ${LPKG};;
			*) OKVER=yes;;
		esac
	done
}

# return value: ${UOPTS}, ${EX_GCC}, ${EX_GDB}
parse_misc_opts() {
#	UOPTS=""
#	EX_GCC="no"
#	EX_GDB="no"
	while [ $# -gt 0 ] ; do
		case $1 in
		-b) UOPTS="${UOPTS}$1 ";;
		-d) UOPTS="${UOPTS}$1 ";;
		-p) UOPTS="${UOPTS}$1 ";;
		-v) UOPTS="${UOPTS}$1 ";;
		-q) UOPTS="${UOPTS}$1 ";;
		extra-gcc) EX_GCC="yes";;
		cross-gdb) EX_GDB="yes";;
		esac
		shift
	done
}

# return value: ${STAGE}, ${UOPTS}, ${EX_GCC}, ${EX_GDB}
determine_extraopts() {
	STAGE="-s4"
	UOPTS="" # Options passed to emerge by crossdev
	EX_GCC="no"
	EX_GDB="no"

	dialog_init "Build Stage"
	dialog_extraopts "--no-cancel"
	dialog_extraopts "--default-item -s4"
	dialog_menu "Select a build stage" 12 55 5
	dialog_tag_item "-s0 \"Build just binutils\""
	dialog_tag_item "-s1 \"Also build a C compiler (no libc/C++)\""
	dialog_tag_item "-s2 \"Also build kernel headers\""
	dialog_tag_item "-s3 \"Also build the C library (no C++)\""
	dialog_tag_item "-s4 \"Also build a C++ compiler [default]\""
	dialog_save_output "STAGE"
	dialog_launch
	STAGE=`cat ${GENCROSS_TMPDIR}/STAGE`

	dialog_init "Misc Options"
	dialog_extraopts "--no-cancel"
	dialog_extraopts "--separate-output"
	dialog_checklist "Press <space> to choose options [Multiple Choices]" 14 70 7
	dialog_tag_item "-b \"[passed to emerge] build binary packages\" off"
	dialog_tag_item "-d \"[passed to emerge] debug mode\" off"
	dialog_tag_item "-p \"[passed to emerge] pretend to install\" on"
	dialog_tag_item "-v \"[passed to emerge] verbose mode\" off"
	dialog_tag_item "-q \"[passed to emerge] quiet displays\" off"
	dialog_tag_item "extra-gcc \"Build extra gcc targets (gcj/ada/etc...)\" off"
	dialog_tag_item "cross-gdb \"Build a cross gdb\" off"
	dialog_save_output "CROSSDEV_EXTRA_OPTS"
	dialog_launch
	parse_misc_opts `cat ${GENCROSS_TMPDIR}/CROSSDEV_EXTRA_OPTS`
}

# return value: ${TOOLCHAIN}
select_toolchain() {
	# Search for existing toolchains
	local TOOLCHAINS=
	TOOLCHAIN=
	local PORTDIR_OVERLAY=`portageq envvar PORTDIR_OVERLAY`
	for t in ${PORTDIR_OVERLAY}/cross-* ; do
		[ ${t} = "${PORTDIR_OVERLAY}/cross-*" ] && break
		TOOLCHAINS=${TOOLCHAINS}${t##/*/cross-}" \"\" "
	done
	if [ -z ${TOOLCHAINS} ] ; then
		dialog_init "No Toolchain"
		dialog_msgbox "\nNo toolchain found!\n" 7 25
		dialog_launch
	else
		dialog_init "Select Toolchain"
		dialog_menu "Please select a toolchain" 12 45 5
		dialog_tag_item "${TOOLCHAINS}"
		dialog_save_output "TOOLCHAIN"
		dialog_launch
		# If users select <CANCEL>, TOOLCHAIN will be empty string.
		TOOLCHAIN=`cat ${GENCROSS_TMPDIR}/TOOLCHAIN`
	fi
}

# Usage: ${1} = yes || no [whether to select_toolchain first]
config_toolchain() {
	if [ ${1} = "yes" ] ; then
		# Select a toolchain to configure.
		select_toolchain
		# "No toolchain select" || "No existing toolchain"
		[ -z ${TOOLCHAIN} ] && return
	fi

	CTARGET=${TOOLCHAIN}
	SYSROOT=/usr/${CTARGET}
	ROOT=${SYSROOT}/genroot/rootfs
	PORTAGE_CONFIGROOT=${SYSROOT}

	determine_tarch ${CTARGET%%-*}
	[ -d ${SYSROOT}/genroot ] || mkdir -p ${SYSROOT}/genroot
	[ -d ${ROOT} ] || mkdir -p ${ROOT}

	if [ -f ${SYSROOT}/genroot/GENROOT_CONFIG_OK ] ; then
		dialog_init "Already Configured"
		dialog_extraopts "--defaultno"
		dialog_yesno "\nThe toolchain: ${TOOLCHAIN}\nhas been configured.\n\nDo you want to proceed anyway?" 10 50
		dialog_launch
		case $? in
			1) return;;
			255) return;;
		esac
		rm -rf ${SYSROOT}/genroot/GENROOT_CONFIG_OK
	fi

	# Prepare the content of /usr/${CTARGET}/etc/make.conf in /usr/${CTARGET}/genroot/make.conf
	local MAKECONF=${SYSROOT}/genroot/make.conf
	echo "ACCEPT_KEYWORDS=\"${TARCH}\""          > ${MAKECONF}
	echo "ARCH=\"${TARCH}\""                    >> ${MAKECONF}
	echo "CHOST=\"${CTARGET}\""                 >> ${MAKECONF}
	echo "CBUILD=\"`portageq envvar CHOST`\""   >> ${MAKECONF}
	echo "CTARGET=\"${CTARGET}\""               >> ${MAKECONF}
	echo "CFLAGS=\"-Os -pipe\""                 >> ${MAKECONF}
	echo "CXXFLAGS=\"\${CFLAGS}\""              >> ${MAKECONF}
	echo "INPUT_DEVICES=\"keyboard\""           >> ${MAKECONF}
	echo "MAKEOPTS=\"-j2\""                     >> ${MAKECONF}
	echo "USE=\"${TARCH} symlink\""             >> ${MAKECONF}
	mirrorselect -i -o >> ${MAKECONF}
	# Remove blank line(s)
	sed -i -e '/^$/d' ${MAKECONF}

	# Ask users if default make.conf is OK.
	local MAKEOK="no"
	while [ ${MAKEOK} = "no" ] ; do
		# Show ${SYSROOT}/genroot/make.conf
		dialog_init "make.conf for ${CTARGET}"
		dialog_textbox ${MAKECONF} 15 50
		dialog_launch
		# Ask users if they want to change variables in make.com
		dialog_init "make.conf OK?"
		dialog_extraopts "--defaultno"
		dialog_yesno "\nDo you want to change the content of make.conf?" 7 51
		dialog_launch
		case $? in
			0)
			# Parse variables in make.conf
			cp ${MAKECONF} ${GENCROSS_TMPDIR}/MAKECONF
			sed -i -n -e 's/=".*"/ ""/p' ${GENCROSS_TMPDIR}/MAKECONF
			local ALLMAKVAR=`cat ${GENCROSS_TMPDIR}/MAKECONF`
			# Select a variable to change
			dialog_init "make.conf Variables"
			dialog_extraopts "--no-cancel"
			dialog_menu "Please select a variable" 14 35 7
			dialog_tag_item "${ALLMAKVAR}"
			dialog_save_output "MAKVAR"
			dialog_launch
			local CHGVAR=`cat ${GENCROSS_TMPDIR}/MAKVAR`
			local CHGVARVAL=`grep ${CHGVAR}= ${MAKECONF}`
			CHGVARVAL=${CHGVARVAL#*=}
			CHGVARVAL=${CHGVARVAL//\$/\\\$}
			# Ask users to input new value for the variable
			dialog_init "Change ${CHGVAR}"
			dialog_inputbox "input content for ${CHGVAR}" 8 60 "${CHGVARVAL}"
			dialog_save_output "VARVAL"
			dialog_launch
			local CHGVARVAL=`cat ${GENCROSS_TMPDIR}/VARVAL`
			# Escape /
			CHGVARVAL=${CHGVARVAL//\//\\\/}

			# Create a new make.conf
			sed -i -e "s/${CHGVAR}=\".*\"/${CHGVAR}=\"${CHGVARVAL}\"/" ${MAKECONF}
			;;
			1) MAKEOK="yes";;
			255) ;;
		esac
	done
	# copy /usr/${CTARGET}/genroot/make.conf to /usr/${CTARGET}/etc/make.conf
	[ -d ${SYSROOT}/etc ] || mkdir -p ${SYSROOT}/etc
	cp -f ${MAKECONF} ${SYSROOT}/etc/make.conf

	# Creating ${SYSROOT}/etc/make.globals
	cp -f /etc/make.globals "${SYSROOT}/etc"
	# Create the directory for local profile configuration files
	mkdir -p "${SYSROOT}/etc/portage/profile"
	# Setting the sysroot Portage profile
	# FIXME: ugly implementation
	dialog_init "Select Profile"
	dialog_extraopts "--no-cancel --default-item uclibc/x86"
	dialog_menu "Please select a profile" 15 55 8
	dialog_tag_item "uclibc/amd64 \"\""
	dialog_tag_item "uclibc/arm \"\""
	dialog_tag_item "uclibc/mips \"\""
	dialog_tag_item "uclibc/ppc \"\""
	dialog_tag_item "uclibc/sh \"\""
	dialog_tag_item "uclibc/x86 \"\""
	dialog_tag_item "default-linux/x86/2006.1 \"\""
	dialog_tag_item "default-linux/x86/no-nptl \"\""
	dialog_tag_item "default-linux/x86/no-nptl/2.4 \"\""
	dialog_tag_item "default-linux/x86/2006.1/desktop \"\""
	dialog_tag_item "hardened/x86 \"\""
	dialog_tag_item "hardened/x86/2.6 \"\""
	dialog_tag_item "default-linux/ppc/ppc32/2006.1 \"\""
	dialog_tag_item "hardened/ppc \"\""
	#dialog_tag_item " \"\""
	dialog_save_output PROFILE
	dialog_launch
	local PROFILE=`portageq envvar PORTDIR`/profiles/`cat ${GENCROSS_TMPDIR}/PROFILE`
	ln -snf ${PROFILE} "${SYSROOT}/etc/make.profile"

	# Create xmerge: A simple cross emerge wrapper
	local XMERGEFILE=${SYSROOT}/genroot/xmerge_${CTARGET}
	echo "#!/bin/bash"                                   > ${XMERGEFILE}
	echo                                                >> ${XMERGEFILE}
	echo "SYSROOT=\"${SYSROOT}\""                       >> ${XMERGEFILE}
	echo "PORTAGE_CONFIGROOT=\"${PORTAGE_CONFIGROOT}\"" >> ${XMERGEFILE}
	echo "ROOT=\"${ROOT}\""                             >> ${XMERGEFILE}
	echo "if [ \"\${1}\" == \"--root\" ] ; then"        >> ${XMERGEFILE}
	echo "	ROOT=\"\${2}\""                             >> ${XMERGEFILE}
	echo "	shift 2"                                    >> ${XMERGEFILE}
	echo "fi"                                           >> ${XMERGEFILE}
	echo "export PORTAGE_CONFIGROOT ROOT SYSROOT"       >> ${XMERGEFILE}
	echo                                                >> ${XMERGEFILE}
	echo "emerge \$*"                                   >> ${XMERGEFILE}
	chmod +x ${XMERGEFILE}

	# Create xkmake: A cross kernel make wrapper
	determine_karch ${TARCH}
	local XKMAKEFILE=${SYSROOT}/genroot/xkmake_${CTARGET}
	echo "#!/bin/bash"                                   > ${XKMAKEFILE}
	echo                                                >> ${XKMAKEFILE}
	echo "SYSROOT=\"${SYSROOT}\""                       >> ${XKMAKEFILE}
	echo "PORTAGE_CONFIGROOT=\"${PORTAGE_CONFIGROOT}\"" >> ${XKMAKEFILE}
	echo "ROOT=\"${ROOT}\""                             >> ${XKMAKEFILE}
	echo "if [ \"\${1}\" == \"--root\" ] ; then"        >> ${XKMAKEFILE}
	echo "	ROOT=\"\${2}\""                             >> ${XKMAKEFILE}
	echo "	shift 2"                                    >> ${XKMAKEFILE}
	echo "fi"                                           >> ${XKMAKEFILE}
	echo "export PORTAGE_CONFIGROOT SYSROOT"            >> ${XKMAKEFILE}
	echo                                                >> ${XKMAKEFILE}
	echo "make ARCH=${KARCH} CROSS_COMPILE=${CTARGET}- INSTALL_MOD_PATH=\${ROOT} \$*" >> ${XKMAKEFILE}
	chmod +x ${XKMAKEFILE}

	touch ${SYSROOT}/genroot/GENROOT_CONFIG_OK
}

build_and_config_now() {
	# Prepare arguments for crossdev
	local CROSSDEVOPTS=${UOPTS}
	[ ${EX_GCC} = "yes" ] && CROSSDEVOPTS=${CROSSDEVOPTS}"--ex-gcc "
	[ ${EX_GDB} = "yes" ] && CROSSDEVOPTS=${CROSSDEVOPTS}"--ex-gdb "
	[ ${BVER} != "[latest]" ] && CROSSDEVOPTS=${CROSSDEVOPTS}"--b ${BVER} "
	[ ${GVER} != "[latest]" ] && CROSSDEVOPTS=${CROSSDEVOPTS}"--g ${GVER} "
	[ ${KVER} != "[latest]" ] && CROSSDEVOPTS=${CROSSDEVOPTS}"--k ${KVER} "
	[ ${LVER} != "[latest]" ] && CROSSDEVOPTS=${CROSSDEVOPTS}"--l ${LVER} "
	CROSSDEVOPTS=${CROSSDEVOPTS}"${STAGE} "
	CROSSDEVOPTS=${CROSSDEVOPTS}"-t ${CTARGET}"
	# Ask users to confirm again
	dialog_init "Final Confirmation"
	dialog_extraopts "--defaultno"
	dialog_yesno 	"\nTarget Architecture: ${TARCH}\nHost   Architecture: ${HARCH}\nCTARGET: ${CTARGET}\nbinutils: ${BVER}\ngcc: ${GVER}\nlinux-headers: ${KVER}\n${LPKG}: ${LVER}\nUOPTS: ${UOPTS}\nEX_GCC: ${EX_GCC}\nEX_GDB: ${EX_GDB}" 16 45
	dialog_launch

	if [ $? = "0" ] ; then # Answer is yes
		# Start to build
		clear
		crossdev ${CROSSDEVOPTS}

		# Check if the build is successful
		if [ $? -ne 0 ] ; then
			# Build failure, remove built packages
			echo; echo "Build failure!"; echo "Press <Enter> to continue"; read
			crossdev -C ${CTARGET}
			local PORT_LOGDIR=`portageq envvar PORT_LOGDIR`
			PORT_LOGDIR=${PORT_LOGDIR:-/var/log/portage}
			dialog_init "Build Failure"
			dialog_msgbox "\nPlease check log files in the following dir for more details:\n${PORT_LOGDIR}/cross-${CTARGET}-*" 8 70
			dialog_launch
		else
			# The build is ok.
			dialog_init "Build Success"
			dialog_msgbox "\nToolchain: ${CTARGET}\nhas been built successfully!\n" 8 50
			dialog_launch
			# Config toolchian now!
			dialog_init "Config Toolchain"
			dialog_msgbox "\nConfiguring ${CTARGET}" 7 48
			dialog_launch
			TOOLCHAIN=${CTARGET}
			config_toolchain "no"
		fi
	fi
}

build_toolchain() {
	determine_ctarget # retuen value: ${CTARGET}, ${LCAT}, ${LPKG}, ${TARCH}
	determine_version # return value: ${BVER}, ${GVER}, ${KVER}, ${LVER}
	determine_extraopts # return value: ${STAGE}, ${UOPTS}, ${EX_GCC}, ${EX_GDB}
	build_and_config_now
}

remove_toolchain() {
	# Select a toolchain to configure.
	select_toolchain
	# "No toolchain select" || "No existing toolchain"
	[ -z ${TOOLCHAIN} ] && return

	CTARGET=${TOOLCHAIN}
	SYSROOT=/usr/${CTARGET}
	ROOT=${SYSROOT}/genroot/rootfs
	PORTAGE_CONFIGROOT=${SYSROOT}
	dialog_init "Final Confirmation"
	dialog_extraopts "--defaultno"
	dialog_yesno "The following toolchain is to be removed:\n\n${CTARGET}\n\nAre you sure to do this?" 9 45
	dialog_launch
	case $? in
		0)
			clear
			rm -rf ${SYSROOT}/genroot
			rm -rf ${SYSROOT}/etc
			crossdev -C ${CTARGET};;
		255) ;;
	esac
}

# Install packages in /usr/${CTARGET}/genroot/rootfs by default
parse_and_install() {
	local USEFLAGS=
	local PKGS=
	local NOPKG=no
	[ $# -eq 0 ] && NOPKG=yes

	while [ $# -gt 0 ] ; do
		case ${1} in
		sys-libs/uclibc)
			#USEFLAGS=${USEFLAGS}"minimal "
			PKGS=${PKGS}"sys-libs/uclibc ";;
		sys-apps/baselayout-lite)
			# Check whether baselayout-lite is masked.
			${GENMERGE} -p sys-apps/baselayout-lite 1>/dev/null 2>/dev/null
			[ $? != "0" ] && echo "sys-apps/baselayout-lite -*" >> ${PORTAGE_CONFIGROOT}/etc/portage/package.keywords
			PKGS=${PKGS}"sys-apps/baselayout-lite ";;
		sys-apps/busybox)
			USEFLAGS=${USEFLAGS}"make-symlinks "
			PKGS=${PKGS}"sys-apps/busybox ";;
		net-misc/udhcp)
			PKGS=${PKGS}"net-misc/udhcp ";;
		net-misc/dropbear)
		# FIXME:cannot use "zlib", otherwise cannot configured successfully
			USEFLAGS=${USEFLAGS}"-zlib "
			PKGS=${PKGS}"net-misc/dropbear ";;
		www-client/lynx)
			PKGS=${PKGS}"www-client/lynx ";;
		net-irc/scrollz)
			PKGS=${PKGS}"net-irc/scrollz ";;
		sys-apps/net-tools)
			PKGS=${PKGS}"sys-apps/net-tools ";;
		net-misc/iputils)
			PKGS=${PKGS}"net-misc/iputils ";;
		app-misc/screen)
		# FIXME: cannot configured successfully
			PKGS=${PKGS}"app-misc/screen ";;
		sys-apps/coreutils)
		# FIXME: pull in too many packages
			PKGS=${PKGS}"sys-apps/coreutils ";;
		app-shells/bash)
		# FIXME: cannot configured successfully
			PKGS=${PKGS}"app-shells/bash ";;
			#dialog_init "Install ${1}"
			#dialog_msgbox "\n${1}\n" 7 40
			#dialog_launch ;;
		*) ;;
		esac
		shift
	done

	if [ ${NOPKG} = "yes" ] ; then
		dialog_init "No Packages"
		dialog_msgbox "\nNo packages selected!" 7 27
		dialog_launch
	else
		clear
		USE=${USEFLAGS} ${GENMERGE} -avuN ${PKGS}
		echo; echo "Press <Enter> to continue"; read
	fi
}

config_rootfs() {
	# Configuring rootfs
	dialog_init "Config Rootfs?"
#	dialog_extraopts "--defaultno"
	dialog_yesno "\nConfiguring roofs includes:\n\n1. Set up root password\n2. Set the hostname\n3. Write fstab\n4. Write /init(initramfs)\n\nDo you want to do these?" 14 45
	dialog_launch
	[ $? = "0" ] || return

	# Set up root password
	# FIXME: Is there any way to encrypt user's password in bash shell script?
	# root password: test
	echo "root:\$1\$\$whuMjZj.HMFoaTaZRRtkO0:0:0:root:/root:/bin/ash" > ${ROOT}/etc/passwd
	echo "root:\$1\$\$whuMjZj.HMFoaTaZRRtkO0:0:0:root:/root:/bin/ash" > ${ROOT}/etc/passwd-
	dialog_init "FIXME: Root Password"
	dialog_msgbox "\nRoot password cannot be set dynamically now.\nIt's 'test' by far.\n" 8 50
	dialog_launch
	# Set the hostname
	dialog_init "Set Hostname"
	dialog_inputbox "Please input hostname" 8 60 "genroot"
	dialog_save_output "HOSTNAME"
	dialog_launch
	echo `cat ${GENCROSS_TMPDIR}/HOSTNAME` > ${ROOT}/etc/hostname
	# Write fstab
	local ROOTFSTAB=${ROOT}/etc/fstab
	echo "# default ram disk as root" > ${ROOTFSTAB}
	echo "" >> ${ROOTFSTAB}
	echo "#/dev/ram0		/		cramfs 		defaults 	0 0" >> ${ROOTFSTAB}
	echo "#none			/proc		proc		defaults  	0 0" >> ${ROOTFSTAB}
	echo "" >> ${ROOTFSTAB}
	echo "# glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for" >> ${ROOTFSTAB}
	echo "# POSIX shared memory (shm_open, shm_unlink). " >> ${ROOTFSTAB}
	echo "# (tmpfs is a dynamically expandable/shrinkable ramdisk, and will" >> ${ROOTFSTAB}
	echo "#  use almost no memory if not populated with files)" >> ${ROOTFSTAB}
	echo "# Adding the following line to /etc/fstab should take care of this:" >> ${ROOTFSTAB}
	echo "" >> ${ROOTFSTAB}
	echo "#none			/dev/shm	tmpfs		defaults	0 0" >> ${ROOTFSTAB}
	echo "none			/tmp		tmpfs		defaults	0 0" >> ${ROOTFSTAB}
	echo "none			/proc		proc		defaults	0 0" >> ${ROOTFSTAB}
	dialog_init "/etc/fstab"
	dialog_msgbox "\nWrite /etc/fstab OK\n" 7 25
	dialog_launch
	# Write /init (initramfs)
	local ROOTINIT=${ROOT}/init
	echo "#!/bin/ash"                                             > ${ROOTINIT}
	echo "echo"                                                  >> ${ROOTINIT}
	echo "echo"                                                  >> ${ROOTINIT}
	echo "echo \" Welcome to Genroot\""                          >> ${ROOTINIT}
	echo "echo"                                                  >> ${ROOTINIT}
	echo "echo"                                                  >> ${ROOTINIT}
	echo ""                                                      >> ${ROOTINIT}
	echo "echo \" * Setting umask..\""                           >> ${ROOTINIT}
	echo "umask 022"                                             >> ${ROOTINIT}
	echo "echo \" * Mounting /proc..\""                          >> ${ROOTINIT}
	echo "mount -t proc none /proc"                              >> ${ROOTINIT}
	echo "echo \" * Starting init..\""                           >> ${ROOTINIT}
	echo "exec <dev/console >dev/console 2>&1"                   >> ${ROOTINIT}
	echo "exec chroot . /sbin/init"                              >> ${ROOTINIT}
	echo ""                                                      >> ${ROOTINIT}
	echo "echo \" *** Starting init failed! ***\""               >> ${ROOTINIT}
	echo "echo \" * Trying to start a shell..\""                 >> ${ROOTINIT}
	echo "exec /bin/ash"                                         >> ${ROOTINIT}
	chmod +x ${ROOTINIT}
	dialog_init "/init"
	dialog_msgbox "\nWrite /init OK\n" 7 20
	dialog_launch
	# Change /etc/inittab?
	# Change the timezone?

	# Create initramfs image
	cd ${ROOT} && find . | cpio -H newc -o | gzip -9 > ${SYSROOT}/genroot/initramfs_${CTARGET}.igz
	dialog_init "initramfs Image"
	dialog_msgbox "\ninitramfs_${CTARGET}.igz now in\n${SYSROOT}/genroot/\n" 8 55
	dialog_launch
}

# $1 = cat/pkg, $2 = file which contains the answer in ${GENCROSS_TMPDIR} dir
check_installed_version() {
	portageq match ${ROOT} ${1} 1>${GENCROSS_TMPDIR}/${2}
	local VERSION=`cat ${GENCROSS_TMPDIR}/${2}`
	VERSION=${VERSION#${1}-}
	[ -z ${VERSION} ] && VERSION=N/A
	echo ${VERSION} > ${GENCROSS_TMPDIR}/${2}
}

# Updated values: ${CTARGET}, ${SYSROOT}, ${ROOT}, ${PORTAGE_CONFIGROOT}, ${GENMERGE}, ${GENMAKE}
toolchain_package() {
	# Select a toolchain to configure.
	select_toolchain
	# "No toolchain select" || "No existing toolchain"
	[ -z ${TOOLCHAIN} ] && return

	CTARGET=${TOOLCHAIN}
	SYSROOT=/usr/${CTARGET}
	ROOT=${SYSROOT}/genroot/rootfs
	[ -d ${ROOT} ] || mkdir -p ${ROOT}
	PORTAGE_CONFIGROOT=${SYSROOT}
	GENMERGE="/usr/${CTARGET}/genroot/xmerge_${CTARGET}"
	GENMAKE="/usr/${CTARGET}/genroot/xkmake_${CTARGET}"

	# Select and install packages
	dialog_init "Select Packages"
	dialog_extraopts "--no-cancel --separate-output"
	dialog_checklist "Please selects packages to be installed" 15 60 8
	case ${CTARGET##*-} in
		gnu)
			check_installed_version "sys-libs/glibc" "VERSION"
			dialog_tag_item "sys-libs/glibc \"`cat ${GENCROSS_TMPDIR}/VERSION`\" on";;
		klibc)
			check_installed_version "dev-libs/klibc" "VERSION"
			dialog_tag_item "dev-libs/klibc \"`cat ${GENCROSS_TMPDIR}/VERSION`\" on";;
		uclibc)
			check_installed_version "sys-libs/uclibc" "VERSION"
			dialog_tag_item "sys-libs/uclibc \"`cat ${GENCROSS_TMPDIR}/VERSION`\" on";;
	esac
	# The following packages can be compiled successfully in the following target:
	# i386-gentoo-linux-uclibc
	check_installed_version "sys-apps/baselayout-lite" "VERSION"
	dialog_tag_item "sys-apps/baselayout-lite \"`cat ${GENCROSS_TMPDIR}/VERSION`\" on"
	check_installed_version "sys-apps/busybox" "VERSION"
	dialog_tag_item "sys-apps/busybox \"`cat ${GENCROSS_TMPDIR}/VERSION`\" on"
	check_installed_version "net-misc/udhcp" "VERSION"
	dialog_tag_item "net-misc/udhcp \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
	check_installed_version "net-misc/dropbear" "VERSION"
	dialog_tag_item "net-misc/dropbear \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
	check_installed_version "www-client/lynx" "VERSION"
	dialog_tag_item "www-client/lynx \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
	check_installed_version "net-irc/scrollz" "VERSION"
	dialog_tag_item "net-irc/scrollz \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
	check_installed_version "sys-apps/net-tools" "VERSION"
	dialog_tag_item "sys-apps/net-tools \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
	check_installed_version "net-misc/iputils" "VERSION"
	dialog_tag_item "net-misc/iputils \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
#	check_installed_version "app-misc/screen" "VERSION"
#	dialog_tag_item "app-misc/screen \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
#	check_installed_version "sys-apps/coreutils" "VERSION"
#	dialog_tag_item "sys-apps/coreutils \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
#	check_installed_version "app-shells/bash" "VERSION"
#	dialog_tag_item "app-shells/bash \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
#	dialog_tag_item "system \"\" off"
	#check_installed_version "sys-libs/glibc" "VERSION"
	#dialog_tag_item " \"`cat ${GENCROSS_TMPDIR}/VERSION`\" off"
	dialog_save_output "PACKAGES"
	dialog_launch

	parse_and_install `cat ${GENCROSS_TMPDIR}/PACKAGES`
	config_rootfs
}

install_kernel() {
	# Install kernel with respect to /
	ROOT=/
	dialog_init "Select Kernel"
	dialog_menu "Please select a kernel for\n${CTARGET}" 14 45 6
	check_installed_version "sys-kernel/gentoo-sources" "VERSION"
	dialog_tag_item "gentoo-sources \"`cat ${GENCROSS_TMPDIR}/VERSION`\""
	check_installed_version "sys-kernel/hppa-sources" "VERSION"
	dialog_tag_item "hppa-sources \"`cat ${GENCROSS_TMPDIR}/VERSION`\""
	check_installed_version "sys-kernel/mips-sources" "VERSION"
	dialog_tag_item "mips-sources \"`cat ${GENCROSS_TMPDIR}/VERSION`\""
	check_installed_version "sys-kernel/sh-sources" "VERSION"
	dialog_tag_item "sh-sources \"`cat ${GENCROSS_TMPDIR}/VERSION`\""
	check_installed_version "sys-kernel/sparc-sources" "VERSION"
	dialog_tag_item "sparc-sources \"`cat ${GENCROSS_TMPDIR}/VERSION`\""
	check_installed_version "sys-kernel/vanilla-sources" "VERSION"
	dialog_tag_item "vanilla-sources \"`cat ${GENCROSS_TMPDIR}/VERSION`\""
	dialog_save_output "KERNEL"
	dialog_launch
	# Check the version of selected kernel source
	check_installed_version "sys-kernel/`cat ${GENCROSS_TMPDIR}/KERNEL`" "VERSION"
	# Recover ${ROOT}
	ROOT=${SYSROOT}/genroot/rootfs

	if [ `cat ${GENCROSS_TMPDIR}/VERSION` != "N/A" ] ; then
		# The kernel is installed
		# Ask users whether to install anyway
		dialog_init "Already Installed"
		dialog_extraopts "--defaultno"
		dialog_yesno "\nSources: sys-kernel/`cat ${GENCROSS_TMPDIR}/KERNEL`\nVersion: `cat ${GENCROSS_TMPDIR}/VERSION`\n\nDo you want to install anyway?" 10 40
		dialog_launch
		if [ $? = "0" ] ; then
			# Users choose to re-merge the kernel
			clear
			#${GENMERGE} --root / -av `cat ${GENCROSS_TMPDIR}/KERNEL`
			USE="symlink -doc" emerge -av `cat ${GENCROSS_TMPDIR}/KERNEL`
		fi
	else
		# The kernerl is not installed
		# Install it now!
		clear
		#${GENMERGE} --root / -av `cat ${GENCROSS_TMPDIR}/KERNEL`
		USE="symlink -doc" emerge -av `cat ${GENCROSS_TMPDIR}/KERNEL`
	fi
}

manipulate_kernel() {
	ROOT=${SYSROOT}/genroot/rootfs
	cd /usr/src/linux
	if [ $? != "0" ] ; then
		dialog_init "Cannot Enter Kernel Dir"
		dialog_msgbox "\nCannot Enter Kernel Directory\n/usr/src/linux\n" 8 35
		dialog_launch
	fi
	case ${1} in
		config)
			if [ -f ${SYSROOT}/genroot/config_${CTARGET} ] ; then
				if [ ! -f /usr/src/linux/.config ] ; then
					dialog_init "Restore Configuration"
					dialog_extraopts "--defaultno"
					dialog_yesno "\nDo you want to restore kernel configuration from\n${SYSROOT}/genroot?" 8 52
					dialog_launch
					[ $? = "0" ] && cp ${SYSROOT}/genroot/config_${CTARGET} /usr/src/linux/.config
				fi
			fi
			${GENMAKE} menuconfig
			if [ -f "/usr/src/linux/.config" ] ; then
				dialog_init "Backup Configuration"
				dialog_extraopts "--defaultno"
				dialog_yesno "\nDo you want to copy kernel configuration to\n${SYSROOT}/genroot?" 8 48
				dialog_launch
				[ $? = "0" ] && cp /usr/src/linux/.config ${SYSROOT}/genroot/config_${CTARGET}
			fi
			;;
		compile)
			rm -f /usr/src/linux/usr/.initramfs_*
			rm -f .built-in.o.cmd .gen_init_cpio.cmd
			rm -f built-in.o gen_init_cpio initramfs_data.cpio.gz initramfs_data.o
			${GENMAKE}
			echo; echo "Build End"; echo "Press <Enter> to continue"; read
			;;
		insmod)
			[ -d "${ROOT}/lib/modules" ] && rm -rf ${ROOT}/lib/modules
			${GENMAKE} modules_install
			echo; echo "Installation End"; echo "Press <Enter> to continue"; read
			;;
		image)
			dialog_init "Build Image"
			dialog_extraopts "--defaultno"
			dialog_yesno "Please enable initramfs (Device Drivers->Block Devices) and \nSpecify rootfs directory (General setup, default rootfs: \n${SYSROOT}/genroot/rootfs)\nPS: only 2.6 kernel support initramfs\n\nDo you want to proceed to build the image?" 10 65
			dialog_launch
			[ $? != "0" ] && return
			rm -f /usr/src/linux/usr/.initramfs_*
			rm -f .built-in.o.cmd .gen_init_cpio.cmd
			rm -f built-in.o gen_init_cpio initramfs_data.cpio.gz initramfs_data.o
			${GENMAKE}
			[ -d "${ROOT}/lib/modules" ] && rm -rf ${ROOT}/lib/modules
			${GENMAKE} modules_install
			rm -f /usr/src/linux/usr/.initramfs_*
			rm -f .built-in.o.cmd .gen_init_cpio.cmd
			rm -f built-in.o gen_init_cpio initramfs_data.cpio.gz initramfs_data.o
			${GENMAKE}
			echo; echo "Build End"; echo "Press <Enter> to continue"; read
			;;
	esac
}

toolchain_kernel() {
	# Select a toolchain to configure.
	select_toolchain
	# "No toolchain select" || "No existing toolchain"
	[ -z ${TOOLCHAIN} ] && return

	CTARGET=${TOOLCHAIN}
	SYSROOT=/usr/${CTARGET}
	ROOT=${SYSROOT}/genroot/rootfs
	[ -d ${ROOT} ] || mkdir -p ${ROOT}
	PORTAGE_CONFIGROOT=${SYSROOT}
	GENMERGE="/usr/${CTARGET}/genroot/xmerge_${CTARGET}"
	GENMAKE="/usr/${CTARGET}/genroot/xkmake_${CTARGET}"

	local DEFAULTITEM="2"
	while [ 1 ] ; do
		dialog_init "Operation on Kernel"
		dialog_extraopts "--default-item ${DEFAULTITEM}"
		dialog_menu "What do you want to do?" 12 50 5
		dialog_tag_item "1 \"Install Kernel\""
		dialog_tag_item "2 \"Configure Kernel\""
		dialog_tag_item "3 \"Compile Kernel and Modules\""
		dialog_tag_item "4 \"Install Modules to Rootfs\""
		dialog_tag_item "5 \"Build a single image (Kernel+Rootfs)\""
		dialog_save_output "ANS"
		dialog_launch

		case `cat ${GENCROSS_TMPDIR}/ANS` in
			1) DEFAULTITEM="1"; install_kernel;;
			2) DEFAULTITEM="2"; manipulate_kernel "config" ;;
			3) DEFAULTITEM="3"; manipulate_kernel "compile";;
			4) DEFAULTITEM="4"; manipulate_kernel "insmod" ;;
			5) DEFAULTITEM="5"; manipulate_kernel "image"  ;;
			*) return;;
		esac
	done
}

main_menu() {
	check_portage_overlay
	local DFTITEM=Build
	while [ 1 ] ; do
		# Launch main menu (main box)
		dialog_init "Main Menu"
		dialog_extraopts "--cancel-label \"Exit\" --default-item \"${DFTITEM}\""
		dialog_menu "What do you want to do?" 12 55 5
		dialog_tag_item "Build \"Build a toolchain\""
		dialog_tag_item "Remove \"Remove a toolchain\""
		dialog_tag_item "Config \"Config a toolchain\""
		dialog_tag_item "Package \"select a toolchain to build package\""
		dialog_tag_item "Kernel \"select a toolchain to build kernel\""
		dialog_save_output "ANS"
		dialog_launch

		local ANS=`cat ${GENCROSS_TMPDIR}/ANS`
		case ${ANS} in
			Build)   DFTITEM=Build   ; build_toolchain        ;;
			Remove)  DFTITEM=Remove  ; remove_toolchain       ;;
			Config)  DFTITEM=Config  ; config_toolchain "yes" ;;
			Package) DFTITEM=Package ; toolchain_package      ;;
			Kernel)  DFTITEM=Kernel  ; toolchain_kernel       ;;
			*) exit 0 ;;
		esac
	done
}

[ -d ${GENCROSS_TMPDIR} ] && rm -rf ${GENCROSS_TMPDIR}
mkdir -p ${GENCROSS_TMPDIR}

main_menu
