#!/bin/sh
SRC_TAR_DIR="."
PATCH_DIR="debian/patches"
STRIP_LEVEL=1; # 0 or 1
VARS_FILE=""
cmd=""

if [ $(basename $0) = lib ];then
        while [ -n "$1" ]; do
        	case "$1" in 
        		*=*)
        			[ -n "$cmd" ] && echo "Already seen command" 1>&2 && exit 1;
        			eval "$1"
        			;;
        		*)
        			cmd="$1"
        			;;
        	esac			
        	shift;
        done;	
        
        if [ -e "$VARS_FILE" ] ; then
        	. "$VARS_FILE"	
        else 
        	make -f /usr/share/dbs/internal/vars.mk -C debian sh.vars
        	. debian/sh.vars
        fi
fi

fetchmsg() {
	local msg
	msg=$1;shift
	eval echo $(sed -ne "s/^$(BASENAME):$msg://p" /usr/share/dbs/internal/messages)
}
START() {
	echo -n "$(fetchmsg START "$@") "
}
OK() {
	fetchmsg OK "$@"
}
FAILED() {
	fetchmsg FAILED "$@"
}
ALREADY_DONE() {
	fetchmsg ALREADY_DONE "$@"
}

BASENAME() {
	local base
	if [ "$cmd" ];then
		base=$cmd
	else
		base=${0##*/}
	fi
	if [ x$base = x ];then
		echo "Danger, Will Robinson, Danger!" 1>&2
		echo "Bash is very confused." 1>&2
		exit 1
	fi
	if [ x$base = xlib ];then
		echo "You can't call this directly." 1>&2
		echo "This is a library that should be sourced." 1>&2
		exit 1
	fi
	echo $base
}
file2cat() {
	$(decompress_prog $1) $1
}
debug() {
	echo "$@"
	eval "$@"
}
decompress_prog() {
	local which
	which="cat"
	[ $1 != ${1%.tgz} -o $1 != ${1%.gz} -o $1 != ${1%.Z} ] && which="gunzip -c"
	[ $1 != ${1%.bz2} ] && which="bunzip2 -c"
	[ $1 != ${1%.bz} ] && which="bunzip -c"
	echo $which
}
compress_ext() {
	local which
	which=""
	[ $1 != ${1%.gz} ] && which=gz
	[ $1 != ${1%.Z} ] && which=Z
	[ $1 != ${1%.bz2} ] && which=bz2
	[ $1 != ${1%.bz} ] && which=bz
	echo $which
}
filetype_detect() {
	local which f
	which=""
	f=$(echo "$1" | sed 's|:::.*||')
	[ $f != ${f%.jar} ] && which=jarfile
	[ $f != ${f%.zip} ] && which=zipfile
	[ $f != ${f%.xpi} ] && which=zipfile
	[ $f != ${f%.tgz} ] && which=tarball
	[ $f != ${f%.tar.$(compress_ext $f)} ] && which=tarball
	[ $f != ${f%.tar} ] && which=tarball
	[ $f != ${f%.diff.$(compress_ext $f)} -o $1 != ${1%.patch.$(compress_ext $1)} ] && which=patch
	[ $f != ${f%.diff} -o $1 != ${1%.patch} ] && which=patch
	[ $f != ${f%.dsc} ] && which=dsc
	echo $which
}
extract_tar() {
	local which file dir curd
	dir="$1"
	shift
	curd=$(pwd)
	while [ $# -gt 0 ];do
		file="$1"
		[ "$file" = "${1#/}" ] && file="$curd/$file"
		case "$(filetype_detect $file)" in
			"jarfile")	(cd $dir;fastjar -xf $file);;
			"zipfile")	(cd $dir;miniunzip -x $file);;
			"tarball")	$(decompress_prog $file) $file | (cd $dir;tar xvf -);;
			*)		echo "unsupported tarball";;
		esac
		shift
	done
}

do_patching() {
	stop_at=""
	stop_and_include=""
	while [ $# -gt 0 ]; do
		[ "x$1" = "x--stop" ] && stop_at="`basename $2`" && shift 2
		[ "x$1" = "x--stop-include" ] && stop_and_include="`basename $2`" && shift 2
	done		
	filetmpl=\$d/\$f
	reversesort=""
	reversepatch=""

	case "$cmd" in
		source_patch)
			mkdir -p $SOURCE_DIR/$TAR_DIR
			patch_dirs="$SRC_PATCH_DIR $SRC_ADD_PATCH_DIR"
			stampfiletmpl=\$STAMP_DIR/\$d/\$f
			logtmpl=\$STAMP_DIR/log/\$d/\$f.log
			dirprep="\$STAMP_DIR/log/\$d \$STAMP_DIR/\$d"
			if [ $STRIP_LEVEL != "0" ] ; then
				patchapplydirtmpl=\$SOURCE_DIR/\$TAR_DIR
				STRIP_LEVEL=1
			else 				
				patchapplydirtmpl=\$SOURCE_DIR
			fi				
			;;
		patch_apply)
			mkdir -p $SOURCE_DIR/$TAR_DIR $STAMP_DIR/patches
			patch_dirs="$PATCH_DIR $ADD_PATCH_DIR"
			stampfiletmpl=\$STAMP_DIR/patches/\$f
			logtmpl=\$STAMP_DIR/log/\$d/\$f.log
			dirprep=\$STAMP_DIR/log/\$d
			patchapplydirtmpl=\$SOURCE_DIR/\$TAR_DIR
			if [ $STRIP_LEVEL != "0" ] ; then
				patchapplydirtmpl=\$SOURCE_DIR/\$TAR_DIR
				STRIP_LEVEL=1
			else 				
				patchapplydirtmpl=\$SOURCE_DIR
			fi				
			;;
		fix_source_patch)
			if [ "$DBS_UNIFIED" -o ! -e debian/fixpatch ];then
				exit
			fi
			mkdir -p $STAMP_DIR/fixpatch
			patch_dirs=debian/fixpatch
			stampfiletmpl="$STAMP_DIR/fixpatch/\$(basename \$f)"
			logtmpl=\$STAMP_DIR/log/fixpatch/\$f.log
			dirprep=\$STAMP_DIR/log/fixpatch
			patchapplydirtmpl=upstream
			;;
		unfix_source_patch)
			if [ "$DBS_UNIFIED" -o ! -e debian/fixpatch ];then
				exit
			fi
			mkdir -p $STAMP_DIR/fixpatch
			patch_dirs=debian/fixpatch
			stampfiletmpl="$STAMP_DIR/fixpatch/\$(basename \$f)"
			logtmpl=\$STAMP_DIR/log/fixpatch/\$f.log
			dirprep=\$STAMP_DIR/log/fixpatch
			patchapplydirtmpl=upstream
			reversesort=-r
			reversepatch=-R
			;;
	esac
	for d in $patch_dirs;do
		if [ ! -d $d ];then
			continue
		fi
		eval mkdir -p $dirprep
		for f in `(cd $d;find . -maxdepth 1 -type f ! -name 'chk-*' -and ! -path '*/.*' -and ! -path '*/CVS/*' 2>/dev/null | sed -e 's;^./;;' )| LC_COLLATE=C sort $reversesort`;do
			eval stampfile=$stampfiletmpl
			eval log=$logtmpl
			eval file=$filetmpl
			eval patchapplydir=$patchapplydirtmpl
			if [ "x$stop_at" != "x" ]; then
				[ "$stop_at" = "`basename $file`" ] && return;
			fi				
			if [ ! -e $stampfile ];then
				START $file
				
				if file2cat $file | (cd $patchapplydir; patch -p$STRIP_LEVEL  --no-backup-if-mismatch $reversepatch) > $log;then
					OK $file
					touch $stampfile
				else
					FAILED $file
					exit 1
				fi
			else
				ALREADY_DONE $file
			fi
			if [ "x$stop_and_include" != "x" ]; then
				[ "$stop_and_include" = "`basename $file`" ] && return;
			fi				

		done
	done

}
#
# External api functions.
#

source_clean() {
	cmd="source_clean"
	if [ "$DBS_UNIFIED" ];then
		exit
	fi
	rm -rf $SOURCE_DIR $STAMP_DIR/upstream $STAMP_DIR/patches
	rm -f $STAMP_DIR/source_clean $STAMP_DIR/source_build $STAMP_DIR/source_make
	return
if [ x$SOURCE_DIR = x ];then
	files=`find . -maxdepth 1 -mindepth 1 -type f`
	dirs=`find . -maxdepth 1 -mindepth 1 -type d ! -name 'debian' ! -name 'upstream'`
        echo files=\"$files\"
        echo dirs=\"$dirs\"
fi

}

source_unpack() {
	cmd="source_unpack"
	mkdir -p $STAMP_DIR/upstream/tarballs/ $STAMP_DIR/log/upstream/tarballs/ $SOURCE_DIR
	if [ ! -z "$SRC_TAR_DIR" -a -d "$SRC_TAR_DIR" ];then
		files=$(find -L $SRC_TAR_DIR -maxdepth 1 -type f -and ! -path '*/.*' -and ! -path '*/CVS/*' | LC_COLLATE=C sort)
	else
		VER=$(dpkg-parsechangelog 2>&1|egrep ^Version|cut -d " " -f 2|cut -d "-" -f 1)
		SRC=$(dpkg-parsechangelog 2>&1|egrep ^Source|cut -d " " -f 2-)
		files=../${SRC}_${VER}.orig.tar.gz
	fi
	for f in $files;do
		stampfile=$STAMP_DIR/upstream/tarballs/`basename $f`
		logfile=$STAMP_DIR/log/upstream/tarballs/`basename $f`.log
		if [ ! -e $stampfile ];then
			START $f
			if extract_tar ${SOURCE_DIR:-.} $f > "$logfile"; then
				OK $f
				touch $stampfile
			else
				FAILED $f
				exit 1
			fi
		else
			ALREADY_DONE $f
		fi
	done
}	

source_patch()		{ cmd=source_patch; do_patching "$@"; }
fix_source_patch()	{ cmd=fix_source_patch; do_patching "$@"; }
unfix_source_patch()	{ cmd=unfix_source_patch; do_patching "$@"; }
patch_apply()		{ cmd=patch_apply; do_patching "$@"; }

if [ $(basename $0) = lib ];then
	$cmd;
fi

