#!/bin/bash
# 2008, 2010 Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain

load_mod rpm

set_hasherdir()
{
	HSH=/usr/bin/hsh
	if [ ! -x "$HSH" ] ; then
		fatal "Please install hasher package before use it"
	fi

	#if [ -n "$HASHERDIR" ] ; then
	#	fatal "Possible HASHERBASEDIR is not set correctly. Please replace HASHERDIR with HASHERBASEDIR in the config file"
	#fi
	HASHERDIR=$HASHERBASEDIR$MENVARG
	if [ "$BUILDARCH" = "x86_64" ] ; then
		HASHERDIR="$HASHERDIR-64"
	fi
}

check_locking()
{
	test -f "$HASHERDIR/pid" || return
	local pid="$(cat "$HASHERDIR/pid")"
	if [ "$pid" -gt 0 ] ; then
		if kill -0 -- "$pid" 2>/dev/null; then
			warning "hasher dir $HASHERDIR is already locked by pid $pid"
			ps hp "$pid" >&2
		# disable due always reported
		#else
		#	warning "hasher dir $HASHERDIR is locked by stale pid $pid"
		fi
	fi

#	echo -n "Wait for unlocking"
#	while test -f $HASHERDIR/lockdir/lockfile
#	do
#		echo -n "."
#		sleep $(($RANDOM%5+3))
#	done

}

# workaround about hard coded path to sources.list in apt.conf
print_tmp_aptconf()
{
	test -r "$1" || fatal "$1 is missed"
	# Note: /etc/apt and /etc/eterbuild/apt is supported
	cat "$1" | \
		sed -e "s|\".*/sources.list|\"$OURTMPDIR/sources.list|g"
}

# printout sources.list with filtering from apt.conf
# workaround about hard coded arch in sources.list
print_tmp_sourceslist()
{
	local SLIST
	test -r "$1" || fatal "$1 is missed"
	# Note: /etc/apt and /etc/eterbuild/apt is supported
	if rhas "$1" "^/etc" ; then
		SLIST=`cat "$1" | \
			grep "/sources.list" | sed -e 's|.*"\(.*\)".*|\1|g'`
	else
		SLIST=`cat "$1" | \
			sed -e "s|\"/etc/.*apt/sources.list|\"$ETERBUILDETC/apt/sources.list|g" | \
			grep "/sources.list" | sed -e 's|.*"\(.*\)".*|\1|g'`
	fi
	test -r "$SLIST" || fatal "'$SLIST' - sources.list path from $1 is missed"
	if [ "$BUILDARCH" = "x86_64" ] ; then
		cat "$SLIST" | sed -e "s|\([ /]\)i[56]86|\1$BUILDARCH|g"
	else
		# Note: drop biarch 32bit on real 32bit
		cat "$SLIST" | sed -e "s|x86_64\([ /]\)|$BUILDARCH\1|g" | grep -v "x86_32" | grep -v "x86_64-i586"
	fi
}

prepare_aptconfig()
{
	export OURAPTCONF=$OURTMPDIR/apt.conf.$MENV
	print_tmp_aptconf $APTCONF >$OURAPTCONF || fatal "Can't create apt.conf"
	export OURSOURCES=$OURTMPDIR/sources.list.$MENV
	print_tmp_sourceslist $APTCONF >$OURSOURCES || fatal "Can't create sources.list"
	if [ -n "$ETERBUILD_APTREPO" ] ; then
		cat <<EOF >>$OURSOURCES

# Apply repo(s) from external ETERBUILD_APTREPO variable
$ETERBUILD_APTREPO
EOF
	fi
	[ -n "$QUIETMODE" ] && return
	echo
	echog "Apt sources from $APTCONF:"
	cat $OURSOURCES | grep -v "^#" | grep -v "^\$" | grep rpm | sed -e "s|rpm|    rpm|"
	echo
}
