# /usr/share/abuild/functions.sh

sysconfdir=@sysconfdir@
prog=${0##*/}


abuild_conf=${ABUILD_CONF:-"$sysconfdir/abuild.conf"}
abuild_home=${ABUILD_USERDIR:-"$HOME/.abuild"}
abuild_userconf=${ABUILD_USERCONF:-"$abuild_home/abuild.conf"}

# read config
if [ -f "$abuild_conf" ]; then
	. "$abuild_conf" || abuild_conf=
fi

# read user config if exists
if [ -f "$abuild_userconf" ]; then
	. "$abuild_userconf" || abuild_userconf=
fi


# expects $1 to be a package directory in the aports tree ('foo' or 'main/foo')
# outputs APKBUILD's path if successful
aports_buildscript() {
	[ -n "$APORTSDIR" ] || return 1
	if [ "${1#*/}" != "$1" ]; then
		( cd "$APORTSDIR/$1" && [ -f APKBUILD ] && echo "$PWD/APKBUILD" )
	else
		( cd "$APORTSDIR"/*/"$1" && [ -f APKBUILD ] && echo "$PWD/APKBUILD" )
	fi
}

# expects $1 to be a file, or a directory containing an APKBUILD, or a package directory in the aports tree
# outputs APKBUILD's path if successful (doesn't verify that it's a valid APKBUILD)
any_buildscript() {
	if [ -f "$1" ]; then
		echo "$1"
	elif [ -d "$1" ]; then
		[ -f "$1/APKBUILD" ] || return 1
		echo "$1/APKBUILD"
	else
		aports_buildscript "$1" || return 1
	fi
}


# output functions
case $prog in
abuild)
	if [ -n "$USE_COLORS" ]; then
		NORMAL="\033[1;0m"
		STRONG="\033[1;1m"
		RED="\033[1;31m"
		GREEN="\033[1;32m"
		YELLOW="\033[1;33m"
		BLUE="\033[1;34m"
	fi

	msg() {
		local prompt="$GREEN>>>${NORMAL}"
		local fake="${FAKEROOTKEY:+${BLUE}*${NORMAL}}"
		local name="${STRONG}${subpkgname:-$pkgname}${NORMAL}"
		[ -z "$quiet" ] && printf "${prompt} ${name}${fake}: $@\n" >&2
	}

	warning() {
		local prompt="${YELLOW}>>> WARNING:${NORMAL}"
		local fake="${FAKEROOTKEY:+${BLUE}*${NORMAL}}"
		local name="${STRONG}${subpkgname:-$pkgname}${NORMAL}"
		printf "${prompt} ${name}${fake}: $@\n" >&2
	}

	error() {
		local prompt="${RED}>>> ERROR:${NORMAL}"
		local fake="${FAKEROOTKEY:+${BLUE}*${NORMAL}}"
		local name="${STRONG}${subpkgname:-$pkgname}${NORMAL}"
		printf "${prompt} ${name}${fake}: $@\n" >&2
	}
	;;
*)
	msg() {
		# Here we write to stdout, but abuild's fancier messages write to stderr
		[ -z "$quiet" ] && echo "$@"
	}

	error() {
		echo "$prog: $@" >&2
	}
	;;
esac

# caller may override
cleanup() {
	return 0
}

die() {
	error "$@"
	cleanup
	exit 1
}
