#! /usr/bin/env sh
# This script is part of the eix project and distributed under the
# terms of the GNU General Public License v2.
#
# Author and Copyright (c):
#   Martin V\"ath <vaeth@mathematik.uni-wuerzburg.de>
#
# This file must be "source"d by POSIX scripts.
#
# It can add or remove local layman overlays to the current eix
# database. (eix 0.13.3).

. '/usr/bin/functions-eix.sh'
read_functions

Usage () {
	local I R
	R=${1:-1}
	echo "Usage: ${0##*/} [options] command
Add or remove local layman overlays to eix database (eix 0.13.3)
The following commands are provided:

add:	Add the local layman overlays to the eix database
remove:	Remove the local layman overlays from the eix database.

Options:
	-a OVERLAY    Add overlay to the list of layman overlays.
	-A PATH       Add PATH to the sourced make.conf's used to determine
	              the layman overlays. Current value:"
	eval "set -- ${LAYMAN_MAKE}"
	[ ${#} -eq 0 ] && set -- \
		'none (i.e. no readable layman make.conf specified)'
	for I
	do
		echo \
"	            	${I}"
	done
	echo \
"	-C            Clear the above list
	-c LAYMAN_CFG Use layman.cfg file to determine entry for above list
	-v            Verbose (default)
	-q            Quiet"
	exit ${R}
}

ClearLaymanMake () {
	Push -c LAYMAN_MAKE
}

PushLaymanMake () {
	local M R
	R=1
	for M; do
		[ -n "${M}" ] || continue
		test -r "${M}" || continue
		Push LAYMAN_MAKE "${M}"
		R=0
	done
	return ${R}
}

PrintLaymanMake () {
	python -c "from layman.config import Config
print Config()['make_conf']" "${@}" 2>/dev/null
}

CalcLaymanMake () {
	local L
	L=`PrintLaymanMake "${@}"` || return
	PushLaymanMake "${L}"
}

GetPortdir
ClearLaymanMake
CalcLaymanMake || \
	PushLaymanMake '/usr/local/portage/layman/make.conf' || \
	PushLaymanMake "${LOCAL_PORTDIR:-/}local/layman/make.conf"
LAYMAN_OVERLAYS=''

while getopts 'vqa:A:c:C?hH' OPTION; do
	case "${OPTION}" in
		v) VERBOSE=true;;
		q) VERBOSE=false;;
		a) Push LAYMAN_OVERLAYS "${OPTARG}";;
		c) CalcLaymanMake -c "${OPTARG}";;
		A) PushLaymanMake "${OPTARG}";;
		C) ClearLaymanMake;;
		*) Usage 0;;
	esac
done
[ ${OPTIND} -gt 1 ] && shift "`expr ${OPTIND} - 1`"

GetOverlays () {
	local I
	eval "set -- ${LAYMAN_MAKE}"
	for I; do
		[ -n "${I}" ] && test -r "${I}" && Push LAYMAN_OVERLAYS \
			`PORTDIR_OVERLAY=''; . "${I}"; \
				echo "${PORTDIR_OVERLAY}"`
	done
}

Init () {
	ClearUpdateEixArgs
	GetOverlays
	AddLocalMethods
}

Add () {
	Init
	eval "AddOverlays ${LAYMAN_OVERLAYS}"
	CallUpdateEix
}

Remove () {
	Init
	eval "AddExcludes ${LAYMAN_OVERLAYS}"
	CallUpdateEix
}

MAIN_COMMAND="${1}"
[ ${#} -gt 0 ] && shift

case "${MAIN_COMMAND}" in
	add*)               Add "${@}";;
	rem*|del*|rm*|sub*) Remove "${@}";;
	*)                  Usage;;
esac

exit 0
