#!/usr/bin/env bash
# Copyright 2006-2010 Gentoo Foundation; Distributed under the GPL v2
# $Id: ecopy 56412 2010-01-18 18:07:43Z grobian $

# This probably will blow up if not ran in a Prefix environment, sorry.

RSURL=${RSURL:-"http://tinderbox.dev.gentoo.org/portage"}
EPREFIX=${EPREFIX:-$(portageq envvar EPREFIX)}
WGET_CMD="wget --no-verbose --no-glob --no-clobber"

source "${EPREFIX}/sbin/functions.sh"

if ! type -P qatom > /dev/null ; then
	ewarn "This script requires the use of qatom, please emerge"
	ewarn "app-portage/portage-utils to continue."
	exit 1
fi

if ! type -P wget > /dev/null ; then
	ewarn "This script requires the use of wget."
	ewarn "It is not in your PATH."
	exit 1
fi

if [[ -z ${1} ]] ; then
	einfo
	einfo "usage: ecopy <category>/<package>"
	einfo "- make sure the scripts directory from the overlay is in your path"
	einfo "- make sure you call ecopy from the root of the overlay"
	einfo "- you can also specify a specific version, using the '=' prefix"
	einfo "and appending a version"
	einfo
	einfo "ecopy is a best effort script only. It doesn't guarantee a working"
	einfo "result"
	exit 0
fi

# Uses qatom to determine if the second atom is greater than the first, and
# returns true if so.
is_greater_atom() {
	if [[ $(qatom -c $1 $2 | awk '{print $2}') == "<" ]]; then
		return 0
	else
		return 1
	fi
}

# Takes input of a list of ebuild strings and uses is_greater_atom() to return
# the greatest in the list.
return_greatest() {
	# Append '-0_alpha' to the end of the name such that any version is greater
	# than it. bug #278113
	max="${catpkg#*\/}-0_alpha"
	for i in $@; do
		if is_greater_atom $max $i; then
			max="${i}"
		fi
	done
	echo $max
}

# Either use qatom or fall back to a non-qatom approach which may generate false
# positive.
return_greatest_wrapper() {
	echo "$( return_greatest "$( \
	wget -q "${RSURL}/${catpkg}" -O - | \
	egrep "href=\"[^\"]+\.ebuild\"" -o | \
	sed -e 's/^href="//' -e 's/"$//' -e 's/%2b/+/g' )" )"
}

# Mangle user input
if [[ ${1:0:1} == "=" ]] ; then # Check to see if the first char is an "="
	ebuildgrep="${1#*\/}.ebuild"
	catpkg="${1#=}"       # Strip the leading "="
	catpkg="${catpkg%-[0-9]*}" # Strip the trailing verion numbers
	# Grab the index from the current $RSURL and parse it for the list
	# of ebuilds.  Grab the specified version that the user entered.
	ebuild="$(wget -q "${RSURL}/${catpkg}" -O - | \
		grep -F $ebuildgrep -o | head -n1)"
else
	catpkg="$1"
	# Use the wrapper function to just grab the latest version.
	ebuild="$( return_greatest_wrapper )"
fi

# TODO: fix error checking. patches welcome.
# Error checking.
echo $ebuild
if [[ -z ${ebuild} ]] ; then
	ewarn "please specify a correct specific version"
	[[ ${1:0:1} == "=" ]] \
		&& ewarn "$1 doesn't match an existing ebuild in the tree" \
		|| ewarn "example: =$1-0.2.3"
	exit -1
fi

# Copy these so the Prefix tree matches the gentoo-x86 tree. But don't if the
# $catpkg dir already exists. It is assumed that they are already there.
if [[ ! -d ${catpkg} ]]; then 
	mkdir -p "${catpkg}" && cd "$catpkg"
	${WGET_CMD} "${RSURL}/$catpkg/ChangeLog"
	${WGET_CMD} "${RSURL}/$catpkg/metadata.xml"
	${WGET_CMD} "${RSURL}/$catpkg/Manifest"
else
	einfo
	einfo "It appears that $catpkg already exists. I will continue but"
	einfo "you should verify my actions"
	einfo
	cd "$catpkg"
fi

# needed for sourcing ebuild and understanding ebuild specific vars.
PF="${ebuild/.ebuild}"
P="${PF%-r[1-9]*}"
PN="${P%-*}"
PV="${P/${PN}-}"

# Get the ebuild
${WGET_CMD} "${RSURL}/${catpkg}/${ebuild}"

source ${ebuild} 2> /dev/null #get rid of "inherit: command not found" message.

# Get the patches. Assumed that every patch has FILESDIR in the line. Good
# assumption.
for i in $(eval echo $(grep FILESDIR $ebuild | sed -e 's:.*FILESDIR[}"]*/::' -e 's:"::g' -e "s:'::" -e "s:#.*::" -e "s: .*::")); do
	mkdir -p "files"
	${WGET_CMD} -P "files" "${RSURL}/$catpkg/files/$i"
done

# Set explicit PATHs for scripts in the prefix tree so they don't need to be
# copied to your PATH. IOW, you always want eapify & ecleankw to be ran.
"$(portageq envvar PORTDIR)"/scripts/eapify ${ebuild}
"$(portageq envvar PORTDIR)"/scripts/ecleankw ${ebuild}
source "${EPREFIX}/etc/make.profile/make.defaults"

# Force the user's keyword on the ebuild. Less work for the user.
if ! type -P ekeyword > /dev/null ; then
	einfo
	einfo "ekeyword not found! Please emerge app-portage/gentoolkit-dev then run '$(eval echo ekeyword "~${ACCEPT_KEYWORDS#*\~}" $ebuild)' manually"
else
	ekeyword "~${ACCEPT_KEYWORDS#*\~}" $ebuild
fi

ebuild ${ebuild} digest #re-digest for changes made to the ebuild above
