#!/bin/sh

cd /usr/ports

# CHECK COMMAND LINE ARGUMENT
if [ ! -z "$1" ]; then
    INPUT="$1"
    if [ -f "/usr/ports/$INPUT/pkg/DESCR" ]; then
        DIR="$INPUT"
    fi
fi

# CHECK CLIPBOARD
if [ -z "$1" ]; then
    INPUT="$(xclip -o|head -1|col -b)"
    if [ -f "/usr/ports/$INPUT/pkg/DESCR" ]; then
        DIR="$INPUT"
    fi
fi

# ASK USER
if [ -z "$DIR" ]; then
    DIR=$(ls -1d */* mystuff/*/* \
            | egrep -v '^pobj|^distfiles|^log|^plist|^packages|CVS|Makefile|\.tgz$' \
            | fzf -e);
fi

# Nothing selected.
[ -z "$DIR" ] && exit 0

# Move to chosen dir
cd "/usr/ports/$DIR"

# Gather port details and show them
DETAILS=$(printf "%s\n\n%s\n%s\n%s\n\nCVS %s\n" \
            "/usr/ports/$DIR" \
            "Package:    $(make show=FULLPKGNAME)" \
            "Maintainer: $(make show=MAINTAINER)" \
            "Homepage:   $(make show=HOMEPAGE)" \
            "$(cvs log -Nl -rHEAD 2>&1 \
                | awk '{
                    if ($0 ~ /^===/) p++;
                    if (p == 1) print $0;
                    if ($0 ~ /^---/) p++;
                    }' \
            )" \
            | fzf -e)

# Nothing selected.
[ -z "$DETAILS" ] && exit 0

# Do whatever.
case "$DETAILS" in
    Package*)    make show=FULLPKGNAME | xclip -r; ;;
    Maintainer*) make show=MAINTAINER | xclip -r; ;;
    Homepage*)   firefox "$(make show=HOMEPAGE)" & ;;
    *)           cd "$DETAILS"; port mark; ksh; ;;
esac
