#!/bin/bash -x
# Distributed under the terms of the GNU General Public License v2
#
# Latest version of this file can be downloaded from:
#  http://www.emdebian.org/repos/current/emdebian/trunk/buildcross/trunk/
# but it might need some fix for you to work.
# ----------------------------------------------------------------------
# Copyright 1999-2007 Emdebian

source conf_vars.sh

PKG=$1
ARCH=$2

if [ ${ARCH} == "armel" ]; then
	MIRROR=${MIRROR:="http://ftp.gnuab.org/debian/"}

fi

if [ ! -d $LOGPATH ]; then
	mkdir -p $LOGPATH
fi

# Sets build as failed
echo 1 > $LOGPATH/$HOST-$ARCH-$PKG.log


#----------------------------------------------------------------------
# Useful shell functions

#----------------------------------------------------------------------
# check build-deps
checkinstalled () {
	while [ -n "$1" ]; do
		dpkg -l "$1" |grep -q "^ii" || {
			echo "$1 is not installed."
			apt-get -y --force-yes install $1
		}
		shift
	done
}

sanitycheck () {
	# sanity check build environment
	echo "Sanity check..."
	checkinstalled dpkg-cross
#	checkinstalled wget
	#checkinstalled dctrl-tools 
	checkinstalled grep-dctrl 
	checkinstalled sudo
	checkinstalled fakeroot
	checkinstalled dpatch
	checkinstalled patchutils
	checkinstalled tar
	checkinstalled bzip2
	checkinstalled lsb-release
	checkinstalled autoconf
	checkinstalled autoconf2.13
	checkinstalled automake1.9
	checkinstalled libtool
	checkinstalled autogen
	checkinstalled gawk
	checkinstalled bison
	checkinstalled flex
	checkinstalled realpath
	checkinstalled texinfo
	checkinstalled devscripts
	checkinstalled reprepro
	checkinstalled less 
	checkinstalled coreutils
	checkinstalled automake1.4
	checkinstalled automake1.7
	checkinstalled dh-make
	checkinstalled debhelper
	checkinstalled apt-cross
	checkinstalled emdebian-tools
	
	# Following lines are gdb dependencies
	checkinstalled tetex-bin 
	checkinstalled libncurses5-dev 
	checkinstalled libreadline5-dev 
	#checkinstalled gcj 
	checkinstalled gobjc 
	checkinstalled cdbs  
 	checkinstalled quilt 
 	checkinstalled type-handling
	echo "Sanity check passed."
}

#----------------------------------------------------------------------
# find full version string: version <binarypackage>
# XXX: What about epochs?
version () {
	rmadison -a ${ARCH} ${1} | grep ${SUITE} | cut -d'|' -f2 | tr -d ' ' | cut -d'+' -f1 |sed 's/1://'|tail -n 1
}

srcver () {
	local x=$(apt-cache showsrc $1 |grep ^Version: |sed 's/^Version: //' |sort -bru |head -1)
	echo $(echo $x |sed 's/\(.*\)\(-[0-9]*$\)/\1/' |sed 's/1://')
}

# find upstream version string: upstreamversion <binarypackage>
upstreamversion () {
	echo $(version $1 |sed 's/\(.*\)\(-[0-9]*$\)/\1/')
}

# find debian revision string: debianrevision <binarypackage>
debianrevision () {
	echo $(version $1 |sed 's/\(.*-\)\([0-9]*$\)/\2/')
}

# find sourcepackage: sourcepackage <binarypackage>
sourcepackage () {
	local x=$(grep-status -PX $1 -s Source: -n)
	local y=$1
	echo ${x:=$y}
}

# find source directory: sourcedir <sourcepackage>
sourcedir () {
	echo $1-$(srcver $1)
}


# make cross ${ARCH} package: make-cross-package <binarypackage>
make-cross-package () {
	local _version=$(version $1)
#	apt-cross -v -v -a ${ARCH} -S ${SUITE} -m ${MIRROR} -i $1 
	apt-cross -v -v -a ${ARCH} -S ${SUITE} -m ${MIRROR} -i $1 
	apt-cross -v -v -a ${ARCH} -S ${SUITE} -m ${MIRROR} -f -b $1 
	apt-cross -v -v -a ${ARCH} -S ${SUITE} -m ${MIRROR} -f -b $1 
	# apt-cross -v -v --force -a ${ARCH} -S ${SUITE} -m ${MIRROR} -i $1 
	# apt-cross -v -v --force -a ${ARCH} -S ${SUITE} -m ${MIRROR} -b $1 
	# rm -rf ${1}_${_version}_${ARCH}.deb
		
}


# build and install libraries needed to build the cross toolchain
build-libs () {
	
	# Lets get kernel info; linux kernel headers
	make-cross-package linux-libc-dev
        
	# Lets get glibc
	if [ ${ARCH} = "alpha" ] || [ ${ARCH} = "ia64" ] ; then
                make-cross-package libc6.1 
                make-cross-package libc6.1-dev 
	else
		make-cross-package libc6
		make-cross-package libc6-dev
	fi
	
	# Build dependencies
	if [ ${ARCH} = "ia64" ] ; then
		make-cross-package libatomic-ops-dev
		make-cross-package libunwind7
		make-cross-package libunwind7-dev
	fi
	
	if [ ${ARCH} = "powerpc" ]; then
		make-cross-package libc6-ppc64
		make-cross-package libc6-dev-ppc64
	fi

	if [ ${ARCH} = "i386" ]; then
		make-cross-package libc6-amd64
		make-cross-package lib64gcc1 
		make-cross-package libc6-dev-amd64
	fi
		
	if [ ${ARCH} = "sparc" ]; then
		make-cross-package libc6-sparc64
		make-cross-package libc6-dev-sparc64
	fi
	
	if [ ${ARCH} = "s390" ]; then
		make-cross-package libc6-s390x
		make-cross-package libc6-dev-s390x
	fi

	if [ ${ARCH} = "hppa" ]; then
		make-cross-package libgcc4 
	fi
	
	if [ ${ARCH} = "m68k" ] ; then
		make-cross-package libgcc2 
	else
		make-cross-package libgcc1
	fi

	# Added lib32gcc1 for testing - not sure if this is needed
	if [ ${ARCH} = "amd64" ] ; then
		make-cross-package lib32gcc1 
	fi
	
	if [ ${ARCH} = "ia64" ] ; then
		make-cross-package lib32gcc1 
	fi
	

#	make-cross-package uclibc-toolchain
#	make-cross-package libuclibc0
#	make-cross-package libuclibc-dev
	make-cross-package gcc-4.3-base
#	make-cross-arch-package gdb

	# Final work: Install libraries and do clean up
#	dpkg -i *all.deb
	rm -rf *${ARCH}.deb

}

# applies patches 
apply_patch () {
	patch -p1 < ../../patches/$1
}

# build and install cross gdb
# Actually not used
build-gdb () {
	local _upver=$(upstreamversion gdb)
	local _version=$(version gdb)
	local _dir=$(sourcedir gdb)
	local _debarch=${ARCH}

	if [ ! -d gdb-${_version} ]; then
		rm -rf $_dir
		apt-get source gdb
		# pushd $_dir
		# echo "${ARCH}" > debian/target
		#// Workarround patches
		# apply_patch binutils-cross-2.17.patch
		# popd
		mv $_dir gdb-${_version}
	fi
	pushd gdb-${_version}
#	dpkg-buildpackage -us -uc -B -rfakeroot
	TARGET=${ARCH} dpkg-buildpackage -rfakeroot -uc -us
	popd

#	$ROOTCMD dpkg -i gdb-${_debarch}-linux-gnu_${_version}_${HOSTARCH}.deb >> dpkg.log

	#// Do clean up
	rm -rf *.gz *.bz2 *.dsc *.changes *.tgz *.tar gdb-${_version}/ 

}

# build and install cross binutils
build-binutils () {
	local _upver=$(upstreamversion binutils)
	local _version=$(version binutils)
	local _dir=$(sourcedir binutils)
	local _debarch=${ARCH}

	if [ ! -d binutils-${_version} ]; then
		rm -rf $_dir
		apt-get source binutils
		pushd $_dir
		echo "${ARCH}" > debian/target
		#// Workarround patches
		# apply_patch binutils-cross-2.17.patch
		apply_patch binutils-cross-2.18.patch
		# apply_patch binutils-cross-2.18.1cvs20071027.patch
		popd
		mv $_dir binutils-${_version}
	fi
	pushd binutils-${_version}
#	dpkg-buildpackage -us -uc -B -rfakeroot
	TARGET=${ARCH} fakeroot debian/rules binary-cross
	popd

	$ROOTCMD dpkg -i binutils-*-linux-gnu*.deb >> dpkg.log

	#// Do clean up
	rm -rf *.gz *.bz2 *.tgz *.dsc *.changes *.tar binutils-${_version}/ 

}


# build cross gcc versions: build-gcc <majorversion>
build-gcc () {
	local _upver=$(upstreamversion gcc-$1)
	local _version=$(version gcc-$1)
	local _dir=$(sourcedir gcc-$1)

	if [ ! -d gcc-$1-${_version} ]; then
		rm -rf $_dir
		apt-get source gcc-$1
		pushd $_dir
		echo "${ARCH}" > debian/target

		# Workaround for GCC4.2
		if [ ${1} = "4.2" ]; then
		#	apply_patch reverse_cross_fix.patch
		#	apply_patch gcc42-amd64-i386.patch
			apply_patch gcc-4.2-4.2.2-cross.patch
		fi
		# Patch gcc-3.3
                if [ ${GCCVER} = "3.3" ]; then
                        # cp ../../patches/gcc-3.3.6-emdebian-cross.dpatch debian/patches
                        # apply_patch gcc-3.3.patch

			# Disables multi-arch
                        apply_patch gcc-3.3.6.patch
                fi
		
		DEB_CROSS=yes fakeroot debian/rules control
		popd
		mv $_dir gcc-$1-${_version}
	fi
	pushd gcc-$1-${_version}
	if [ ${ARCH} = "armel"  ]; then
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/arm-linux-gnueabi/lib/:/arm-linux-gnueabi/lib:/usr/arm-linux-gnueabi/lib32/:/usr/arm-linux-gnueabi/lib64/:/arm-linux-gnueabi/lib32/:/arm-linux-gnueabi/lib64/:/emul/ia32-linux/lib/:/emul/ia32-linux/usr/lib/ DEB_CROSS=yes dpkg-buildpackage -us -uc -B -rfakeroot
	else
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/${ARCH}-linux-gnu/lib/:/${ARCH}-linux-gnu/lib:/usr/${ARCH}-linux-gnu/lib32/:/usr/${ARCH}-linux-gnu/lib64/:/${ARCH}-linux-gnu/lib32/:/${ARCH}-linux-gnu/lib64/:/emul/ia32-linux/lib/:/emul/ia32-linux/usr/lib/ DEB_CROSS=yes dpkg-buildpackage -us -uc -B -rfakeroot
	fi
	popd
}

# install cross gcc versions: install-gcc <majorversion>
install-gcc () {
	local _version=$(version gcc-$1)
	local _versionrepo=$(echo gcc-$1 | sed -e 's/-//' | sed -e 's/\.//')
	
	#// Do clean up
	rm -rf *.gz *.bz2 *.tgz *.tar gcc-$1-${_version}/ *.changes *.dsc

}


# build and install cross gcc-3.3
build-gcc-3.3 () {
	checkinstalled gcc-3.3
	GCCVER=${GCCVER:="3.3"}
	build-gcc 3.3
	install-gcc 3.3
}

# build and install cross gcc-3.4
build-gcc-3.4 () {
	checkinstalled gcc-3.4
	GCCVER=${GCCVER:="3.4"}
	build-gcc 3.4
	install-gcc 3.4
}

# build and install cross gcc-4.0
build-gcc-4.0 () {
	checkinstalled gcc-4.0
	GCCVER=${GCCVER:="4.0"}
	build-gcc 4.0
	install-gcc 4.0
}

# build cross gcc-4.1
build-gcc-4.1 () {
	checkinstalled gcc-4.1
	GCCVER=${GCCVER:="4.1"}
	#// Please check this url before trying to build gcc-4.1
	#// http://people.debian.org/~terpstra/thread/20061015.114041.d049319b.en.html
	#// FIXME: Need to workarround that bug.
	build-gcc 4.1
	install-gcc 4.1
}

# build cross gcc-4.2
build-gcc-4.2 () {
        checkinstalled gcc-4.2
        GCCVER=${GCCVER:="4.2"}
        build-gcc 4.2
        install-gcc 4.2
}

build-gcc-4.3 () {
        checkinstalled gcc-4.3
        GCCVER=${GCCVER:="4.3"}
        build-gcc 4.3
        install-gcc 4.3
}

# build cross gcc-snapshot
build-gcc-snapshot () {
	# Hack, hack.
	pushd /usr/lib
	$ROOTCMD ln -sf /usr gcc-snapshot
	popd

	build-gcc snapshot
#	install-gcc snapshot
}

#----------------------------------------------------------------------
# Finally, do the work.

sanitycheck

# dpkg-cross version check
if [[ "1.39" > $(dpkg-cross --help 2>&1 |awk '{print $3; exit;}') ]]; then
	echo "dpkg-cross is too old."
	exit 1
fi

# do we need to check more version from some packages ?

# for ARCH in ${ARCHLIST}; do

	# Clean dir ?
	#./cleandir.sh
	[ -d ${ARCH} ] || mkdir ${ARCH}
	pushd ${ARCH}
	echo "Updating apt-cross cache"
	apt-cross -a ${ARCH} -S ${SUITE} -m ${MIRROR} -u
	echo "Building for ARCH::${ARCH}" 
	#// make libs
	if [ ${1} = "libs" ]; then
		build-libs &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	#// make binutils
	elif [ ${1} = "binutils" ]; then
		build-binutils  &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	#// make gdb
	elif [ ${1} = "gdb" ]; then
		build-gdb  &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	#// make gcc
	#elif [ ${1} = "snapshot" ]; then
	#	build-gcc-snapshot  &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	elif [ ${1} = "3.3" ]; then
		GCCVER=${1}
		echo $GCCVER
		echo Runs
		echo gcc-3.3
#		build-gcc-${GCCVER} &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	elif [ ${1} = "3.4" ]; then
		GCCVER=${1}
		build-gcc-${GCCVER} &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	elif [ ${1} = "4.1" ]; then
		GCCVER=${1}
		build-gcc-${GCCVER} &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	elif [ ${1} = "4.2" ]; then
		GCCVER=${1}
		build-gcc-${GCCVER} &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	elif [ ${1} = "4.3" ]; then
		GCCVER=${1}
		build-gcc-${GCCVER} &> ../$LOGPATH/$HOST-$ARCH-$PKG.log
	else
		echo " Unknown option"
		exit 1
	fi
	popd

	# REPLACE: This quite does not work
	# echo 0 >> $LOGPATH/$HOST-$ARCH-$PKG.log
	TEST=`cat $LOGPATH/$HOST-$ARCH-$PKG.log | grep $HOST.deb`
	if [ -n ${TEST} ]; then
	 	echo 1 >> $LOGPATH/$HOST-$ARCH-$PKG.log
	else
	 	echo 0 >> $LOGPATH/$HOST-$ARCH-$PKG.log
	fi
	
# done

