#!/bin/bash
# by David Watzke <david@watzke.cz> @ 2006
# http://www.watzke.cz/en/bash

if [[ -r /sbin/functions.sh ]]; then
        source /sbin/functions.sh
else
        echo "Could not find /sbin/functions.sh!"
        echo "You will need sys-apps/baselayout!"
        exit 1
fi

die() {
        eerror "$@"
        exit 1
}

ehelp() {
        einfo "echange by David Watzke <david@watzke.cz> http://www.watzke.cz/bash"
        einfo "Usage: echange [[number of lines] [category/]package]"
        [[ $# -eq 0 ]] && exit 0 || exit 1
}

check_lineno() {
        if [[ "$1" =~ ^[[:digit:]]*$ ]]; then
                if [[ $1 -lt 18446744073709551616 ]]; then
                        line=$1
                else
                        die "Digit has to be less than 2^64!"
                fi
        else
                die "Not a digit: '$1'!"
        fi
}

check_pkgname() {
        [[ $(wc -l <<< "$1") -ne 1 ]] && goodname=false
        a=[[:alnum:]]
        if $goodname && grep -qE "^$a+(|(\-|$a)*$a)(|/$a+(|(\-|$a)*$a))$" <<< "$1"; then
                pkg=$1
        else
                die "Not a valid package name: '$1'!"
        fi
}

if [[ -r /etc/make.globals ]]; then
        source /etc/make.conf /etc/make.globals >& /dev/null
else
        eerror "Could not find a /etc/make.globals config file!"
        die "Are you sure you have Portage installed?"
fi

if [[ -z "$PORTDIR" ]]; then
        eerror "You have not '\$PORTDIR' variable set!"
        die "Could not find Portage tree!"
fi

if [[ "$PORTDIR" != "${PORTDIR// }" ]]; then
        eerror "You cannot have spaces in the path to the Portage tree!"
        die "Please fix this error!"
fi

if [[ $# -eq 1 ]]; then
        line=20
        check_pkgname $1
elif [[ $# -eq 2 ]]; then
        check_lineno $1
        check_pkgname $2
else
        ehelp
fi

if [[ "$pkg" =~ ./. ]]; then
        array=false
        log=$PORTDIR/$pkg/ChangeLog
else
        array=true
        log=($PORTDIR/*/$pkg/ChangeLog)
fi

if $array; then
        if [[ ${#log[*]} -eq 1 ]]; then
                log=${log[0]}
        else
                ewarn "Package name '$pkg' is ambiguous!"
                ewarn "Please specify full name (with category):"
                for ((i=0; i<${#log[*]}; i++)); do
                        pkgtmp=${log[$i]#$PORTDIR}
                        pkgtmp=${pkgtmp%/*}
                        ewarn "\t${pkgtmp#/}"
                done
                exit 1
        fi
fi

if [[ -r $log ]]; then
        head -n$line $log
else
        die "Package '$pkg' was not found!"
fi

# TODO:
# kontrolovat zda $line neni moc velky cislo
# konfigurak