#!/bin/bash
# vim: set et sw=4 sts=4 :

# This hook makes Paludis use diff-eix (from app-portage/eix) to compare the
# contents of the eix cache before and after a sync. To enable this
# functionality, this script should be copied or symlinked into:
#
#     /usr/share/paludis/hooks/sync_all_pre/
#     /usr/share/paludis/hooks/sync_all_post/
#
# You should ensure that it has execute permissions.

source ${PALUDIS_EBUILD_DIR}/echo_functions.bash

EIX_CACHE="${EIX_CACHE:-${ROOT}/var/cache/eix}"
EIX_CACHE_OLD="${EIX_CACHE_OLD:-${ROOT}/var/cache/eix.old}"

REPO_FORMAT="ebuild"

die() {
    echo -e "${COLOUR_BAD}$*${COLOUR_NORMAL}"
    kill ${PALUDIS_PID}
    exit 1
}

shopt -s extglob

opts=""
for repo in `${PALUDIS_COMMAND} --list-repositories --repository-format ${REPO_FORMAT}|awk '{print $NF}'`; do
    location=$(${PALUDIS_COMMAND} --configuration-variable ${repo} location)
    cache=$(${PALUDIS_COMMAND} --configuration-variable ${repo} cache)

    opts="${opts} --add-overlay ${location}"

    # eix cannot yet use any metadata, if it exists, it has to be in ${location}/metadata/cache
    [[ "${cache}" == "${location}/metadata/cache" ]] || continue
    opts="${opts} -m ${location} metadata"
done

case "${HOOK}" in
    sync_all_pre)
        # Make sure the old eix cache exists and is in a current format
        if [[ ! -f "${EIX_CACHE}" ]]; then
            update-eix -q --output "${EIX_CACHE}" ${opts} || die "update-eix failed"
        fi
        if ! eix --is-current; then
            update-eix -q --output "${EIX_CACHE}" ${opts} || die "update-eix failed"
        fi

        # Copy old cache and set permissions and owner correctly correctly
        cp "${EIX_CACHE}" "${EIX_CACHE_OLD}" || die "Could not copy ${EIX_CACHE} to ${EIX_CACHE_OLD}"
        if [[ "${UID}" -eq 0 ]]; then
            chown portage:portage "${EIX_CACHE_OLD}" || die "Could not set portage as owner for ${EIX_CACHE_OLD}"
        fi
        chmod 664 "${EIX_CACHE_OLD}" || die "Could not set permissions correctly for ${EIX_CACHE_OLD}"
    ;;

    sync_all_post)
        # Update eix cache and diff it against the old
        update-eix -q --output "${EIX_CACHE}" ${opts} || die "update-eix failed"
        diff-eix -F "${EIX_CACHE_OLD}" "${EIX_CACHE}" || die "Failed to diff against current cache"
    ;;

    *)
        echo -e "${COLOUR_BAD}There is no handler for this hook: ${HOOK}${COLOUR_NORMAL}"
    ;;
esac
