#!/bb/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`
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

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
}


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
			
}

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
}

getMd5sum() {
> /tmp/"$1".pkglist
grep -B 1 -A 8 "^Package: $1$" "$DEBINX" |  grep -B8 "^$" > /tmp/"$1".pkglist
grep "^MD5sum:" /tmp/"$1".pkglist | cut -f2 -d" " 
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] 
			}
		
		}
		
	} ' < "$DEBINX"
}


cleanup() {
	rm -rf /tmp/work
	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/.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
	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.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/PKGADDDEP ] && sudo rm /tmp/PKGADDDEP
	[ -f /tmp/PKGEXTRAFILEMD5SUMLIST ] && sudo rm /tmp/PKGEXTRAFILEMD5SUMLIST
	[ -f /tmp/PKGDATAFILEMD5SUMLIST ] && sudo rm /tmp/PKGDATAFILEMD5SUMLIST
	[ -f /tmp/PKGEXTRAFILES ] && sudo rm /tmp/PKGEXTRAFILES
	[ -f /tmp/PKGEXTRAREPODEP ] && sudo rm /tmp/PKGEXTRAREPODEP
	[ -f /tmp/PKGPREBUILTDEP ] && sudo rm /tmp/PKGPREBUILTDEP
	[ -f /tmp/PREBUILTMD5SUMLIST ] && sudo rm /tmp/PREBUILTMD5SUMLIST
}

# Main
[ -d /tmp/work ] && sudo rm -r /tmp/work
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"

# debGetEnv "$2" || exit 1
read DEBINX < /tmp/debinx
DEBINX="/etc/sysconfig/tcedir/$DEBINX"
echo " "
echo " "
echo "Using Package Index: $DEBINX"
echo " "
read MIRROR < /opt/debmirror
echo "Using "$DISTRO" 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"/debinx.* > /dev/null 2>&1; then
	for I in `ls "$TCEDIR"/debinx.*`; do 
	H=`basename "$I" | sed 's:debinx.::'`
	if [ ! -f /opt/debextra/"$H" ]; then
		rm "$I"
	fi 
	done
fi


if [ -s /tmp/.targetfile ]; then
	echo "$TARGET is from your own custom package list:"
	echo "`readlink /tmp/.targetfile`"
	META="$TARGET"

elif sudo grep -q "^$TARGET:" /tmp/PKGADDDEP && ! sudo grep "^Package: $TARGET" "$DEBINX" > /dev/null 2>&1; then
	echo "$TARGET is a meta package of related "$DISTRO" ones."
	META="$TARGET"
elif sudo grep "^Package: $TARGET$" "$TCEDIR"/debinx.* > /dev/null 2>&1; then
	EXTRAINX=`grep -l "^Package: $TARGET$" "$TCEDIR"/debinx.* | head -n 1 | cut -f1 -d:`
	MIRRORFILE=`echo "$EXTRAINX" | sed "s:"$TCEDIR"/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"`."
elif sudo grep "^$TARGET:" /tmp/PKGPREBUILTDEP > /dev/null 2>&1; then
	echo "$TARGET is a dCore premade package."
	META="$TARGET"
elif sudo grep -q "^Package: $TARGET" "$DEBINX" > /dev/null 2>&1; then
	echo "$TARGET is a standard "$DISTRO" "$REPO" package."
else
	echo "$TARGET is not a standard "$DISTRO", dCore precompiled, or meta package, exiting.."
	cleanup 
	exit 1
fi


> /var/log/sce.log
[ -d "$TCEDIR"/sce ] || mkdir "$TCEDIR"/sce
[ -d "$TCEDIR"/import/debs ] || mkdir -p "$TCEDIR"/import/debs
DEBS="$TCEDIR"/import/debs

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" ] || mkdir "$TARGET"
cd "$TARGET"
> /tmp/import.log	

if [ -s /tmp/.targetfile ]; then
	echo "Gathering dependency info.."
	for I in `echo "$TARGET" && cat /tmp/.targetfile`; do 
		debGetDeps "$I" > /dev/null 2>&1
	done &
	/usr/bin/rotdash $!
else
	echo "Gathering dependency info.."
	debGetDeps "$TARGET" > /dev/null 2>&1 &
	/usr/bin/rotdash $!
fi

if [ -s /tmp/.blocked ]; then
	cat /tmp.blocked
	echo -n "The above packages are blocked dependencies of $TARGET and will not be included in \
the final SCE. This can cause problems.  Proceed anyway? (y/N): "
	read ans
	if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
		:
	else
		echo "Exiting.."
		cleanup
		exit 1
	fi
fi

if [ -f /tmp/.importdep ]; then
	debGetSceDep "$TARGET"
fi

if [ -f /tmp/.pkgexists ]; then
	echo "$TARGET already exists in below dependency sce's, aborting."
	cat /tmp/.pkgexists
	cleanup
	exit 1
fi



if [ -f /etc/sysconfig/tcedir/sce/"$TARGET".sce.dep ]; then
	echo
	echo
	echo "The below SCE's in your SCE directory will be used as"
	echo "to 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
	echo
	echo
fi

if [ -f /tmp/.importsize ]; then
	echo "Determining HD and RAM space needed.."
	debGetSize "$TARGET" &
	/usr/bin/rotdash $!
fi

if [ -s /tmp/.importfree ]; then
	cat /tmp/.importfree
	echo "The above errors have occured. Do you wish to continue"
	echo -n "importing "$TARGET" despite the warnings? (y/N):"
	read ans
	if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
		:
	else
		echo "Exiting.."
		cleanup
		exit 1
	fi
fi

for I in `ls /tmp/work/`; do grep "^$I$" /tmp/.scedebs > /dev/null 2>&1 || echo "$I" >> /tmp/.pkglist; done


if [ ! -f /tmp/.importinteractive ]; then
	echo "Do you want to review the list of packages that $TARGET.sce"
	echo "will consist of? Enter y to view and q to exit reading"
	echo -n "the package list. (y/N): "
	read ans
	if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
		less /tmp/.pkglist
	fi
	echo
	echo
	echo -n "Proceed to create $TARGET.sce? (y/N): "
	read ans
	if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
		:
	else
		echo "Exiting.."
		cleanup
		exit 1
	fi
fi

mkdir -p usr/local/sce/"$TARGET"

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 
	 read FULLPATH < /tmp/work/"$DEBINFO"
	 read IMPORTMIRROR < /opt/tcemirror                                                                             
	 PREBUILTMIRROR="${IMPORTMIRROR%/}/dCore/"$BUILD"/import"
	 IMPORTMIRROR="${IMPORTMIRROR%/}/dCore/import"
	 if grep "^${DEBINFO}:" /tmp/PKGPREBUILTDEP >/dev/null && ! grep "^Package: $DEBINFO$" "$TCEDIR"/debinx.* > /dev/null 2>&1 ; then
	 #if [ -z "$FULLPATH" ] && grep "^${DEBINFO}:" /tmp/PKGPREBUILTDEP >/dev/null; then
		if grep "^$DEBINFO": /tmp/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": /tmp/PREBUILTMD5SUMLIST | cut -f2 -d" "` ]; then
					echo "Fetching updated "${DEBINFO}".tar.gz.."
					rm "${DEBINFO}".tar.gz*
					/bb/wget -O "${DEBINFO}".tar.gz "$PREBUILTMIRROR"/"${DEBINFO}".tar.gz
				fi
				
			else
				/bb/wget -O "${DEBINFO}".tar.gz "$PREBUILTMIRROR"/"${DEBINFO}".tar.gz 
			fi
	
			if [ -f "${DEBINFO}".tar.gz ] && [ `/bb/md5sum "${DEBINFO}".tar.gz | cut -f1 -d" "` == `grep "^$DEBINFO": /tmp/PREBUILTMD5SUMLIST | cut -f2 -d" "` ]; then	 
				echo "${DEBINFO}: `/bb/md5sum "${DEBINFO}".tar.gz | cut -f1 -d" "`" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".md5sum		  
				echo "Merging "${DEBINFO}":"
	    	   		tar xf "${DEBINFO}".tar.gz -C "$IMPORT"/"$TARGET"        		  
			else 
				echo "md5sum failed for "${DEBINFO}".tar.gz, exiting.."
				cleanup
				exit 1
			fi
			cd "$IMPORT"/"$TARGET"
		fi	
	 elif [ "$FULLPATH" != "" ]; then
	 	THISDEB="${FULLPATH##*/}"
		if grep "^Package: $DEBINFO$" "$TCEDIR"/debinx.* > /dev/null 2>&1 ; then
			DEBINX=`grep "^Package: $DEBINFO$" "$TCEDIR"/debinx* | head -n 1 | cut -f1 -d:`
			MIRRORFILE=`echo "$DEBINX" | sed "s:"$TCEDIR"/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
			sudo debExtract "$DEBS"/"$THISDEB" "$TARGET"
			if [ "$?" != "0" ]; then
				echo "Failure to extract "$THISDEB", exiting.."
				cleanup
				exit 1
			fi		
			echo ""$DEBINFO":  "$MD5NEW"" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".md5sum
			read DEBINX < /tmp/debinx
			DEBINX="/etc/sysconfig/tcedir/$DEBINX"	
			read MIRROR < /opt/debmirror
		else
			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
			sudo debExtract "$DEBS"/"$THISDEB" "$TARGET"
			if [ "$?" != "0" ]; then
				echo "Failure to extract "$THISDEB", exiting.."
				cleanup
				exit 1
			fi
		
			echo ""$DEBINFO":  "$MD5NEW"" >> "$IMPORT"/"$TARGET"/usr/local/sce/"$TARGET"/"$TARGET".md5sum
			read DEBINX < /tmp/debinx
			DEBINX="/etc/sysconfig/tcedir/$DEBINX"	
			read MIRROR < /opt/debmirror
		fi	
	 fi
done



cd ..
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

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

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
	mksquashfs "$TARGET" "$TCEDIR"/sce/update/"$TARGET".sce -noappend
	if [ "$?" == "0" ]; then
		cd "$TCEDIR"/sce/update/
		/bb/md5sum "$TARGET".sce > "$TARGET".sce.md5.txt	
		cd "$IMPORT"
	fi
	
else
	mksquashfs "$TARGET" "$TCEDIR"/sce/"$TARGET".sce -noappend
	if [ "$?" == "0" ]; then
		cd "$TCEDIR"/sce/
		/bb/md5sum "$TARGET".sce > "$TARGET".sce.md5.txt	
		cd "$IMPORT"
	fi
fi

if [ "$?" == "0" ]
then
	#mv "$TARGET".sce "$TCEDIR"/sce/.
	sudo rm -rf "$TARGET"
	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 "Done."
else
	echo "Failed."
fi

cleanup
