#!/bin/ksh

PORTSDIR="/usr/ports/" # append slash
PORTSINDEX="${PORTSDIR}INDEX"

if [ "$1" == "makeindex" ]; then
    printf '%s\n' "Indexing ports... (this may take a bit)"
    find "$PORTSDIR" -not -path "*/pobj*" \
                     -not -path "*/distfiles*" \
                     -type f -name "DESCR" \
                     2>/dev/null > "$PORTSINDEX"
    exit 0
fi

! [ -f "$PORTSINDEX" ] \
    && printf '%s\n' 'You must run "portsearch makeindex" first.\n' \
    && exit 2

cat "$PORTSINDEX" | \
while read LINE; do
    if printf "$LINE" | grep -iq "$1" || \
       grep -iq "$1" "$LINE"; then
        PORT="$(printf "$LINE" | cut -b$((${#PORTSDIR}+1))- | cut -d"/" -f 1,2)"
        HOMEPAGE="$(cat "${LINE%/*}/../Makefile" | grep "^HOMEPAGE" | tr '\t' ' ')"
        printf '\n\033[31;1;4m%s\033[0m\n%s\n%s\n' "$PORT" "$(cat "$LINE")" "$HOMEPAGE"
    fi
done
