# Z-shell functions
#
# $Revision: 2.3 $ $Date: 2019-01-30 01:17:03-05 $
# $UUID: f3bdc06f-528d-34aa-8cfd-16dd2fa4fbc4 $

# cd up N levels.  usage: .. [n]
unset -f .. 2> /dev/null
.. () {
    local arg=${1:-1};
    local dir=""
    while [ $arg -gt 0 ]; do
        dir="../$dir"
        arg=$(($arg - 1));
    done
    cd $dir #>&/dev/null
}

# go to the directory containing a file or another directory
unset -f D 2> /dev/null
D () {
    case "$#" in
        1) if test -e "$1"; then
               cd $(dirname $(realpath "$1"))
           else
               echo "can't find $1"
           fi ;;

        *) echo 'need a file or directory' ;;
    esac
}

# use this when connected via SSH;
# running daemon/daemonize can screw up exit
unset -f bye 2> /dev/null
bye () {
    case "X$SSH_CLIENT" in
        X) builtin exit ;;
        *) kill -15 $$ $PPID ;;
    esac
}

# if current directory is a link, cd to actual directory
unset -f cwd 2> /dev/null
cwd () {
    _x=$(/bin/pwd)
    chdir "$_x"
    unset _x
}

unset -f here 2> /dev/null
here () {
    current=$PWD
    echo "current='$current'" >! $HOME/.current
}

# Directory stuff.
unset -f up 2> /dev/null
up () {
    cd ../$*
}

unset -f upp 2> /dev/null
upp () {
    cd ../../$*
}

# Better setup for which: shows aliases, functions.
unset -f which 2> /dev/null
unalias which  2> /dev/null
which () {
    (alias; declare -f) | /usr/bin/which --tty-only --read-alias \
        --read-functions --show-tilde --show-dot $@
}
