#!/bin/ksh -e
# needs converters/qprint

if [ -t 0 ] || [ -z "$1" ]
then
    echo "usage: patch.sh [git|patch] < patchfile.diff"
    exit 2
fi

echo "Shortcuts:"
echo "ld    - luakit-dev"
echo "lt    - luakit-test"
echo "ltmp  - luakit-tmp"
echo "src   - /usr/src"
echo "sys   - /usr/src/sys"
echo "ports - /usr/ports"
echo "www   - /usr/www"
echo
printf "Path [$PWD]: "
read _reply < /dev/tty

if [ -z "$_reply" ]
then
    _path="$PWD"
else
    _path="$_reply"
fi

# shortcuts!!!
case "$_path" in
    ld) _path="/home/sdk/src/luakit-dev" ;;
    lt) _path="/home/sdk/src/luakit-test" ;;
  ltmp) _path="/home/sdk/src/luakit-tmp" ;;
    src) _path="/usr/src" ;;
    sys) _path="/usr/src/sys" ;;
  ports) _path="/usr/ports" ;;
esac

if [ ! -d "$_path" ]
then
    _path="$(port-jump "$_path")"
fi

print "Using: $_path"

if [ ! -d "$_path" ]
then
    echo "Error with path: $_path"
    exit 2
fi

cd "$_path"
if [ "$1" == "git" ]
then
    cat /dev/stdin | git am
fi

if [ "$1" == "patch" ]
then
    printf "Strip [0]: "
    read _strip < /dev/tty
    _strip=${_strip:=0}
    
    cat /dev/stdin | doas -u sdk patch -E -N -p$_strip -d "$_path"
fi

echo "$_path" | xclip

