autoload -U terminfo
autoload -U add-zsh-hook

function swap_hogs() {
    grep --color=never -n VmSwap /proc/*/status | sort -n -k2 | awk '/proc\/([0-9]+)\/status/ { split($1, p, "/"); fn="/proc/"p[3]"/status"; getline s < fn; split(s, n, ":"); sub(/^[ \t\r\n]+/, "", n[2]); print n[2] " (" p[3] ") " $2 "kB" }'
}

# ssh-agent {{{
# typeset _ssh_env_cache
# _ssh_env_cache="$HOME/.ssh/environment-${HOST/.*/}"
# function _start_ssh_agent() {
#     ssh-agent -s -t 4h | sed 's/^echo/#echo/' >! "$_ssh_env_cache"
# 
#     for ident in $HOME/.ssh/*.pub; do
#         ssh-add ${ident/.pub/}
#     done
# }
# 
# if [[ -n "$SSH_AUTH_SOCK" ]]; then
#     [[ -L "$SSH_AUTH_SOCK" ]] || ln -snf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USER-screen
# elif [[ -f "$_ssh_env_cache" ]]; then
#     . "$_ssh_env_cache" > /dev/null
#     pgrep ssh-agent | grep -q $SSH_AGENT_PID || {
#         _start_ssh_agent
#     }
# else
#     _start_ssh_agent
# fi
# 
# unset _ssh_env_cache
# }}}

# battery/UPS {{{
if [[ -x "$(whence apcaccess)" ]]; then
    function battery_pct_remaining() {
        echo $(apcaccess | fgrep BCHARGE | cut -d: -f2 | cut -d\  -f2)
    }
    function battery_time_remaining() {
        echo $(apcaccess | fgrep TIMELEFT | cut -d: -f2)
    }
    function battery_pct_prompt() {
        b=$(battery_pct_remaining)
        if [[ $b -gt 60 ]]; then
            color=green
        elif [[ $b -gt 25 ]]; then
            color=yellow
        else
            color=red
        fi
        echo "%{$fg[$color]%}$(battery_pct_remaining)%%%{$reset_color%}"
    }
else
    function battery_pct_remaining() {
    }
    function battery_time_remaining() {
    }
    function battery_pct_prompt() {
    }
fi
# }}}

# git prompt {{{
function git_prompt_info() {
    local ref
    ref=$(command git symbolic-ref HEAD 2>/dev/null) || \
    ref=$(command git rev-parse --short HEAD 2>/dev/null) || return 0
    echo "git:(${ref#refs/heads/}$(parse_git_dirty))"
}
function parse_git_dirty() {
    local STATUS=''
    local -a FLAGS
    FLAGS=('--porcelain' '--untracked-files=no')
    STATUS=$(command git status ${FLAGS} 2>/dev/null | tail -n1)
    if [[ -n "$STATUS" ]]; then
        # dirty
        echo -e " %{\e[1;35m%}%{⧱%G%}%{\e[0;34m%}"
    else
        # clean
        echo ""
    fi
}
# }}}

function title {
    emulate -L zsh
    [[ "$EMACS" == *term* ]] && return
    : ${2=$1}
    case "$TERM" in
        cygwin|xterm*|putty*|rxvt*|ansi)
            print -Pn "\e]2;$2:q\a" # window
            print -Pn "\e]1;$1:q\a" # tab
            ;;
        screen*)
            print -Pn "\ek$1:q\e\\"
            ;;
        *)
            if [[ -n "$terminfo[fsl]" ]] && [[ -n "$terminfo[tsl]" ]]; then
                echoti tsl
                print -Pn "$1"
                echoti fsl
            fi
            ;;
    esac
}

function title_precmd {
    title "%15<…<%~%<<" "%n@%m: %~"
}

add-zsh-hook precmd title_precmd

function title_preexec {
    setopt extended_glob
    local CMD=${1[(wr)^(*=*|sudo|ssh|mosh|rake|-*)]:gs/%/%%}
    local LINE="${2:gs/%/%%}"

    title "$CMD" "%100>…>$LINE%<<"
}

add-zsh-hook preexec title_preexec


function md() {
    mkdir -p $1
    cd $1
}

function cdl() {
    pushd "$1" && ls -CF --color=always "${@:2}"
}

function dur() {
    ls -lSr -hd "${1:-.}"/*; du -chd2 -- "${1:-.}"/ | sort -h; df -h "$@"
}

alias rcp="rsync -aiPvh"
alias rup="rsync -aiPvhu"

function rmv() {
    local -a flags=(${(M)@:#-*})
    local -a parms=(${@:#-*})
    shift $parms
    local src="${parms[1]}"
    local dest="${parms[2]}"
    rsync -aiPvhu --remove-source-files --prune-empty-dirs "${(@)flags}" "$parms"
    if [[ -d "$src" ]] ; then
        find "$src" -type d -empty -delete
    fi
}

function unpack() {
    filename="$1"
    echo "$filename"
    shift
    basefilename="$(basename "${filename}")"
    dirname="${basefilename%.*}"
    echo "$dirname"
    mkdir -p "$dirname"
    7z x -o"$dirname" "$filename"
}
function unpack-mv() {
    unpack "$1"
    mv "$@"
}

cp-lower() {
    local -a from=()
    local to
    local CMD=""
    local verbose
    while [[ $# -gt 1 ]]; do
        case "$1" in
            -n)
                CMD=echo
                echo '.-n' "$@"
                ;;
            -v)
                verbose=-v
                echo '.-v' "$@"
                ;;
            *)
                if [[ -e "$1" ]]; then
                    from+=("$to")
                    to="$1"
                fi
                echo "$@"
                ;;
        esac
        shift
    done

    echo ${(@)from}
    echo $to
}
ytclip () {
  yt-dlp -f "bv+ba" --download-sections "*$1-$2" --force-keyframes-at-cuts $3 -q -o ~/Videos/clip
}

# vim:ft=zsh

mp3towav(){
	[[ $# -eq 0 ]] && { echo "mp3wav mp3file"; exit 1; }
	for i in "$@"
	do
		# create .wav file name
		local out="${i%/*}.wav"
		[[ -f "$i" ]] && { echo -n "Processing ${i}..."; mpg123 -w "${out}" "$i" &>/dev/null  && echo "done." || echo "failed."; }
	done
}
