#!/bin/bash
# --------------------------------------------
# BuildRoot 1.0 - (C) 1999-2000 Erich Roncarolo
# License: GPL2 (see LICENSE)
# --------------------------------------------

dircomm=$(dirname $0)
comm=$(basename $0)
if [ ! -x "./$comm" ] ; then
	echo "$comm should be executed in BYLD home: cd $dircomm"
	cd $dircomm
fi

. Environment

#
# Some variables
#

# debug informations
# 0 - Nothing
# 1 - Warning
# 2 - Test
# 3 - All
DEBUG=1

while [ "$1" != "" ] ; do
	case "$1" in
	  *=*) eval "$1" ;;
	  *) CONF=$1 ;;
	esac
        shift
done

# home and root
HOUSE=$( pwd )
if [ ! -d ${RD_ROOT} ] ; then 
	mkdir -p ${RD_ROOT} || exit $?
fi
RWD=$( cd ${RD_ROOT} ; pwd )
B_PACK_DIR=$(cd ${PACK_DIR} ; pwd )
RLOG=$HOUSE/$LOGFILE

# Functions

function br_log { echo "$@" >> $RLOG ; }
function br_echo { echo "$@" | tee -a $RLOG ; }
function br_warn  { if [ $DEBUG -ge 1 ] ; then echo "$@" | tee -a $RLOG ; else echo "$@" >> $RLOG ; fi ; }
function br_check { if [ $DEBUG -ge 2 ] ; then echo "$@" | tee -a $RLOG ; else echo "$@" >> $RLOG ; fi ; }
function br_debug { if [ $DEBUG -ge 3 ] ; then echo "$@" | tee -a $RLOG ; else echo "$@" >> $RLOG ; fi ; }

test "$RM_LOG" = "true" && rm $RLOG 2> /dev/null

br_log
br_log "******" $(date) "******"

# Set configuration
if [ "$CONF" ] ; then
	case $CONF in
	${CONF_DIR}/*) ;;
	*) CONF=${CONF_DIR}/${CONF} ;;
	esac
else
	br_echo
	br_echo "Usage: $0 configuation"
	br_echo "Configuration files available in $CONF_DIR:"
	for f in $(ls $CONF_DIR) ; do
		test -f $CONF_DIR/$f && br_echo " - $f"
	done
	br_echo
	exit 2
fi

# Don't touch!
PUTDONE=false


####################################
#
# Tree loop
#
br_echo
br_echo "----------------------------"
if [ ${DEBUG} -ge 2 ] ; then
	br_echo "Checking configuration..."
	br_echo " (${CONF})"
else
	br_echo "Building root directory..."
fi
br_echo "----------------------------"
br_echo

if [ ! -f ${CONF} ] ; then
	br_echo "*** Fatal error: configuration file ${CONF} does not exist! ***"
	br_echo
	exit 1
fi

br_echo "Checking dependencies"
while read Pack dummy ; do
	if [ "$Pack" ] ; then
		case "${Pack}" in
		\#*) ;; # Ignore comment
		*) PACK=${B_PACK_DIR}/${Pack}
		if [ ! -d ${PACK} ] ; then
			br_warn "*** Warning: package ${PACK} does not exist: ignoring..."
			WARN_DEP=true
			continue
		fi
		#source $PACK
		br_check "Checking package ${Pack} dependencies... "
		DEPEND="${DEPEND} ${Pack}"
		while read dep ; do
			test -z "$dep" && continue
			case $dep in
			\#*) continue ;;
			*/*) depaux=${dep} ;;
			*)   depaux=$(cat ${B_PACK_DIR}/.dep/${dep}) ;;
			esac
			for xdep in ${depaux} ; do
				for prec in ${DEPEND} ; do
					test "$xdep" = "$prec" && continue 3
				done
			done
			br_echo "Warning: ${Pack} depends on $dep"
			WARN_DEP=true
		done < ${PACK}/Depend
		br_check "done."
		;;
		esac
	fi
done < ${CONF}
if [ "${WARN_DEP}" = "true" ] ; then
	br_echo
	br_echo "*** Some dependencies are NOT OK ***"
	br_echo -n "*** Press ctrl-c now to stop or press [enter] to continue..."
	read dummy
fi
br_echo "Dependencies OK"

if [ "${CLEAN_BEFORE_BUILD}" = "true" ] ; then
	br_check "Cleaning ${RD_ROOT}... "
	br_check "# rm -R ${RWD}/* &> /dev/null"
	if [ ${DEBUG} -lt 2 ] ; then
		mv ${RWD}/CVS ${RWD}/.CVS
		rm -R ${RWD}/* &> /dev/null
		mv ${RWD}/.CVS ${RWD}/CVS
	fi
	br_check "done."
fi

#if [ ! -x $HOUSE/ReadSymLink ] ; then
#	br_check "Compiling ReadSymLink... "
#	br_check "# gcc -o $HOUSE/ReadSymLink $HOUSE/ReadSymLink.c"
#	br_check "# strip $HOUSE/ReadSymLink"
#	br_check "# chmod 755 $HOUSE/ReadSymLink"
#	if [ ${DEBUG} -lt 2 ] ; then
#		gcc -o $HOUSE/ReadSymLink $HOUSE/ReadSymLink.c
#		strip $HOUSE/ReadSymLink
#		chmod 755 $HOUSE/ReadSymLink
#	fi
#	br_check "done."
#fi

rm ${TMPFILE} &> /dev/null
mkdir -p $TMPDIR
rm $TMPDIR/* &> /dev/null

##########################
#
# Read configuration file
#

br_echo
while read Pack dummy ; do
	if [ "$Pack" ] ; then
		case "${Pack}" in
		\#*) ;;
		*) PACK=${B_PACK_DIR}/${Pack}
		if [ ! -d ${PACK} ] ; then
			br_echo "*** Warning: package ${PACK} does not exist ***"
			br_echo -n "*** Press ctrl-c now to stop or press [enter] to continue..."
			read dummy < /dev/tty
			continue
		fi
		for prec in ${INSTALLED} ; do
			if [ "${Pack}" = "$prec" ] ; then
				ALREADY_INSTALLED=${Pack}
				break
			fi
		done
		#source $PACK
		if [ ${DEBUG} -lt 2 ] ; then
			if [ "${Pack}" = "${ALREADY_INSTALLED}" ] ; then 
				br_warn "Warning: package ${Pack} already installed"
			else
				br_echo -n "Building package ${Pack}... "
				( cd $RWD; PACK_WD=$PACK PATH=$PACK:$HOUSE:$PATH ; source ${PACK}/Buildfile )
			fi
		else
			if [ "${Pack}" = "${ALREADY_INSTALLED}" ] ; then 
				br_warn "Warning: package ${Pack} already installed"
			else
				br_echo "Building package ${Pack}... "
				br_echo "( cd $RWD; PACK_WD=$PACK PATH=$PACK:$HOUSE:$PATH ; source ${PACK}/Buildfile )"
			fi
		fi
		INSTALLED="${INSTALLED} ${Pack}"
		br_echo "done."
		;;
		esac
	fi
done < ${CONF}
br_echo

#######################################
#
# Putting libraries in /lib
#

if [ ${DEBUG} -le 1 ] ; then
	br_echo -n "Getting dinamic libraries and put in ${RD_ROOT}/lib... "
	PUTDONE=true
else
	br_echo "Getting dinamic libraries and put in ${RD_ROOT}/lib... "
fi

# Create /lib
if [ ! -d ${RWD}/lib ] ; then
	if [ -e ${RWD}/lib ] ; then
		br_echo "Error: ${RWD}/lib exists and is not a directory"
		exit 1
	fi
	br_debug "Creating dir ${RWD}/lib"
	br_check "# mkdir -p ${RWD}/lib"
	if [ ${DEBUG} -ge 2 ] ; then
		mkdir -p ${RWD}/lib
	fi
fi
br_debug "Entering dir ${RWD}/lib"
test "${DEBUG}" -lt 2 && cd ${RWD}/lib
#
# Following code is deprecated
#
#unset link swd icomm comm
#for src in $(sort ${TMPFILE} | uniq) ; do
#	unset link swd icomm comm
#
#	# accept only line starting with a slash /
#	case ${src} in
#	/*) dest=$(basename ${src}) ;;
#	*) continue ;;
#	esac
#
#	# follow symbolic links
#	link=${src}
#	while [ "${link}" != "-" -a -L ${link} ] ; do
#		br_debug "- Now using ${link} ..."
#		linkc=$(${HOUSE}/ReadSymLink ${link})
#		br_debug "- ${link} -> ${linkc} ..."
#		case ${linkc} in
#		/*) link=${linkc}
#		;;
#		*) swd=$(dirname ${link})
#			link=${swd}/${linkc}
#		;;
#		esac
#	done
#	ldest=$(basename ${link})
#
#	if [ ! -e ${link} ] ; then
#		br_warn "Warning! ${link} not found: ignored"
#		continue
#	fi
#
#	test "${link}" != "${src}" -a -z "${icomm}" && icomm="cp ${link} ${ldest} ; test -e ${dest} -o -L ${dest} || ln -s ${ldest} ${dest}"
#	test "${icomm}" || icomm="cp -u ${src} ${dest}"
#	test -z "${comm}" -a "${icomm}" != "-" && comm=${icomm}
#	test "${comm}" && br_debug "Executing command: ${comm}"
#	test ${DEBUG} -lt 2 && bash -c "${comm}"
#	test  ! -d ${dest} -a -x ${dest} -a ${DEBUG} -lt 2 && strip ${dest}
#done

#
# Now we use mklibs.sh to take libraries
# Only executables files in */bin and */sbin directory are passed to mklibs
#
br_debug "mklibs.sh: An automated way to create a minimal /lib/ directory."
br_log "${HOUSE}/mklibs.sh -d ${RWD}/lib $(find ${RWD} -type f -perm +111 -path \"*bin*\")"
test "${DEBUG}" -lt 2 && ${HOUSE}/mklibs.sh -d ${RWD}/lib $(find ${RWD} -type f -perm +111 -path "*bin*")


# set correct owner
chown -R 0.0 ${RWD}/lib/

# log which files uses libs...
br_log ; br_log "--- Libraries used by files ---"
for src in $(sort ${TMPFILE} | uniq) ; do
	# accept only line starting with a slash /
	case ${src} in
	/*) test "${last_src}" = "${src}" && continue ;;
	*) continue ;;
	esac
	br_log "$( basename ${src} ) => ${src} :"
	br_log -e "\t" $(cd $TMPDIR ; grep -l ${src} *)
	last_src=${src}
done
br_log "---"
test "${PUTDONE}" = "true" && br_echo "done."

# remove tmp files
#test ${DEBUG} -lt 2 && rm ${TMPFILE}
test ${DEBUG} -lt 2 && cd ${HOUSE}

if [ ${DEBUG} -ge 2 ] ; then
	br_echo
	cat ${TMPFILE}
	br_echo
	br_echo "Configuration ${CONF} checked."
	br_echo
	exit 0
fi

#br_echo -n "Pak testpak: "
#$HOUSE/Pak testpak && mv testpak.tgz root/var/

#
# Finish
#

br_echo
br_echo "*** Root builded. Now use ./MakeImage to create root image file."
br_echo
