#!/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'
alias mount='/bb/mount'
> /tmp/.pkglist

TCUSER=`cat /etc/sysconfig/tcuser`
sudo chown "$TCUSER":staff /tmp
sudo chmod 1777 /tmp
checkroot
BUILD=`getBuild`
if [ "$BUILD" == "x86" ]; then
	DEBBUILD="i386"
elif [ "$BUILD" == "armv7" ]; then
	DEBBUILD="armhf"
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`
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
	chown root.staff "$IMPORT"/"$TARGET"/usr/local/tce.installed
}

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

		sudo /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 -m 1 -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 0
		} 

	} ' < "$DEBINX"
}
##

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

# 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 "You must specify a target."
	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 " "
echo "Using Package Index:"
echo ""$DEBINX""
echo " "
echo "Using Security Index:"
echo ""$DEBINX_SECURITY""
echo " "
read MIRROR < /opt/debmirror
read MIRROR_SECURITY < /opt/securitymirror
echo "Using "$DISTRO" Mirror: $MIRROR"
echo " "
echo "Using "$DISTRO" Security Mirror: $MIRROR"
echo " "
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 "$TARGET is from your own custom package list."
	echo "`readlink /tmp/.targetfile`"
	META="$TARGET"
elif sudo grep "^$TARGET:" "$DEBINXDIR"/PKGPREBUILTDEP > /dev/null 2>&1; then
	echo "$TARGET is a dCore premade package."
        echo " "
	META="$TARGET"
elif sudo 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 "$TARGET is a "$DISTRO" `echo "$EXTRAREPO"` `echo "$EXTRAPOOL"` package from `echo "$EXTRAMIRROR"`."
        echo " "
elif sudo grep -q "^Package: $TARGET$" "$DEBINX_SECURITY" > /dev/null 2>&1; then
	echo "$TARGET is a "$DISTRO" "$REPO" security update package from `cat /opt/securitymirror`."
        echo " "
elif sudo grep -q "^Package: $TARGET$" "$DEBINX" > /dev/null 2>&1; then
	echo "$TARGET is a standard "$DISTRO" "$REPO" package."
        echo " "
elif sudo grep -q "^$TARGET:" "$DEBINXDIR"/PKGADDDEP; then
	echo "$TARGET is a metapackage of related "$DISTRO" ones."
        echo " "
	META="$TARGET"
else
	echo ""$TARGET" is not a standard "$DISTRO", 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 `echo "$TARGET" && cat /tmp/.targetfile`; do 
		debGetDeps "$I" > /dev/null 2>&1 & /usr/bin/rotdash $!
	done
	echo " " && echo " "
else
	echo -n "Gathering dependencies."
	debGetDeps "$TARGET" > /dev/null 2>&1 & /usr/bin/rotdash $!
	echo " " && 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 "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, (n)o exits: "
	read ans
	echo " "
	if [ "$ans" == "y" ] || [ "$ans" == "Y" ] || [ "$ans" == "" ]; then
		:
	else
		cleanup
		exit 1
	fi
fi
##

## Determine if 'Recommended' packages are desired.
if [ -f /tmp/.recommends ]; then
	if [ -s /tmp/.targetfile ]; then
		for I in `cat /tmp/.targetfile`; do
			debGetRecommends "$I" > /dev/null 2>&1 &
		done 
	else
		debGetRecommends "$1" > /dev/null 2>&1 &
	fi
	/usr/bin/rotdash $!
	if [ -s /tmp/sce.recommends ]; then
		[ -d usr/local/sce/"$TARGET" ] || mkdir -p usr/local/sce/"$TARGET"
		touch usr/local/sce/"$TARGET"/recommends
		echo -n "Gathering Recommended packages dependencies."
		for I in `cat /tmp/sce.recommends | sort | uniq`; do 
			debGetDeps "$I" > /dev/null 2>&1
		done &
	/usr/bin/rotdash $!
	echo " " && echo " "
	fi
fi

## Determine if 'Suggested' packages are desired.
if [ -f /tmp/.suggests ]; then
	if [ -s /tmp/.targetfile ]; then
		for I in `cat /tmp/.targetfile`; do
			debGetSuggests "$I" > /dev/null 2>&1 &
		done 
	else
		debGetSuggests "$1" > /dev/null 2>&1 &
	fi
	/usr/bin/rotdash $!
	if [ -s /tmp/sce.suggests ]; then
		[ -d usr/local/sce/"$TARGET" ] || mkdir -p usr/local/sce/"$TARGET"
		touch usr/local/sce/"$TARGET"/suggests
		echo -n "Gathering Suggested packages dependencies."
		for I in `cat /tmp/sce.suggests | sort | uniq`; do 
			debGetDeps "$I" > /dev/null 2>&1
		done &
		/usr/bin/rotdash $!
		echo " " && echo " "
	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
			cat /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep
			echo " "
			echo "Press Enter to use the existing "$TARGET".sce.dep entries above"
			echo "for dependencies or enter (n)o to remove or modify dependencies." && sleep 3
			echo " "
			echo -n "${YELLOW}WARNING:${NORMAL} Entering (n)o will delete existing "$TARGET".sce.dep file: "
			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" == "N" ]; then
					sudo rm /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep
				else
					sudo 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 ""$TARGET" already exists in the dep files of the SCE(s) below,"
	echo "aborting to prevent circular dependency."
	cat /tmp/.sceconflict
	cleanup
	exit 1
fi

if [ -f /tmp/.pkgexists ]; then
	echo " "
	echo ""$TARGET" already exists in below dependency SCEs, aborting."
	echo " "
	cat /tmp/.pkgexists
	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 "Estimating HD and RAM space needed..."
	debGetSize "$TARGET" & /usr/bin/rotdash $!
fi
##

## Echo when not enough free space in RAM or chosen working partition.
if [ -s /tmp/.importfree ]; then
	cat /tmp/.importfree
	echo " "
	echo "Please review warning(s), to import "$TARGET" anyway"
	echo -n "press Enter, (n)o exits: "
	read ans
	if [ "$ans" == "y" ] || [ "$ans" == "Y" ] || [ "$ans" == "" ]; then
		echo " "
		:
	else
		cleanup
		exit 1
	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
	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" == "y" ] || [ "$ans" == "Y" ] || [ "$ans" == "" ]; then
		more /tmp/.pkglist
		sleep 3
		echo " "
	fi
	echo  "Proceeding to create $TARGET.sce..."
	echo " "
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
		echo " "
		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 "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 "Failed download of "${DEBINFO}".tar.gz, exiting.."
					cleanup
					exit 1
				fi
			fi

			if ! grep "^$DEBINFO": "$DEBINXDIR"/PREBUILTMD5SUMLIST > /dev/null 2>&1; then
				echo " "
				echo ""$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 "Failed merging of "${DEBINFO}".tar.gz."
					echo "${DEBINFO}".tar.gz  >> /tmp/import.log
				fi  
			else 
				echo " "
				echo "md5sum failed for "${DEBINFO}".tar.gz, exiting.."
				cleanup
				exit 1
			fi
			cd "$IMPORT"/"$TARGET"
		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=$(getMd5sum1 "$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 "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 sudo 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 "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 "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	
	 fi
done



cd ..
## Move *.debs package listing to the SCE.
mv /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
		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 || sudo rm -r "$TARGET"/usr/share/locale/"$I" ; done
		fi
	fi

	DELETEFILE=/etc/sysconfig/sce.purge

	if [ -f "$DELETEFILE" ]; then
		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 ] && busybox mount | grep " /tmp/tcloop/"$TARGET" " > /dev/null 2>&1; then
	[ -d "$TCEDIR"/sce/update ] || mkdir -p "$TCEDIR"/sce/update
	mksquashfs "$TARGET" "$TCEDIR"/sce/update/"$TARGET".sce -noappend
	if [ "$?" == "0" ]; then
		sudo 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
		fi
		echo " "
		echo "Imported "${YELLOW}""$TARGET".sce"${NORMAL}"."
	else
		echo " "
		echo "Error creating "$TARGET".sce, exiting.." 
		exit 1
	fi
else
	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
		fi
		echo " "
		echo "Imported "${YELLOW}""$TARGET".sce"${NORMAL}"."
	else
		echo " "
		echo "Error creating "$TARGET".sce, exiting.." 
		exit 1
	fi
fi

cleanup