#!/bin/busybox ash
# (c) Robert Shingledecker 2012
# Contributions by Jason Williams
. /etc/init.d/tc-functions

#useBusybox
alias wget='/bb/wget'
alias md5sum='/bb/md5sum'
> /tmp/.pkglist

TCUSER=`cat /etc/sysconfig/tcuser`
chown "$TCUSER":staff /tmp > /dev/null 2>&1
chmod 1777 /tmp > /dev/null 2>&1
checkroot
BUILD=`getBuild`
if [ "$BUILD" == "x86" ]; then
	DEBBUILD="i386"
elif [ "$BUILD" == "armv7" ]; then
	DEBBUILD="armhf"
elif [ "$BUILD" == "x86_64" ]; then
	DEBBUILD="amd64"
fi

if [ -f /usr/share/doc/tc/distro.txt ]; then
	DISTRO=`cat /usr/share/doc/tc/distro.txt`
else
	DISTRO=debian
fi

if [ -f /usr/share/doc/tc/repo.txt ]; then
	REPO=`cat /usr/share/doc/tc/repo.txt | sed 's:64::'`
else
	REPO=wheezy
fi

TCEDIR=/etc/sysconfig/tcedir
SCEDIR="$TCEDIR"/sce
DEBINXDIR=""$TCEDIR"/import/debinx"

[ -d /etc/sysconfig/tcedir/import/debinx ] || mkdir -p /etc/sysconfig/tcedir/import/debinx

setupStartupScript() {
	[ -d "$IMPORT"/"$TARGET"/usr/local/tce.installed ] || mkdir -p "$IMPORT"/"$TARGET"/usr/local/tce.installed
	chmod 775 "$IMPORT"/"$TARGET"/usr/local/tce.installed > /dev/null 2>&1
	chown root.staff "$IMPORT"/"$TARGET"/usr/local/tce.installed > /dev/null 2>&1
}

## Retrieve the Debian package from the appropriate Debian repo.
fetchDeb() {

		/bb/wget -O "$DEBS"/"$THISDEB"  ${MIRROR}/${1}
		if [ "$?" != 0 ]
		then
			echo "Failed on download of "$1"."
			echo "$1" >> /tmp/import.log
			selectDeb ${1}
		fi
			
}
##

## Bring up a menu if the matching file name of the Debian package is not found in the Debian repo.
selectDeb() {
	FULLPATH=${1}
	SELECT_PATH="${FULLPATH%/*}"
	PKG="${1##*/}"
	/bb/wget -q -O - "$MIRROR"/"$SELECT_PATH" | awk 'BEGIN{FS=" href="}{print $2}' | awk 'BEGIN{FS="\""}{print $2}' | grep "^${PKG%%_*}" | grep ".deb$" | select "Select Package for ${PKG}" "-"
	read DEB < /tmp/select.ans
	if [ "$DEB" != "q" ]
	then
		fetchDeb ${SELECT_PATH}/${DEB}
	fi
}
##

## Functions to get the md5sum of the Debian .deb from the appropriate Packages list.
getMd5sum() {
> /tmp/"$1".pkglist
grep -B 1 -A 10 "^Package: $1$" "$DEBINX" |  grep -B10 "^$" > /tmp/"$1".pkglist
DEBINX=/tmp/"$1".pkglist
getMd5sum1 $1
rm /tmp/"$1".pkglist
}

getMd5sum1() {
	awk -v package="Package: $1" -v build="$DEBBUILD" -v FIELD="$1: "  '
	BEGIN {
		RS=""
		FS="\n"
	}
	{
		if ($1 == package) {
			for (i=2; i <= NF; i++) {
				split($i,f,": ")

				if ( f[1] == "Architecture" ) {
					if ( f[2] == "all" )
						{}
					else if ( f[2] == build )
						{}
					else
						break
					}
				
				if ( f[1] == "MD5sum" )
					{ print f[2]; exit; }
					
			}
		} 

	} ' < "$DEBINX"
}
##

## Check to see if package is available for dCore port.
checkextrarepoexists() {
	awk -v package="Package: $1" -v build="$DEBBUILD" -v FIELD="$1: "  '
	BEGIN {
		RS=""
		FS="\n"
	}
	{
		if ($1 == package) {
			for (i=2; i <= NF; i++) {
				split($i,f,": ")

				if ( f[1] == "Architecture" ) {
					if ( f[2] == "all" )
						{}
					else if ( f[2] == build )
						{}
					else
						break
					}
				
				if ( f[1] == "Filename" )
					{ print f[2]; exit; }
					
			}
		} 

	} ' < "$DEBINX"
}
##

## Create SCE_import_summary file before squashing up extension.
createImportSummary () {
	IMPORTSUMMARY=""$TARGET"/usr/local/sce/"$TARGET"/"$TARGET"_import_summary"
	touch "$IMPORTSUMMARY"
	if [ -f "$TCEDIR"/sce/"$TARGET".sce ]; then
		echo "Re-imported "$TARGET".sce on `date`." >> "$IMPORTSUMMARY"
	else
		echo "Imported "$TARGET".sce on `date`." >> "$IMPORTSUMMARY"
	fi
	
	echo " " >> "$IMPORTSUMMARY"
	if cat /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep > /dev/null 2>&1; then
		echo "Dependency SCE(s) selected during import:" >> "$IMPORTSUMMARY"
		cat /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep >> "$IMPORTSUMMARY"
		echo " " >> "$IMPORTSUMMARY"
		echo "Packages provided by selected dependency SCE(s) and any" >> "$IMPORTSUMMARY"
		echo "applicable dependency chain SCE(s) outlined below." >> "$IMPORTSUMMARY"
		echo " " >> "$IMPORTSUMMARY"
		for I in `ls /tmp/*.debs`; do
			echo "Dependencies provided as per "$I":" >> "$IMPORTSUMMARY"
			for E in `cat "$I"`; do
				if cat /tmp/"$TARGET".debdeps | grep "$E" > /dev/null 2>&1; then
					echo "$E" >> "$IMPORTSUMMARY"
					DEPS="1"
				fi
			done
			if [ "$DEPS" != "1" ]; then
				echo "0 packages" >> "$IMPORTSUMMARY"
			fi
			DEPS="0"
			echo " " >> "$IMPORTSUMMARY"
		done
	fi
	totalPKG=`ls /tmp/work | wc -l`
	adjPKG=`cat /tmp/.pkglist | wc -l`
	echo "Total import "$adjPKG" packages ("$totalPKG" - $((totalPKG-adjPKG)) dependency provided):" >> "$IMPORTSUMMARY"
	cat /tmp/.pkglist >> "$IMPORTSUMMARY"
}
##

cleanup() {
	[ -d /tmp/work ] && rm -rf /tmp/work
	[ -d "$SCEDIR" ] && chown -R "$TCUSER":staff "$SCEDIR" > /dev/null 2>&1
	[ -d /tmp ] && chmod 1777 /tmp > /dev/null 2>&1
	[ -d /usr/local/tce.installed ] && chmod 775 /usr/local/tce.installed > /dev/null 2>&1
	[ -d /usr/local/tce.icons ] && chmod 775 /usr/local/tce.icons > /dev/null 2>&1
	[ -d /usr/local/tce.installed ] && chgrp staff /usr/local/tce.installed > /dev/null 2>&1
	[ -d /usr/local/tce.icons ] &&  chgrp staff /usr/local/tce.icons > /dev/null 2>&1
	if ls /tmp/*.debs > /dev/null 2>&1; then 
		rm /tmp/*.debs > /dev/null 2>&1
	fi
	[ -f /tmp/.sceconflict ] && rm /tmp/.sceconflict > /dev/null 2>&1
	[ -f /tmp/.scedeps ] && rm /tmp/.scedeps > /dev/null 2>&1
	[ -f /tmp/.scedebs ] && rm /tmp/.scedebs > /dev/null 2>&1
	[ -f /tmp/.scelist ] && rm /tmp/.scelist > /dev/null 2>&1
	[ -f /tmp/.importfree ] && rm /tmp/.importfree > /dev/null 2>&1
	[ -f /tmp/.pkgexists ] && rm /tmp/.pkgexists > /dev/null 2>&1
	[ -f /tmp/.importdep ] && rm /tmp/.importdep > /dev/null 2>&1
	[ -f /tmp/.newdep ] && rm /tmp/.newdep > /dev/null 2>&1
	if ls /tmp/*.debdeps > /dev/null 2>&1; then 
		rm /tmp/*.debdeps > /dev/null 2>&1
	fi	 
	[ -f /tmp/control.tar.gz ] && rm /tmp/control.tar.gz > /dev/null 2>&1
	[ -f /tmp/data.tar.gz ] && rm /tmp/data.tar.gz > /dev/null 2>&1
	[ -f /tmp/data.tar.bz2 ] && rm /tmp/data.tar.bz2 > /dev/null 2>&1
	[ -f /tmp/data.tar.xz ] && rm /tmp/data.tar.xz > /dev/null 2>&1
	#[ -f /tmp/deb2sce.tar.gz ] && rm /tmp/deb2sce.tar.gz > /dev/null 2>&1
	[ -f /tmp/.prebuiltmd5sumlist ] && rm /tmp/.prebuiltmd5sumlist > /dev/null 2>&1
	[ -f /tmp/select.ans ] && rm /tmp/select.ans > /dev/null 2>&1
	#[ -f /tmp/.nogetdeps ] && rm /tmp/.nogetdeps > /dev/null 2>&1
	[ -f /tmp/.recommends ] && rm /tmp/.recommends > /dev/null 2>&1
	[ -f /tmp/.suggests ] && rm /tmp/.suggests > /dev/null 2>&1
	[ -d "$TCEDIR"/import/"$TARGET" ] && rm -r "$TCEDIR"/import/"$TARGET" > /dev/null 2>&1
	[ -d  /tmp/import/"$TARGET" ] && rm -r /tmp/import/"$TARGET" > /dev/null 2>&1
	[ -f /tmp/.scenoconfig ] && rm /tmp/.scenoconfig > /dev/null 2>&1
	:
}

# Main
unset ONBOOT ONDEMAND FILE
while getopts bo OPTION
do
	case ${OPTION} in
		b) ONBOOT=TRUE ;;
		o) ONDEMAND=TRUE ;;
		*) exit 1 ;;
	esac
done
shift `expr $OPTIND - 1`

if [ -z "$1" ]
then
	echo " "
	echo "${YELLOW}Warning:${NORMAL} You must specify a target, exiting.."
	exit 1
fi
TARGET="$1"

## Update the DEBINX files
# debGetEnv "$2" || exit 1
read DEBINX < /etc/sysconfig/tcedir/import/debinx/debinx
DEBINX="/etc/sysconfig/tcedir/import/debinx/$DEBINX"
read DEBINX_SECURITY < /etc/sysconfig/tcedir/import/debinx/debinx_security
DEBINX_SECURITY="/etc/sysconfig/tcedir/import/debinx/$DEBINX_SECURITY"
echo "* Package index:"
echo "  "$DEBINX""
echo "* Security index:"
echo "  "$DEBINX_SECURITY""
read MIRROR < /opt/debmirror
read MIRROR_SECURITY < /opt/securitymirror
echo "* Main mirror: $MIRROR"
echo "* Security mirror: $MIRROR"

unset META

## Remove unused debinx files in TCEDIR that will cause confusion if their /opt/debextra entries do not exist.
if ls "$TCEDIR"/import/debinx/debinx.* > /dev/null 2>&1; then
	for I in `ls "$TCEDIR"/import/debinx/debinx.*`; do 
	H=`basename "$I" | sed 's:debinx.::'`
	if [ ! -f /opt/debextra/"$H" ]; then
		rm "$I"
	fi 
	done
fi
##

## Determine which repo the package will come from.
if [ -s /tmp/.targetfile ]; then
	echo "* ${YELLOW}$TARGET${NORMAL} is made from your own custom package list."
	#echo "`readlink /tmp/.targetfile`"
	#echo "`readlink /tmp/.targetfile`" > /dev/null 2>&1
	echo -n "`readlink /tmp/.targetfile`"
	META="$TARGET"
elif grep "^$TARGET:" "$DEBINXDIR"/PKGPREBUILTDEP > /dev/null 2>&1; then
	echo "* ${YELLOW}$TARGET${NORMAL} is a dCore premade package."
	META="$TARGET"
elif grep "^Package: $TARGET$" "$TCEDIR"/import/debinx/debinx.* > /dev/null 2>&1; then
	EXTRAINX=`grep -l "^Package: $TARGET$" "$TCEDIR"/import/debinx/debinx.* /dev/null | head -n 1 | cut -f1 -d:`
	MIRRORFILE=`echo "$EXTRAINX" | sed "s:"$TCEDIR"/import/debinx/debinx.::"`
	EXTRAMIRROR=`cat /opt/debextra/"$MIRRORFILE" | awk '{print $1}'`
	EXTRAREPO=`cat /opt/debextra/"$MIRRORFILE" | awk '{print $2}'`
	EXTRAPOOL=`cat /opt/debextra/"$MIRRORFILE" | awk '{print $3}'`
	echo "* ${YELLOW}$TARGET${NORMAL} is an extra repository package from repo:"
	echo "  /opt/debextra/`basename "$EXTRAINX" | cut -f2 -d.`"
	echo "* Mirror:"
	echo "  `echo "$EXTRAMIRROR"`."
	DEBINX=`grep "^Package: $TARGET$" "$TCEDIR"/import/debinx/debinx* /dev/null | head -n 1 | cut -f1 -d:`
	if [ -z `checkextrarepoexists "$TARGET"` ]; then
		echo "* Error: ${YELLOW}$TARGET${NORMAL} is not available for `version | cut -f1 -d:` "$BUILD", exiting.."
		exit 1
	fi
	read DEBINX < /etc/sysconfig/tcedir/import/debinx/debinx
	DEBINX="/etc/sysconfig/tcedir/import/debinx/$DEBINX"
elif grep -q "^Package: $TARGET$" "$DEBINX_SECURITY" > /dev/null 2>&1; then
	echo "* ${YELLOW}$TARGET${NORMAL} is a "$DISTRO" "$REPO" security update package from:"
	echo "  `cat /opt/securitymirror`."
elif grep -q "^Package: $TARGET$" "$DEBINX" > /dev/null 2>&1; then
	echo "* ${YELLOW}$TARGET${NORMAL} is a standard "$DISTRO" "$REPO" package."
elif grep -q "^$TARGET:" "$DEBINXDIR"/PKGADDDEP; then
	if [ ! -f /tmp/.importinteractive ]; then
		echo " "
		echo "  ${YELLOW}$TARGET${NORMAL} is specified in dCore's dependency file list and may be"
		echo "  a metapackage but does not itself exist in our or "$DISTRO"'s repo."
		echo -n "  To proceed press Enter, (q)uit exits:  "
		read ans
		echo " "
		if [ "$ans" == "q" ] || [ "$ans" == "quit" ]; then
			cleanup
			exit 1
		else
			:
		fi
	else
		echo "* ${YELLOW}$TARGET${NORMAL} may be a dCore metapackage of related "$DISTRO" ones."
	fi	
	META="$TARGET"
else
	echo " "
	echo "${YELLOW}Warning:${NORMAL} "$TARGET" is not a standard "$DISTRO","
	echo "         dCore or metapackage, exiting.."
	cleanup
	exit 1
fi
##

## Create the directory where the packages will be downloaded to.
> /var/log/sce.log
[ -d "$TCEDIR"/sce ] || mkdir "$TCEDIR"/sce
[ -d "$TCEDIR"/import/debs ] || mkdir -p "$TCEDIR"/import/debs
DEBS="$TCEDIR"/import/debs
##

## Determine if RAM will be used to unpack packages.
if [ -f /tmp/.importram ]; then
	IMPORT=/tmp/import
	mkdir -p "$IMPORT"
	cd "$IMPORT"
else
	IMPORT="$TCEDIR"/import
	cd "$IMPORT"
fi
##

#[ -f exclude.lst ] || gzip -dc /tmp/deb2sce.xlst.gz > exclude.lst

[ -d "$TARGET" ] && rm -rf "$TARGET"
mkdir "$TARGET"
cd "$TARGET"
> /tmp/import.log	

## Get the dependencies of the desired packages or list of packages.
if [ -s /tmp/.targetfile ]; then
	echo -n "* Gathering dependencies."
	for I in `cat /tmp/.targetfile`; do 
		debGetDeps "$I" > /dev/null 2>&1 & /usr/bin/rotdash $!
	done
	echo " "
else
	echo -n "* Gathering dependencies."
	debGetDeps "$TARGET" > /dev/null 2>&1 & /usr/bin/rotdash $!
	echo " "
fi
##

## Determine if any blocked packages are in the dependency list.
if [ -s /tmp/.blocked ] && [ ! -f /tmp/.importinteractive ]; then
	cat /tmp/.blocked
	echo " "
	echo "${YELLOW}Warning:${NORMAL} The above packages are blocked dependencies of "$TARGET""
	echo "and will not be included in the final SCE, which can cause problems,"
	echo -n "to proceed anyway press Enter, (q)uit exits: "
	read ans
	echo " "
	if [ "$ans" == "q" ] || [ "$ans" == "quit" ]; then
		cleanup
		exit 1
	else
		:
	fi
fi
##

## Create safe backup if sceconfig SAFEBACKUP=TRUE
if cat /etc/sysconfig/sceconfig | grep -v '^#' | grep SAFEBACKUP=TRUE > /dev/null 2>&1; then
	if [ -f /etc/sysconfig/tcedir/sce/"$TARGET".sce ]; then
		BkDir="`date +%Y-%m-%d-%H:%M`"_$TARGET""
		mkdir -p /etc/sysconfig/tcedir/sce/backup/"$BkDir"
		cp -f /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep /etc/sysconfig/tcedir/sce/backup/"$BkDir" > /dev/null 2>&1
		cp -f /etc/sysconfig/tcedir/sce/"$TARGET".sce.lst /etc/sysconfig/tcedir/sce/backup/"$BkDir" > /dev/null 2>&1
		cp -f /etc/sysconfig/tcedir/sce/"$TARGET".sce /etc/sysconfig/tcedir/sce/backup/"$BkDir"
		cp -f /etc/sysconfig/tcedir/sce/"$TARGET".sce.md5.txt /etc/sysconfig/tcedir/sce/backup/"$BkDir"
		echo "* Safe backup created."
	fi
fi

## Get the SCE deps if any and check for duplicates between deps.
if [ -f /tmp/.importdep ]; then
	if [ -f /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep ]; then
		if [ ! -f /tmp/.importinteractive ]; then
			echo " "
			cat /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep
			echo " "
			echo "${YELLOW}WARNING:${NORMAL} Existing "$TARGET".sce.dep file found."
			echo "         Entering (n)o will delete this file."
			echo " "
			echo "Press Enter to use the existing "$TARGET".sce.dep entries above"
			echo -n "for dependencies or enter (n)o to remove or modify dependencies: "
			read ans
			if [ "$ans" == "n" ] || [ "$ans" == "N" ]; then
				echo " "
				echo "Press Enter to create a new "$TARGET".sce.dep file from existing SCE(s),"
				echo -n "or enter (n)o to import "$TARGET" without a dependency file: "
				read ANS
				echo " "
				if [ "$ANS" == "n" ] || [ "$ANS" == "no" ]; then
					rm /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep
				else
					rm /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep
					debGetSceDep "$TARGET" 
				fi
			else
				[ -d usr/local/sce/"$TARGET" ] || mkdir -p usr/local/sce/"$TARGET"
				cp /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep usr/local/sce/"$TARGET"/"$TARGET".dep
				debGetSceDep "$TARGET" 
			fi
		else
			debGetSceDep "$TARGET" 
		fi
	else
		if [ ! -f /tmp/.importinteractive ]; then
			debGetSceDep "$TARGET" 
		fi
	fi
fi


if [ -f /tmp/.sceconflict ]; then
	echo " "
	echo "${YELLOW}WARNING:${NORMAL} "$TARGET" already exists in the dep files of the SCE(s) below,"
	echo "aborting to prevent circular dependency."
	cat /tmp/.sceconflict
	rm /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep > /dev/null 2>&1
	cleanup
	exit 1
fi

if [ -f /tmp/.pkgexists ]; then
	echo " "
	echo "${YELLOW}WARNING:${NORMAL} "$TARGET" already exists in below dependency SCE(s), exiting.."
	cat /tmp/.pkgexists
	rm /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep > /dev/null 2>&1
	cleanup
	exit 1
fi
##

## Bring up list of SCEs that will profide package dependencies for the TARGET one.
if [ -f /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep ]; then
	echo "The SCE(s) below will provide dependencies for "$TARGET".sce."
	echo " "
	for FILE in `cat /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep`; do
		if [ -f /etc/sysconfig/tcedir/sce/"$FILE".sce ]; then
			echo "$FILE"
		fi
	done
	sleep 3
	echo " "
fi
##

## Check free space function when specified.
if [ -f /tmp/.importsize ]; then
	echo -n "* Estimating HD and RAM space needed."
	debGetSize "$TARGET" & /usr/bin/rotdash $!
	echo " "
fi
##

## Echo when not enough free space in RAM or chosen working partition.
if [ -s /tmp/.importfree ]; then
	cat /tmp/.importfree
	echo " "
	echo "${YELLOW}WARNING:${NORMAL} Review warning(s), to import "$TARGET" anyway"
	echo -n "press Enter, (q)uit exits: "
	read ans
	if [ "$ans" == "q" ] || [ "$ans" == "quit" ]; then
		cleanup
		exit 1
	else
		echo " "
		:
	fi
fi
##

## Include in TARGET SCE  only package deps of TARGET that are not provided by chosen dependency SCEs
for I in `ls /tmp/work/`; do grep "^$I$" /tmp/.scedebs > /dev/null 2>&1 || echo "$I" >> /tmp/.pkglist; done
##

## Function to provide a "less" list of packages that will be imported.
if [ -f /tmp/.viewpkgs ]; then
	if [ ! -f /tmp/.importinteractive ]; then
		echo "Press Enter to review the packages "$TARGET".sce will consist of,"
		echo -n "enter (n)o to skip review: "
		read ans
		echo " "
		if [ "$ans" == "n" ] || [ "$ans" == "no" ]; then
			:
		else
			more /tmp/.pkglist
			echo " "
			echo -n "Press Enter to continue with import, (q)uit exits: "
			read ans
			if [ "$ans" == "q" ] || [ "$ans" == "quit" ]; then
				cleanup
				exit 1
			else
				echo " "
				:
			fi
		fi
		echo  "*Proceeding to create $TARGET.sce..."
	else
		echo ""$TARGET".sce will consist of:"
		echo " "
		cat /tmp/.pkglist
		echo " "
	fi
		
fi
##

[ -d usr/local/sce/"$TARGET" ] || mkdir -p usr/local/sce/"$TARGET"

## Copy list file to SCE for integrity check ability.
if [ -f /tmp/.targetfile ]; then
		cp /tmp/.targetfile usr/local/sce/"$TARGET"/"$TARGET".lst
fi
##


HERE=`pwd`
for DEBINFO in `ls -t /tmp/work`; do
	 if [ -f /tmp/.scedebs ]; then
	 	grep "^$DEBINFO$" /tmp/.scedebs > /dev/null 2>&1 && continue
	 fi 

	## Package counter during import session:
	if [ ! "$pkgCOUNT" ]; then
		totalPKG=`ls /tmp/work | wc -l`
		adjPKG=`cat /tmp/.pkglist | wc -l`
		if [ "$totalPKG" != "$adjPKG" ]; then
			echo "* Merging "$adjPKG" packages ("$totalPKG" - $((totalPKG-adjPKG)) dependency provided):" && sleep 3
			totalPKG="$adjPKG"
		else
			echo "* Merging "$totalPKG" packages:" && sleep 3
		fi
		pkgNUM="0"
		pkgCOUNT="TRUE"
	fi
	pkgNUM=$((pkgNUM+1))
	#echo -n ""$pkgNUM"/"$totalPKG" "

	 read FULLPATH < /tmp/work/"$DEBINFO"
	 read IMPORTMIRROR < /opt/tcemirror                                                                             
	 PREBUILTMIRROR="${IMPORTMIRROR%/}/dCore/"$BUILD"/import"
	 IMPORTMIRROR="${IMPORTMIRROR%/}/dCore/import"
	 ## Check to see if package is PREBUILT first.
	 if grep "^${DEBINFO}:" "$DEBINXDIR"/PKGPREBUILTDEP >/dev/null && ! grep "^Package: $DEBINFO$" "$TCEDIR"/import/debinx/debinx.* > /dev/null 2>&1 ; then
	 #if [ -z "$FULLPATH" ] && grep "^${DEBINFO}:" "$DEBINXDIR"/PKGPREBUILTDEP >/dev/null; then
		if grep "^$DEBINFO": "$DEBINXDIR"/PREBUILTMD5SUMLIST > /dev/null 2>&1; then
			cd "$DEBS"
			if [ -f "${DEBINFO}".tar.gz ]; then
				if [ `/bb/md5sum "${DEBINFO}".tar.gz | cut -f1 -d" "` != `grep "^$DEBINFO": "$DEBINXDIR"/PREBUILTMD5SUMLIST | cut -f2 -d" "` ]; then
					echo "* Fetching updated "${DEBINFO}".tar.gz."
					rm "${DEBINFO}".tar.gz* > /dev/null 2>&1
					/bb/wget -O "${DEBINFO}".tar.gz "$PREBUILTMIRROR"/"${DEBINFO}".tar.gz 
					if [ "$?" != 0 ]
					then
						echo " "
						echo "${YELLOW}WARNING:${NORMAL} Failed download of "${DEBINFO}".tar.gz, exiting.."
						cleanup
						exit 1
					fi
				fi
				
			else
				/bb/wget -O "${DEBINFO}".tar.gz "$PREBUILTMIRROR"/"${DEBINFO}".tar.gz 
				if [ "$?" != 0 ]
				then
					echo " "
					echo "${YELLOW}WARNING:${NORMAL} Failed download of "${DEBINFO}".tar.gz, exiting.."
					cleanup
					exit 1
				fi
			fi

			if ! grep "^$DEBINFO": "$DEBINXDIR"/PREBUILTMD5SUMLIST > /dev/null 2>&1; then
				echo " "
				echo "${YELLOW}WARNING:${NORMAL} "$DEBINFO" is missing from the prebuilt md5sum list, exiting.."
				cleanup
				exit 1
			fi 
	
			if [ -f "${DEBINFO}".tar.gz ] && [ `/bb/md5sum "${DEBINFO}".tar.gz | cut -f1 -d" "` == `grep "^$DEBINFO": "$DEBINXDIR"/PREBUILTMD5SUMLIST | cut -f2 -d" "` ]; then	 
				echo "${DEBINFO}: `/bb/md5sum "${DEBINFO}".tar.gz | cut -f1 -d" "`" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".md5sum		
				## Merging:
				echo -n ""$pkgNUM"/"$totalPKG" "
				echo "${YELLOW}"${DEBINFO}"${NORMAL}"
	    	   		tar xf "${DEBINFO}".tar.gz -C "$IMPORT"/"$TARGET" 
				if [ "$?" != 0 ]
				then
					echo " "
					echo "${YELLOW}WARNING:${NORMAL} Failed merging of "${DEBINFO}".tar.gz."
					echo "${DEBINFO}".tar.gz  >> /tmp/import.log
				fi  
			else 
				echo " "
				echo "${YELLOW}WARNING:${NORMAL} md5sum failed for "${DEBINFO}".tar.gz, exiting.."
				cleanup
				exit 1
			fi
			cd "$IMPORT"/"$TARGET"
		else
			if ! grep -q "^$DEBINFO:" "$DEBINXDIR"/PKGPREBUILTDEP; then
				echo ""$pkgNUM"/"$totalPKG" ""${YELLOW}$DEBINFO${NORMAL} is a Debian/Ubuntu meta package or does not exist."
			else
				echo ""$pkgNUM"/"$totalPKG" ""${YELLOW}$DEBINFO${NORMAL} is a dCore custom meta package."
			fi
		fi	
	 elif [ "$FULLPATH" != "" ]; then
	 	THISDEB="${FULLPATH##*/}"
		## Check second to see if package is from extra repo.
		if grep "^Package: $DEBINFO$" "$TCEDIR"/import/debinx/debinx.* > /dev/null 2>&1 ; then
			DEBINX=`grep "^Package: $DEBINFO$" "$TCEDIR"/import/debinx/debinx* /dev/null | head -n 1 | cut -f1 -d:`
			MIRRORFILE=`echo "$DEBINX" | sed "s:"$TCEDIR"/import/debinx/debinx.::"`
			MIRROR=`cat /opt/debextra/"$MIRRORFILE" | cut -f1 -d" "`
			MD5NEW=$(getMd5sum "$DEBINFO")
			if [ -f "$DEBS"/"$THISDEB" ]; then
				MD5OLD=$(/bb/md5sum "$DEBS"/"$THISDEB" | cut -f1 -d" ")
				if [ "$MD5NEW" != "$MD5OLD" ]; then
					rm "$DEBS"/"$THISDEB"
					echo "* Fetching updated "$THISDEB"."
					fetchDeb "$FULLPATH"
				fi
			else
				fetchDeb "$FULLPATH"
			fi
			env pkgNUM="$pkgNUM" totalPKG="$totalPKG" debExtract "$DEBS"/"$THISDEB" "$TARGET"
			if [ "$?" != "0" ]; then
				echo " "
				echo "${YELLOW}WARNING:${NORMAL} Failure to extract "$THISDEB", exiting.."
				cleanup
				exit 1
			fi		
			echo ""$DEBINFO":  "$MD5NEW"" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".md5sum
			read DEBINX < /etc/sysconfig/tcedir/import/debinx/debinx
			DEBINX="/etc/sysconfig/tcedir/import/debinx/$DEBINX"	
			read MIRROR < /opt/debmirror
		## Third check to see if package is available as security update.
		elif grep "^Package: $DEBINFO$" "$DEBINX_SECURITY" > /dev/null 2>&1 ; then
			DEBINX="$DEBINX_SECURITY"
			read MIRROR < /opt/securitymirror
			MD5NEW=$(getMd5sum "$DEBINFO")
			if [ -f "$DEBS"/"$THISDEB" ]; then
				MD5OLD=$(/bb/md5sum "$DEBS"/"$THISDEB" | cut -f1 -d" ")
				if [ "$MD5NEW" != "$MD5OLD" ]; then
					rm "$DEBS"/"$THISDEB"
					echo "* Fetching updated "$THISDEB"."
					fetchDeb "$FULLPATH"
				fi
			else
				fetchDeb "$FULLPATH"
			fi
			env pkgNUM="$pkgNUM" totalPKG="$totalPKG" debExtract "$DEBS"/"$THISDEB" "$TARGET"
			if [ "$?" != "0" ]; then
				echo " "
				echo "${YELLOW}WARNING:${NORMAL} Failure to extract "$THISDEB", exiting.."
				cleanup
				exit 1
			fi
		
			echo ""$DEBINFO":  "$MD5NEW"" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".md5sum
			read DEBINX < /etc/sysconfig/tcedir/import/debinx/debinx
			DEBINX="/etc/sysconfig/tcedir/import/debinx/$DEBINX"	
			read MIRROR < /opt/debmirror
		else 
			## Fourth package is standard Debian repo one.
			read DEBINX < /etc/sysconfig/tcedir/import/debinx/debinx
			DEBINX="/etc/sysconfig/tcedir/import/debinx/$DEBINX"	
			read MIRROR < /opt/debmirror
			MD5NEW=$(getMd5sum "$DEBINFO")
			if [ -f "$DEBS"/"$THISDEB" ]; then
				MD5OLD=$(/bb/md5sum "$DEBS"/"$THISDEB" | cut -f1 -d" ")
				if [ "$MD5NEW" != "$MD5OLD" ]; then
					rm "$DEBS"/"$THISDEB"
					echo "* Fetching updated "$THISDEB"."
					fetchDeb "$FULLPATH"
				fi
			else
				fetchDeb "$FULLPATH"
			fi
			env pkgNUM="$pkgNUM" totalPKG="$totalPKG" debExtract "$DEBS"/"$THISDEB" "$TARGET"
			if [ "$?" != "0" ]; then
				echo " "
				echo "${YELLOW}WARNING:${NORMAL} Failure to extract "$THISDEB", exiting.."
				cleanup
				exit 1
			fi
		
			echo ""$DEBINFO":  "$MD5NEW"" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".md5sum
			read DEBINX < /etc/sysconfig/tcedir/import/debinx/debinx
			DEBINX="/etc/sysconfig/tcedir/import/debinx/$DEBINX"	
			read MIRROR < /opt/debmirror
		fi	
	else
		if ! grep -q "^$DEBINFO:" "$DEBINXDIR"/PKGADDDEP; then
			echo ""$pkgNUM"/"$totalPKG" ""${YELLOW}$DEBINFO${NORMAL} is a Debian/Ubuntu meta package or does not exist."
		else
			echo ""$pkgNUM"/"$totalPKG" ""${YELLOW}$DEBINFO${NORMAL} is a dCore custom meta package."
		fi
	fi
done

cd ..

## List extra repos used to make the SCE.
if grep -v "#" /opt/debextra/* > /dev/null 2>&1; then
	for I in `ls /opt/debextra/`; do grep "#" /opt/debextra/"$I" > /dev/null 2>&1 || cat /opt/debextra/"$I" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".extrarepo; done
fi
##

## Copy *.debs package listing to the SCE.
cp /tmp/*.debs "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/ > /dev/null 2>&1
if [ -f /tmp/"$TARGET".debdeps ]; then
	cp /tmp/"$TARGET".debdeps "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/
fi
##
[ -d "$TARGET"/usr/share/menu ] && rm -r "$TARGET"/usr/share/menu
[ -d "$TARGET"/usr/share/lintian ] && rm -r "$TARGET"/usr/share/lintian

## Remove empty dirs.
busybox find "$TARGET" -mindepth 1 -depth -type d -exec rmdir '{}' + 2>/dev/null

if [ ! -f /tmp/.scenoconfig ]; then
	LOCCONFFILE=/etc/sysconfig/locale.nopurge

	if [ -f "$LOCCONFFILE" ]; then
		echo "* Processing locale.nopurge file."
		if [ -d "$TARGET"/usr/share/locale ]; then
			for I in `find "$TARGET"/usr/share/locale -maxdepth 1 -mindepth 1 -type d`; do I=`basename "$I"`; grep "^$I$" "$LOCCONFFILE" > /dev/null 2>&1 || rm -r "$TARGET"/usr/share/locale/"$I" ; done
		fi
	fi

	DELETEFILE=/etc/sysconfig/sce.purge

	if [ -f "$DELETEFILE" ]; then
		echo "* Processing sce.purge file."
		for I in `cat "$DELETEFILE" | grep -v "#"`; do
			if [ -n "$I" ] && [ -n "$TARGET" ]; then
				rm -rf "$TARGET"/$I > /dev/null 2>&1
			fi
		done
	fi
fi

sed -i "s:APPNAME:$TARGET:g" "$TARGET"/usr/local/tce.installed/* > /dev/null 2>&1
if [ -f "$TCEDIR"/sce/"$TARGET".sce ] && mount | grep " /tmp/tcloop/"$TARGET" " > /dev/null 2>&1; then
	[ -d "$TCEDIR"/sce/update ] || mkdir -p "$TCEDIR"/sce/update
	createImportSummary
	mksquashfs "$TARGET" "$TCEDIR"/sce/update/"$TARGET".sce -noappend
	if [ "$?" == "0" ]; then
		rm -rf "$TARGET"
		cd "$TCEDIR"/sce/update/
		/bb/md5sum "$TARGET".sce > "$TARGET".sce.md5.txt	
		MD5SUMDEBINX=`md5sum "$TCEDIR"/import/debinx/NEWDEBINX | cut -f1 -d" "`
		echo "$MD5SUMDEBINX" > "$TARGET".sce.debinx
		cd "$IMPORT"
		if [ "$ONBOOT" ]; then
			if ! grep -wq "$TARGET" "$TCEDIR"/sceboot.lst
			then
				echo "$TARGET" >> "$TCEDIR"/sceboot.lst
			fi
		fi
		[ "$ONDEMAND" ] && su "$TCUSER" -c "ondemand "$TARGET""
		if [ -s /tmp/.targetfile ]; then
			cat /tmp/.targetfile > "$TCEDIR"/sce/"$TARGET".sce.lst
		else
			[ -f "$TCEDIR"/sce/"$TARGET".sce.lst ] && rm "$TCEDIR"/sce/"$TARGET".sce.lst
		fi
		echo "* Imported "${YELLOW}""$TARGET".sce"${NORMAL}"."
	else
		echo " "
		echo "${YELLOW}WARNING:${NORMAL} Error creating "$TARGET".sce, exiting.." 
		exit 1
	fi
else
	createImportSummary
	mksquashfs "$TARGET" "$TCEDIR"/sce/"$TARGET".sce -noappend
	if [ "$?" == "0" ]; then
		cd "$TCEDIR"/sce/
		/bb/md5sum "$TARGET".sce > "$TARGET".sce.md5.txt
		MD5SUMDEBINX=`md5sum "$TCEDIR"/import/debinx/NEWDEBINX | cut -f1 -d" "`
		echo "$MD5SUMDEBINX" > "$TARGET".sce.debinx	
		cd "$IMPORT"
		if [ "$ONBOOT" ]; then
			if ! grep -wq "$TARGET" "$TCEDIR"/sceboot.lst
			then
				echo "$TARGET" >> "$TCEDIR"/sceboot.lst
			fi
		fi
		[ "$ONDEMAND" ] && su "$TCUSER" -c "ondemand "$TARGET""
		if [ -s /tmp/.targetfile ]; then
			cat /tmp/.targetfile > "$TCEDIR"/sce/"$TARGET".sce.lst
		else
			[ -f "$TCEDIR"/sce/"$TARGET".sce.lst ] && rm "$TCEDIR"/sce/"$TARGET".sce.lst
		fi
		echo "* Imported "${YELLOW}""$TARGET".sce"${NORMAL}"."
	else
		echo " "
		echo "${YELLOW}WARNING:${NORMAL} Error creating "$TARGET".sce, exiting.." 
		exit 1
	fi
fi

cleanup
