#!/bin/sh

expr "$-" : '^.*i' >/dev/null || return

##########################################
null(){
    "$@" >/dev/null 2>&1
}
__safe_run(){
    type $1 >/dev/null 2>&1 && "$@"
}

__match(){
    # __match str word
    # return 0 if word is found in str
    expr "$1" : ".*$2.*" >/dev/null
}


#################################
# profile-like setups

__safe_add_path_r(){
    # add path to right
    test -d "$1" && PATH="${PATH}:$1"
}
__safe_add_path_l(){
    # add path to left
    test -d "$1" && PATH="$1:${PATH}"
}

__safe_add_path_l "$HOME/.cabal/bin"
__safe_add_path_l "$HOME/.local/lib/gems/bin"
__safe_add_path_l "$HOME/.local/bin"
__safe_add_path_l "$HOME/.gem/ruby/2.1.0/bin"
__safe_add_path_r "/c/mingw/bin"
__safe_add_path_r "/c/mingw/msys/1.0/bin"

# macports coreutils
# $isdarwin cannot be used it is not defined yet
__safe_add_path_l "/opt/local/bin"
__safe_add_path_l "/opt/local/sbin"
__safe_add_path_l "/opt/local/libexec/gnubin"
__safe_add_path_l \
    "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/bin"

test -f "${__dotdir}/rc.py" && export PYTHONSTARTUP="${__dotdir}/rc.py"

test -d "$HOME/.local/lib/python/site-packages" && \
    export PYTHONPATH="${PYTHONPATH}:${HOME}/.local/lib/python/site-packages"

export GEM_HOME="$HOME/.local/lib/gems"
export RUBYLIB="$RUBYLIB:$HOME/.local/lib/gems/lib"


# it is not so good
# http://archive.linux.or.jp/JF/JFdocs/Program-Library-HOWTO/shared-libraries.html
# http://superuser.com/questions/324613/installing-a-library-locally-in-home-directory-but-program-doesnt-recognize-it
# without this ENV i cannot run tmux. another way is to use --disable-shared
# when building tmux
if ! __match "$LD_LIBRARY_PATH" "$HOME/.local/lib"
then
    export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HOME/.local/lib"
fi

# in my environment powerdown does not work
test -z "$DISPLAY" && test -z "$SSH_CONNECTION" && \
    type setterm >/dev/null 2>&1 && \
    setterm -blank 30 -powersave on # -powerdown 10

#########################
# shrc.common
# this variable must consistent with setup.sh
__shrc_common="$HOME/.shrc.common"

if test -f "$__shrc_common"
then
    . "$__shrc_common"
else
    echo "$__shrc_common not found."
    echo "Run setup.sh first."
    return
fi

##########################
# system type

gnu_coreutils=false      # for mac
null ls --version && gnu_coreutils=true

inbash=false
inzsh=false

if test -n "$BASH_VERSION"
then
    inbash=true
elif test -n "$ZSH_VERSION"
then
    inzsh=true
fi

#################################
# file pathes:
#     shrc: Path to this file

if $inbash
then
    __shrc="$BASH_SOURCE"
elif $inzsh
then
    __shrc="$0"
fi

##################################
# EnvVal definitions

test "$TERM" = linux && export LANG=C
export LC_MESSAGES=C
export LC_TIME=C

export TERMCAP="${TERMCAP}:vb="
$ismsys && export HOSTNAME
# export ENV=~/.shrc

if false $iswindows
then
    export PAGER='tr -d \\r | less'
else
    export PAGER="less"
fi
export LESS="-iRMX"

# Style for lesspipe is defined in esc.style
_src_hilite_lp_path="`command -v src-hilite-lesspipe.sh 2>/dev/null`"
for f in /usr/share/source-highlight/src-hilite-lesspipe.sh
do
    test -z "$_src_hilite_lp_path" && test -e "$f" && _src_hilite_lp_path="$f"
done
test -n "$_src_hilite_lp_path" && export LESSOPEN="| $_src_hilite_lp_path %s"

if null type vim
then
    export EDITOR=vim
else
    export EDITOR=vi
fi
# export CDPATH=".:~"
export VISUAL="$EDITOR"

export GIT_PAGER="less -F"
export GIT_EDITOR="$EDITOR"
export GIT_MERGE_AUTOEDIT=no

if test -n "$TMUX" && \
    __match $TERM screen && \
    __match `tmux display -p '#{client_termname}'` 256color
then
    TERM=screen-256color
fi

if test -z "$TMP"
then
    if test -n "$TMPDIR"
    then
        export TMP=$TMPDIR
    elif test -n "$TEMP"
    then
        export TMP="$TEMP"
    else
        export TMP=/tmp
    fi
fi
__match "$TMP" "${USER}-tmp" >/dev/null || export TMP="${TMP}/${USER}-tmp"
export TEMP="$TMP"
test -d "$TMP" || mkdir -p "$TMP"

if ! $iswindows && null type stty
then
    stty stop undef        # unbind C-s to stop displaying output
    # stty erase '^h'
fi

if $iswindows
then
    export USER=$USERNAME
fi

if test -d ~/dbx
then
    export CHIT_PATH="$HOME/dbx/.chit"
fi

# adhoc fix for ansible on cygwin
# http://blog.s-uni.net/2013/08/27/ansible-running-on-cygwin/
if $incygwin
then
    export ANSIBLE_SSH_ARGS="-o ControlMaster=no"
fi

##########################
# Zsh specific preferences

# http://www.clear-code.com/blog/2011/9/5.html

if $inzsh
then
    bindkey -e

    # http://zsh.sourceforge.net/Guide/zshguide06.html#l147
    autoload compinit; compinit
    # supress cycle by tab
    unsetopt auto_menu
    # unsetopt correct
    setopt complete_aliases
    setopt auto_list
    setopt bash_auto_list
    setopt magic_equal_subst
    setopt list_types
    # what is the difference of these two?
    setopt auto_param_slash
    setopt mark_dirs
    zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
    zstyle ':completion:*' format '%B%d%b'
    zstyle ':completion:*' group-name ''
    zstyle ':completion:*' use-cache yes
    # zstyle ':completion:*:cd:*' tag-order local-directories
    zstyle ':completion:*' completer _complete _bash_completions \
        _history
    # zstyle ':completion:*:*:cd:*' completer
    zstyle ':completion:*' accept-exact-dirs true
    zstyle ':completion:*' special-dirs true

    autoload colors; colors

    # autoload -Uz promptinit
    # promptinit
    # prompt walters

    setopt hist_ignore_dups
    setopt hist_ignore_all_dups
    setopt hist_save_no_dups
    setopt extended_history
    setopt share_history
    setopt append_history
    HISTFILE=$HOME/.zsh-history
    HISTSIZE=100000
    SAVEHIST=100000

    setopt prompt_subst

    setopt interactive_comments
fi

######################
# Print welcome messages

command -v fortune >/dev/nul && {
    if command -v cowsay >/dev/null
    then
        fortune | cowsay
        echo
        fortune -o | cowsay
        echo
    else
        fortune
        echo
        fortune -o
        echo
    fi
}

uname -a
$iswindows && alias tty="echo cmd.exe"
echo TERM $TERM with $(tput colors) colors using $(tty)

echo
__safe_run w yuk

# if null type tmux
# then
#     echo
#     echo tmux sessions:
#     tmux ls 2>/dev/null| sed -e 's/^/  /g'
#     echo
# fi

# if test -n "$TMUX"
# then
#     tmux display -p \
#         'TMUX #S:#I:#W.#P, client TERM: #{client_termname}' \
#         2>/dev/null
#     echo
# fi

###################################
# some aliases and functions

# __func_name: never used interactively
# _func_name: usually not used interactively

__safe_alias(){
    # __safe_alias <name>=<command>
    _bin=`expr "$1" : '^[^=]*=\([^ ]*\)'`
    test -n "$_bin" && \
        null type $_bin && \
        alias "$1"
}

$gnu_coreutils && _timeoption=" --time-style=long-iso"
# color prefs
if $gnu_coreutils
then
    # http://qiita.com/yuyuchu3333/items/84fa4e051c3325098be3
    # gnu coreutils LS_COLORS is used
    null type dircolors && eval `dircolors`
    _coloroption=" --color=auto"
else
    # export LSCOLORS=gxfxcxdxbxegedabagacad
    export LSCOLORS=DxGxcxdxCxegedabagacad
    export CLICOLOR=1
fi
alias ls="ls -hCF${_coloroption}${_timeoption}"

_timeformat_iso="%Y-%m-%dT%H:%M:%S%z"
_timeformat_rfc2822="%a, %d %b %Y %T %z"
_timeformat_num="%Y%m%d%H%M%S"
alias datenum="date +$_timeformat_num"

# export GREP_OPTIONS=""
alias gr="grep -n --color=always"
$iswindows && alias gr="grep -n"
alias less="less -F"
__safe_alias em="emacs -nw"
__safe_alias vi=vim
alias pstree="LANG=C pstree"
alias cp="cp -v"
alias mv="mv -v"
alias rm="rm -v"
alias mkdir="mkdir -v"
alias psaux="ps auxww"
alias q=exit
__safe_alias e3=e3em
#alias dirs="dirs -v -l | \grep -v \$(printf '%s$' \$PWD)"
alias po=popd
alias pu=pushd
__safe_alias sudo="sudo "              # use aliases through sudo
__safe_alias sudoe="sudoedit"
# __safe_alias halt="sudo halt"
# __safe_alias reboot="sudo reboot"
null type dbus-send && {
    alias suspend="dbus-send --system --print-reply \
        --dest=org.freedesktop.UPower \
        /org/freedesktop/UPower org.freedesktop.UPower.Suspend"
    alias hibernate="dbus-send --system --print-reply \
        --dest=org.freedesktop.UPower \
        /org/freedesktop/UPower org.freedesktop.UPower.Hibernate"
}
alias rand="echo \$RANDOM"
__safe_alias xunp="file-roller -h"
__safe_alias pc="sudo \paco -D"
alias pycalc="python -i -c 'from math import *' "
__safe_alias py3=python3
__safe_alias py2=python2
__safe_alias ipy=ipython
__safe_alias ipy3=ipython3
__safe_alias ipy2=ipython2
# Sometimes SHELL cannot be used. For example, when running bash inside zsh
# SHELL is set to be /bin/zsh
if $inbash
then
    alias _reloadrc="exec bash"
elif $inzsh
then
    alias _reloadrc="exec zsh"
else
    alias _reloadrc="exec $SHELL"
fi
# alias mytime="date +%Y%m%d-%H%M%S"
alias sh="ENV=$HOME/.shrc PS1=\$\  PROMPT_COMMAND="" sh"
# type trash >/dev/null 2>&1 && alias rm=trash
__safe_alias mpg123="mpg123 -C -v --title"
__safe_alias xm="xmms2"
#export PLAYER="mpg123 -C -v --title"

__safe_alias screen="screen -e^z^z"
#alias zcd="cd \`zenity --file-selection --directory\`"
__safe_alias gtags="gtags --verbose"
__safe_alias htags="htags --xhtml --symbol --line-number \
--frame --alphabet --verbose"
__safe_alias au=aunpack
# __safe_alias lv="lv|less"
__safe_alias rs="rsync --progress --itemize-changes --compress"
__safe_alias vagr=vagrant
if $iscygwin
then
    __my_wget_options=" --no-check-certificate"
    __safe_alias wget="wget $__my_wget_options"
fi

if $isdarwin
then
    alias updatedb="LC_ALL=C updatedb"
    # do not use locate installed by macports
    test -x /usr/bin/locate && alias locate="/usr/bin/locate"
fi

# somehow not work
# typeset -ga chpwd_functions
# chpwd_functions+=pwd

# chpwd(){
#     pwd
# }
cd(){
    builtin cd "$@" && pwd
}

# pad
alias pad=notepad
__safe_alias pad=gedit
__safe_alias pad=leafpad
$isdarwin && alias pad="open -e"

__safe_alias wic=wicd-curses
__safe_alias wil="wicd-cli -y -l | head"
#alias wicn="wicd-cli -y -c -n"
wicn(){
    if test $# -eq 0
    then
        local num
        wicd-cli -y -l | head
        echo -n "input num: "
        read num
        test -n "$num" && wicd-cli -y -c -n $num
    else
        wicd-cli -y -c -n $1
    fi
}

__find_latest_vimdir(){
    vimdir=/usr/share/vim
    if test -d "$vimdir"
    then
        find "$vimdir" -name 'vim??' -type d | sort | tail -n 1
    else
        echo ""
    fi
}

for f in /usr/share/vim/vimcurrent "`__find_latest_vimdir`"
do
    test -n "$f" || continue
    f="$f/macros/less.sh"
    test -f $f && alias vl=$f && break
done

__safe_alias pa="pacman --color=always"
__safe_alias pa="pacapt"

__safe_alias yt=yaourt
__safe_alias cower="cower --color=auto"
null type pacmatic && {
    alias pacman="pacmatic"
    # variable for yaourt
    export PACMAN="pacmatic"
}

__my_pacman_update_mirrorlist_with_reflector(){
    ml=/etc/pacman.d/mirrorlist
    cmd="$(expr "$(grep -m 1 reflector $ml)" : '# With: *\(.*\)')"
    if test -z "$cmd"
    then
        cmd="reflector --verbose --country Japan --latest 5 --sort rate --save $ml"
    fi
    echo ">>> $cmd ..." 1>&2
    sudo sh -c "$cmd"
}
null type reflector && test -d /etc/pacman.d && \
    alias reflect_mirrorlist=__my_pacman_update_mirrorlist_with_reflector

null type apt-get && {
    alias aupgrade="sudo sh -xc 'apt-get autoremove --yes && \
apt-get update --yes && apt-get upgrade --yes'"
    alias aptin="apt-get install"
    alias aptsearch="apt-cache search"
    alias aptshow="apt-cache show"
}

null type port && {
    alias port="port -v"
    alias pupgrade="sudo sh -xc 'port -v selfupdate && \
port -v upgrade outdated'"
}

if $iscygwin
then
    null type windate || \
        alias windate="cmd.exe //c 'echo %DATE%-%TIME%'"
    # alias cygsu="cygstart /cygwinsetup.exe"
fi

g(){
    if test $# -eq 0 && null type git-info
    then
        git info
    else
        git -c color.ui=always "$@"
    fi
}
if null type _git && $inbash
then
    # enable programmable completion for g
    complete -o bashdefault -o default -o nospace -F _git g 2>/dev/null \
        || complete -o default -o nospace -F _git g
fi
#git svn --help >/dev/null 2>&1 && alias gsvn="git svn"

__safe_alias m=gitmemo

alias setup.py3="sudo python3 setup.py install --record files.txt"

randomstr(){
    len=$1
    test -z "$len" && len=8
    uuidgen | tr -d - | cut -c 1-len
}

datestr(){
    # datestr YYYYMMDDhhmmss
    if test -z "$1" || test "$1" = "-h"
    then
        echo "datestr: usage: datestr <YYYYMMDDhhmmss>"
        return 1
    fi

    dfmt=""                       # actual format for date command
    while test -n "$1"
    do
        fmt="$1"
        shift
        while test -n "$fmt"
        do
            case "$fmt" in
                YYYY*|yyyy*)          # year
                    dfmt="${dfmt}%Y"
                    fmt="`echo "$fmt" | cut -c 5-`"
                    ;;
                YY*|yy*)            # last two digits of year
                    dfmt="${dfmt}%y"
                    fmt="`echo "$fmt" | cut -c 3-`"
                    ;;
                MM*)            # month (01..12)
                    dfmt="${dfmt}%m"
                    fmt="`echo "$fmt" | cut -c 3-`"
                    ;;
                DD*|dd*)            # day of month (01..12)
                    dfmt="${dfmt}%d"
                    fmt="`echo "$fmt" | cut -c 3-`"
                    ;;
                HH* | hh*)            # hour (00..23)
                    dfmt="${dfmt}%H"
                    fmt="`echo "$fmt" | cut -c 3-`"
                    ;;
                mm*)            # minute (00..59)
                    dfmt="${dfmt}%M"
                    fmt="`echo "$fmt" | cut -c 3-`"
                    ;;
                SS*|ss*)            # second (00..60)
                    dfmt="${dfmt}%S"
                    fmt="`echo "$fmt" | cut -c 3-`"
                    ;;
                *)
                    char=`echo "$fmt" | cut -c 1`
                    dfmt="${dfmt}${char}"
                    fmt="`echo "$fmt" | cut -c 2-`"
                    ;;
            esac
        done
    done
    date +"$dfmt"
}

# ssh(){
#     # __my_terminal_title ssh
#     command ssh "$@"
# }

__ssh_with_cd(){
    # __ssh_with_cd <host> <directory> [<arg> ...]
    if test -z "$2"
    then
        echo "usage: __ssh_with_cd <host> <directory> [<arg> ...]"
        return 1
    fi
    host="$1"
    shift
    dir="$1"
    shift
    ssh "$host" "$@" -t "cd \"$dir\"; \$SHELL -l"
}

memo(){
    if test -z "$1"
    then
        _memo="memo.txt"
    else
        _memo="$1/memo.txt"
    fi
        $EDITOR "$_memo"
    if test -z "`cat "$_memo"`"
    then
        echo "$_memo is empty. Removing."
        rm "$_memo"
    fi
}

now(){
    local tformat="%Y/%m/%d %H:%M:%S %z"
    cal
    REPLY=
    printf "\\r`date "+${tformat}"`"
    read -t 1
    while test $? -ne 0
    do
        printf "\\r`date "+${tformat}"`"
        read -t 1
    done
}

s(){
    if git rev-parse --git-dir >/dev/null 2>&1
    then
        echo ">> git grep -n $@" 1>&2
        git grep -n "$@"
    elif which ag >/dev/null 2>&1
    then
        echo ">> ag --pager=\"$PAGER\" $@" 1>&2
        ag --pager="$PAGER" "$@"
    elif which ack >/dev/null 2>&1
    then
        echo ">> ack --pager=\"$PAGER\" $@" 1>&2
        ack --pager="$PAGER" "$@"
    else
        echo \
            ">> find . " \
            "-path '*/.git' -prune -o" \
            "-path '*/.svn' -prune -o" \
            "-type f -exec grep -nH -e --color=always $@ {} +" 1>&2
        if test $# -eq 0
        then
            echo "No search word given." 1>&2
            return 1
        fi
        find . \
            -path '*/.git' -prune -o \
            -path '*/.svn' -prune -o \
            -type -f -exec grep -nH -e --color=always "$@" {} + \
            | $PAGER
    fi
}

MYMANPATH='/usr/lib/erlang/man'
if $inbash || $inzsh
then
    man(){
        env \
            LESS_TERMCAP_mb=$(printf "\e[1;35m") \
            LESS_TERMCAP_md=$(printf "\e[1;31m") \
            LESS_TERMCAP_me=$(printf "\e[0m") \
            LESS_TERMCAP_se=$(printf "\e[0m") \
            LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
            LESS_TERMCAP_ue=$(printf "\e[0m") \
            LESS_TERMCAP_us=$(printf "\e[1;32m") \
            MANPATH="`manpath`:$MYMANPATH" \
            man "$@"
    }
fi

netwait(){
    while ! ping -c 1 -t 1 example.com
    do
        true
    done
    echo network works.
}

__realpath(){
    if type realpath >/dev/null 2>&1
    then
        command realpath "$@"
    else
        while ! test -d $1
        do
            shift
        done
        (command cd "$d" && echo "$PWD")
        # local d="$OLDPWD"
        # command cd "$1"
        # echo "$PWD"
        # command cd "$d"
    fi
}

tx(){
    tmux start-server
    if test -z "$1"
    then
        echo "usage: tx <session_name>"
        tmux list-sessions
    elif test -z "$TMUX"
    then
        # -A: attach if already exists
        # tmux new-session -A -c "$HOME" -s "$1"
        tmux new-session -A -s "$1"
    else
        # create new session if not exists yet
        # tmux has-session -t "$1" || TMUX= tmux new-session -d -c "$HOME" -s "$1"
        tmux has-session -t "$1" || TMUX= tmux new-session -d -s "$1"
        tmux switch-client -t "$1"
    fi
}

dt(){
    # dt [-h] [<name>] [<command ...>]
    __dtach_dir="${TMP}/dtach"
    mkdir -p "${__dtach_dir}"

    if test -n "${__MY_DTACH}"
    then
        # if already in dtach session print current session
        soc_name="`basename "$__MY_DTACH"`"
        echo "Current session: ${soc_name}"
    fi

    if test -z "$1"
    then
        # if no arg given show list of sessions
        echo "Sessions:"
        ls "${__dtach_dir}"
        return 0
    elif test "$1" = "-h"
    then
        echo "dt: usage: dt [-h] [<name>] [<command ...>]" 1>&2
        return 1
    fi

    # set socket name
    soc_name="${__dtach_dir}/$1"
    shift

    if test -n "$__MY_DTACH"
    then
        echo "dtach session cannot be nested." 1>&2
        return 1
    elif test -S "$soc_name"
    then
        dtach -a "$soc_name" -e ^^
    elif test -e "$soc_name"
    then
        echo "dt: File named $soc_name already exists."
        return 1
    elif test -z "$1"
    then
        # if no command given invoke current shell
        __MY_DTACH="$soc_name" dtach -c "$soc_name" -e ^^ sh -c "$SHELL"
        # echo "dt: Socket named $soc_name not exists and no command specified."
        # return 1
    else
        __MY_DTACH="$soc_name" dtach -c "$soc_name" -e ^^ "$@"
    fi
}

scr(){
    test -n "$1" && pf="${1}-"
    local _tformat="%Y%m%d-%H%M%S%z"
    local _file="${HOME}/${pf}`date +${_tformat}`.script"
    __MY_SCRIPT=${_file} script ${_file} "$@"
}

dtscr(){
    # dtscr <command ...>
    if test -z "$1"
    then
        echo "dtscr: usage: dtscr <command ...>"
        return 1
    fi

    local _cmdstr="`echo $@ | tr ' ' +`"
    local _tformat="%Y%m%d-%H%M%S%z"
    local _name="${pf}`date +${_tformat}`-${_cmdstr}"

    local _scr_file="${HOME}/${_name}.script"

    local _dt_dir="${TMP}/dtscr"
    mkdir -p "$_dt_dir"

    dtach -n "${_dt_dir}/${_name}" script "${_scr_file_}" "$@"
    # echo $_name
    # echo $_file
}

mcrypt_stream(){
    test $# -eq 2 || return 1
    case $1 in
        en)
            mcrypt --key $2 | base64 ;;
        de)
            base64 -d | mcrypt -d --key $2 ;;
    esac
}

gpg_stream(){
    test $# -eq 2 || return 1
    case $1 in
        en)
            gpg --passphrase $2 -c --batch |base64 ;;
        de)
            base64 -d|gpg --passphrase $2 -d --batch ;;
    esac
}
dgpg(){
    if test "$1" = help || test -z "$2"
    then
        echo "dgpg: dgpg <en|de> <src-suffix> [<dst-suffix>]" 1>&2
        return
    fi
    local srcs="$2"
    local dsts="$3"
    test -z "$dsts" && dsts="${srcs}.out"
    local pw
    echo -n "dgpg pw: "
    read -s pw
    echo ""
    test -z "$pw" && return 1
    for f in *${srcs}
    do
        local d="$(basename "$f" "${srcs}")${dsts}"
        echo -n "Processing $f to $d..."
        if test -d "$f"
        then
            echo "`printf 'failed (%s is directory)' $f`"
        elif test -f "$d"
        then
            echo "`printf 'failed (%s is already exists)' $d`"
        elif <"$f" gpg_stream $1 $pw >"$d" 2>/dev/null
        then
            echo "done"
        else
            echo "failed"
            test -f "$d" && rm "$d"
        fi
    done
}

alias enst="gpg_stream en"
alias dest="gpg_stream de"

showinfo(){
    echo "Japanese letters are 表示可能"

    __safe_run diskinfo

    ! $isdarwin && test -n "${DISPLAY}" && {
        __safe_run xrandr | \grep --color=never ^Screen
    }

    $iswindows || __safe_run finger $USER
    LANG=C __safe_runc id
    __safe_run xset q
}

x(){
    if [[ -z $DISPLAY ]] && ! [[ -e /tmp/.X11-unix/X0 ]] && (( EUID )); then
        #mkdir -p ~/.var/log
        # nohup startx >~/.var/log/xorg.log 2>&1 &
        # exit
        exec startx
    else
        echo "X cant be started! Another X is already running?" 1>&2
    fi
}

bak(){
    for file in "$@"
    do
        cp -v ${file} ${file}.bak
    done
}

di(){
    if type colordiff >/dev/null 2>&1 && test $TERM != dumb
    then
        local diffcmd=colordiff
    else
        local diffcmd=diff
    fi
    ${diffcmd} -u "$@" | ${PAGER}
}

tb(){
    __datenum=`date +%Y%m%d-%H%M%S`
    __tb="$HOME/.var/tb/$__datenum"
    mkdir -p "$__tb"
    mv "$@" "$__tb"
}

mkdd(){
    _d=`date +%Y%m%d-%H%M%S` && \
        mkdir -p "$_d"
}

mkcd(){
    if test -z "$1"
    then
        echo "mkcd: usage: mkcd <dir>"
        return 1
    elif test -d "$1"
    then
        echo "Dir \"$1\" already exists."
    else
        mkdir -p "$1"
        echo "Dir \"$1\" created."
    fi
    cd "$1"
}

mkcdd(){
    # make and change date directory
    _d=`date +%Y%m%d-%H%M%S` && \
        mkcd "$_d"
}

if test -n "$TMUX" && null type reattach-to-user-namespace
then
    alias pbpaste="reattach-to-user-namespace pbpaste"
    alias pbcopy="reattach-to-user-namespace pbcopy"
fi

catclip(){
    if $iswindows
    then
        cat /dev/clipboard | tr -d \\r
    elif $isdarwin
    then
        pbpaste
    else
        xclip -o -selection "clipboard"
    fi
}

setclip(){
    if test $# -eq 0
    then
        exec 3<&0
    else
        exec 3<<__EOF__
`cat "$@"`
__EOF__
    fi
    if $iswindows
    then
        0<&3 sed -e 's/$/\r/' | tee /dev/clipboard
    elif $isdarwin
    then
        pbcopy 0<&3
    else
        0<&3 xclip -i -f -selection "primary" | \
            xclip -i -f -selection "clipboard"
    fi
    exec 3<&-
}

open_file(){
    if $iscygwin
    then
        cygstart "$@"
    elif $ismsys
    then
        cmd.exe //c start "" "$@"
    elif $isdarwin
    then
        touch "$@"
        open "$@"
    elif $islinux
    then
        touch "$@"
        if null type pcmanfm; then
            LC_MESSAGES= pcmanfm "$@"
        else
            LC_MESSAGES= xdg-open "$@" &
        fi
    else
        cat "$@"
    fi
}

o(){
    if test $# -eq 0
    then
        open_file .
    else
        for f in "$@"
        do
            open_file "$(realpath "$f")"
        done
    fi
}

convmv_sjis2utf8_test(){
    convmv -r -f sjis -t utf8 *
}

convmv_sjis2utf8_notest(){
    convmv -r -f sjis -t utf8 * --notest
}


#################################################
## pastebin services
## https://wiki.archlinux.org/index.php/List_of_Applications/Internet#Pastebin_clients

sprunge(){
    # http://sprunge.us
    if test -z "$1"
    then
        curl -F 'sprunge=<-' http://sprunge.us
    else
        curl http://sprunge.us/$1
    fi
}

dpaste(){
    # http://dpaste.de
    if test -z "$1"
    then
        curl -F 'content=<-' https://dpaste.de/api/
        echo
    else
        curl https://dpaste.de/$1/raw/
    fi
}


######################################
## Prompt Settings

__my_moc_state(){
    type mocp >/dev/null 2>&1 || return
    test "`mocp -Q %state 2>/dev/null`" = PLAY || return
    printf "$1" "`mocp -Q %title 2>/dev/null`"
}

__my_parse_svn_branch() {
    local LANG=C
    local svn_url=$(svn info 2>/dev/null | sed -ne 's#^URL: ##p')
    local svn_repository_root=$(svn info 2>/dev/null | \
        sed -ne 's#^Repository Root: ##p')
    echo ${svn_url} | sed -e 's#^'"${svn_repository_root}"'##g' | \
        awk '{print $1}'
}

__my_svn_ps1(){
    if svn status >/dev/null 2>&1
    then
        local svn_branch=$(__my_parse_svn_branch)
        test -n "${svn_branch}" && printf "$1" "{$svn_branch}"
    fi
}

__my_battery_status(){
    local dir=/sys/class/power_supply/BAT0
    if test -d $dir && test -r $dir/status && test -r $dir/charge_full && \
        test -r $dir/charge_now
    then
        local st=$(cat $dir/status)
        local full=$(cat $dir/charge_full)
        local now=$(cat $dir/charge_now)
        local rate=$(expr $now \* 100 / $full)
        printf "$1" "${st}:${rate}%"
    fi
}
alias bat='__my_battery_status %s\\n'

ipaddress(){
    # ipaddress <fmt>
    type ip >/dev/null 2>&1 || return 1
    local ip=$(LANG=C ip addr show scope global | \
        \grep --color=never --only-matching 'inet [^ ]*' | cut -d " " -f 2)
    test -n "$ip" && printf $1 $ip
}

__my_ps1_scale(){
    if null type stty && ! $ismsys
    then
        echo "[LxC:`stty size | tr -d $'\n' | tr " " x`]"
    fi
}

__my_ps1_tmux(){
    null type tmux || return $last
    local tmuxc="$(tmux display -p '#S:#I:#W.#P' 2>/dev/null)"
    test -n "$TMUX" && echo "[TMUX:$tmuxc]"
}

__my_ps1_moc(){
    __my_moc_state "[MOC:%s]"
}

for f in /usr/share/git/git-prompt.sh \
    /usr/local/share/git-core/contrib/completion/git-prompt.sh \
    /etc/bash_completion.d/git-prompt \
    /opt/local/share/git-core/git-prompt.sh \
    /opt/local/share/doc/git-core/contrib/completion/git-prompt.sh
do
    test -r "$f" && ($inbash || $inzsh) && . "$f" && break
done
GIT_PS1_SHOWDIRTYSTATE=t
GIT_PS1_SHOWUPSTREAM=t
__my_ps1_git(){
    null type __git_ps1 || return $last
    null git rev-parse --git-dir >/dev/null 2>&1 || return $last
    __git_ps1 "[GIT:$(__safe_run git config --get user.name):%s]"
}

__my_ps1_ipaddr(){
    ! $iswindows && ipaddress '[Addr:%s]'
}

__my_ps1_bttry(){
    local bst="${TMP}/batterystatus"
    if test -z "$DISPLAY" && ! $iswindows
    then
        test -f $bst && local bstr="$(cat $bst)"
        test -n "$bstr" && ! echo $bstr | grep 100 >/dev/null 2>&1 && \
            echo "[Battery:$bstr]"
        __my_battery_status %s >$bst &
    fi
}

__my_ps1_memo(){
    test -f memo.txt && echo "m:`du -b memo.txt|cut -f 1`"
}

__my_ps1_dirs(){
    dirs | wc -l
}

__my_ps1_jobs(){
    # __my_ps1_jobs [<num>]
    if test -n "$1"
    then
        jobs="$1"
    else
        jobs="`jobs | wc -l`"
    fi
    if test "$jobs" -gt 0
    then
        echo "JOBS:$jobs"
    fi
}

__my_alert_fail(){
    test $laststatus -eq 0 || \
        echo "STATUS:${laststatus}"
}

# About ansi escape sequences
# http://archive.linux.or.jp/JF/JFdocs/Bash-Prompt-HOWTO-5.html
# http://www.grapecity.com/japan/powernews/column/clang/047/page02.htm


if $inbash || $inzsh
then
    if $inzsh
    then
        __attr_beg=$'%{\033['
        __attr_end='m%}'
    else
        __attr_beg='\[\033['
        __attr_end='m\]'
    fi

    __color_default="${__attr_beg}0${__attr_end}"

    __color_black="${__attr_beg}0;30${__attr_end}"
    __color_red="${__attr_beg}0;31${__attr_end}"
    __color_green="${__attr_beg}0;32${__attr_end}"
    __color_brown="${__attr_beg}0;33${__attr_end}"
    __color_blue="${__attr_beg}0;34${__attr_end}"
    __color_purple="${__attr_beg}0;35${__attr_end}"
    __color_cyan="${__attr_beg}0;36${__attr_end}"
    __color_light_gray="${__attr_beg}0;37${__attr_end}"

    __color_dark_gray="${__attr_beg}1;30${__attr_end}"
    __color_light_red="${__attr_beg}1;31${__attr_end}"
    __color_light_green="${__attr_beg}1;32${__attr_end}"
    __color_yellow="${__attr_beg}1;33${__attr_end}"
    __color_light_blue="${__attr_beg}1;34${__attr_end}"
    __color_light_purple="${__attr_beg}1;35${__attr_end}"
    __color_light_cyan="${__attr_beg}1;36${__attr_end}"
    __color_white="${__attr_beg}1;37${__attr_end}"

    __color_bg_black="${__attr_beg}40${__attr_end}"
    __color_bg_red="${__attr_beg}41${__attr_end}"
    __color_bg_green="${__attr_beg}42${__attr_end}"
    __color_bg_brown="${__attr_beg}43${__attr_end}"
    __color_bg_blue="${__attr_beg}44${__attr_end}"
    __color_bg_purple="${__attr_beg}45${__attr_end}"
    __color_bg_cyan="${__attr_beg}46${__attr_end}"
    __color_bg_light_gray="${__attr_beg}47${__attr_end}"

    __attr_underline="${__attr_beg}4${__attr_end}"
    __attr_reverse="${__attr_beg}7${__attr_end}"
    __attr_bold="${__attr_beg}1${__attr_end}"
fi

# NOTE: tput is another easy way to set colors and background
# For example, "$(tput setab 4)text$(tput sgr0)" print text with background
# color blue.
# http://www.ibm.com/developerworks/jp/linux/aix/library/au-learningtput/index.html

if test "$TERM" != dumb
then
    __my_c1="$__attr_bold$__attr_underline"      # color for PWD
    __my_c2="$__attr_bold$__attr_underline"       # color for user and hostname
    # color for ::
    case "`hostname`" in
        arch-aspireone)
            __my_c4="$__color_yellow"
            ;;
        arch-mba)
            __my_c4="$__color_light_cyan"
            ;;
        newkiwi)
            __my_c4="$__color_light_purple"
            ;;
        freebsd-vb-win7-opti)
            __my_c4="$__color_light_red"
            ;;
        *)
            __my_c4="$__color_light_green"
            ;;
    esac
    __my_c5="$__color_black$__color_bg_light_gray"        # color for SCR
    __my_cdef="$__color_default"
fi

if $inbash
then
    __my_ps1_sh="[BASH:$BASH_VERSION]"
elif $inzsh
then
    __my_ps1_sh="[ZSH:$ZSH_VERSION]"
fi

__my_ps1_info1(){
    # first line of PS1
    echo "${__my_ps1_sh}$(__my_ps1_scale)$(__my_ps1_git)$(__my_ps1_bttry)$(__my_ps1_ipaddr)$(__my_ps1_moc)"
}

test -n "$__MY_SCRIPT" && \
    __my_ps1_str_scr="SCR"

test -n "$SSH_CONNECTION" && \
    __my_ps1_str_ssh="SSH"

test -n "$__MY_DTACH" && \
    __my_ps1_str_dt="DT:`basename "$__MY_DTACH$"`"

__my_ps1_info2(){
    # second line of PS1
    echo $(__my_ps1_memo) $(__my_ps1_jobs) ${__my_ps1_str_scr} \
        ${__my_ps1_str_ssh} ${__my_ps1_str_dt} $(__my_alert_fail) \
        | sed -e 's/ /|/g'
}

__my_ps1_beg="${__my_c4}:: ${__my_cdef}"

__my_ps1_save_pos="\[\033[s\]"
__my_ps1_restore_pos="\[\033[u\]"
__my_ps1_move_rightmost="\[\033[\$(tput cols)C\]"
__my_ps1_move_15left="\[\033[15D\]"
# collapse when command line is too long and try to write over this string
# __my_ps1_right="${__my_ps1_save_pos}${__my_ps1_move_rightmost}"
# ${__my_ps1_move_15left}\D{%Y/%m/%d %H:%M}${__my_ps1_restore_pos}

if $inzsh
then
    PROMPT="\
${__my_ps1_beg}[${__my_c2}%n@%M${__my_cdef}:${__my_c1}%~/${__my_cdef}]\$(__my_ps1_info1)
${__my_ps1_beg}\$(__my_ps1_info2) %# "
    RPROMPT="%D{%Y/%m/%d %H:%M}"
elif $inbash
then
    PS1="\
${__my_ps1_beg}[${__my_c2}\u@\H${__my_cdef}:${__my_c1}\w/${__my_cdef}]\$(__my_ps1_info1)\n\
${__my_ps1_beg}\D{%Y/%m/%d %H:%M} \$(__my_ps1_info2)${__my_ps1_right} \$ "
else
    true
    # PS1="$(printf $(whoami)@$(hostname)$ )"
fi

###################################
# set header and titles

__my_set_header_line(){
    # save current position
    printf "\033[s"
    # move to 0,0
    printf "\033[0;0H"
    # clear curent to eol
    printf "\033[K"
    # inverse color
    printf "\033[7m"
    printf "$1"
    # restore color
    printf "\033[0m"
    # restore saved position
    printf "\033[u"
}

__my_set_screen_name(){
    # set window name
    if test -n "$TMUX" && test -z "$INSIDE_EMACS"
    then
        echo -ne "\033k$1\033\\"
    fi
}

__my_set_title(){
    case $TERM in
        (rxvt*|xterm*|aterm|screen*)
            test -t 1 &&
            test -z "$EMACS" &&
            echo -n -e "\033]0;$1\007"
            ;;
    esac
}

if test -n "$TMUX"
then
    # running tmux locally
    __terminal_title="\$(basename \${PWD})"
elif test -n "$SSH_CONNECTION" && expr "$TERM" : '^screen' >/dev/null
then
    # ssh connect from tmux terminal
    __terminal_title="`whoami`@`hostname`:\$(basename \${PWD})"
else
    __terminal_title="`whoami`@`hostname`:\${PWD}"
fi

if $inzsh
then
    precmd(){
        laststatus=$?
        eval __my_set_title ${__terminal_title}
    }
else
    PROMPT_COMMAND="laststatus=\$?;__my_set_title \"${__terminal_title}\";$PROMPT_COMMAND"
fi
laststatus=0