#!/bin/sh

usage() {
    printf "Argument missing\n"
    exit 2
}
[ -z $1 ] && usage


# MAKE SURE MARKFILE EXISTS
MARKFILE="/var/cache/pmark"
if [ ! -f "${MARKFILE}" ]
then
    doas touch "${MARKFILE}"
    doas sdk:sdk "${MARKFILE}"
fi

portmark() {
    printf "%s" "${PWD}" > ${MARKFILE}
    printf "marked.\n"
}

portsrcdir() {
    printf "%s" "$(cat "${MARKFILE}")"
}
portobjdir() {
    cd "$(cat "${MARKFILE}")" \
        && printf "%s" "$(make show=WRKSRC)"
}

portclean() {(
    cd /usr/ports
    doas rm -rf /usr/ports/{pobj/*,plist,logs,packages,bulk,update}
    doas make fix-permissions > /dev/null
    echo done
)}

portdiff() {
    _opwd="$PWD"
    _name="$(make show=PKGNAME)"
    _epoch="$(make show=EPOCH)"
    _rev="$(make show=REVISION)"
    _patchname="${_name}${_epoch:+v$_epoch}${_rev:+p$_rev}"
    cd /usr/ports \
        && doas cvs -d sdk@cvs.openbsd.org:/cvs diff -uNp $(echo "$_opwd" \
        | sed 's,/data/cvs/ports/,,g' \
        | sed 's,/usr/ports/,,g') \
        > /home/sdk/diffs/${_patchname}.diff
    grep '^?' /home/sdk/diffs/${_patchname}.diff
    cd "$_opwd"
    printf "Patch created: /home/sdk/diffs/%s.diff\n" "$_patchname"
}

portpack() {
    _dir="$(basename "$(readlink -f  .)")"
    cd ..
    doas tar czvf "${_dir}.tgz" "${_dir}" \
    && readlink -f "${_dir}.tgz"
    cd -
}

portjump() {
    if [ -z $1 ]
    then
        echo /usr/ports
        exit 0
    fi
    _dirs="archivers astro audio benchmarks biology books bulk \
           cad chinese comms converters databases devel editors \
           education emulators fonts games geo graphics inputmethods \
           japanese java korean lang mail math meta misc multimedia \
           net news plan9 print productivity security shells sysutils \
           telephony textproc wayland www x11"
    for d in $_dirs
    do
        if [ -d /usr/ports/$d/$1 ]
        then
            echo /usr/ports/$d/$1
        fi
    done
}

case $1 in
    mark) portmark; ;;
    src) portsrcdir; ;;
    obj) portobjdir; ;;
    clean) portclean; ;;
    diff) portdiff; ;;
    pack) portpack; ;;
    jump) portjump $2; ;;
esac
