#/* vim: set filetype=sh : */
# bash_functions содержит определения функций для bash,
# подключается из bashrc
# "extglob" BASH option must by  activated!
#
# dimio (http://dimio.org)
# See more: http://dimio.org/bash-born-again-shell-obolochka-komandnoj-stroki.html
# VERSION='0.08'
# Last update: 2016-09-29 08:49

hash which;

# Simple unpacking archive files
# (c) Librarian (libc6.org)
ex() {
    if [[ -r $1 ]] ; then
        case $1 in
            *.tar.bz2|*.tbz2)   tar xjf $1 ;;
            *.tar.gz|*.tgz)     tar xzf $1 ;;
            *.bz2)              bunzip2 $1 ;;
            *.rar)              unrar x $1 ;;
            *.gz)               gunzip $1  ;;
            *.tar)              tar xf $1  ;;
            *.zip)              unzip $1   ;;
            *.Z)                uncompress $1 ;;
            *.7z)               7z x $1    ;;
            *)                  echo "'$1' cannot be extracted via extract()" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}

# Simple packing files
# (c) Librarian (libc6.org)
pk() {
    if [ $1 ] ; then
        case $1 in
            tbz)    tar cjvf $2.tar.bz2 $2      ;;
            tgz)    tar czvf $2.tar.gz  $2      ;;
            tar)    tar cpvf $2.tar  $2       ;;
            bz2)    bzip $2 ;;
            gz)     gzip -c -9 -n $2 > $2.gz ;;
            zip)    zip -r $2.zip $2   ;;
            7z)     7z a $2.7z $2    ;;
            *)      echo "'$1' cannot be packed via pk()" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}

# Print full path to installed Perl module
# (c) Ether
# See "perldoc -l Module::Name" for replacement
# if it is available
perlwhere () {
    /usr/bin/perl -wle 'eval "require $ARGV[0]" or die;
                ($mod = $ARGV[0]) =~ s|::|/|g;
                print $INC{"${mod}.pm"}' $1
}

# Show external IP address
# (c) Librarian, dimio
my_ip() {
CK_URL='http://checkip.dyndns.org:8245'
    if [[ -x /usr/bin/lynx ]] ; then
        /usr/bin/lynx -dump -hiddenlinks=ignore -nolist ${CK_URL}
    elif [[ -x /usr/bin/elinks ]] ; then
        /usr/bin/elinks -dump ${CK_URL}
    elif [[ -x /usr/bin/wget ]] ; then
        /usr/bin/wget -q -O - ${CK_URL}
    elif [[ -x /usr/bin/curl ]] ; then
        /usr/bin/curl -o - ${CK_URL}
    else
        echo "External IP checking is not available"
    fi
}

# Wget выкачивание сайта с преобразованием абсолютных ссылок в относительные
# (c) dimio
wget_three() {
    if [ $1 ]; then
        /usr/bin/wget -c -r -t0 -k $1
    else
        echo "Укажите URL корневой страницы";
    fi
}

# Run elinks and open page in new tab if
# elinks is running after
el() {
    if [ -S $(find ~/.elinks -type s -quit) ]; then
        /usr/bin/elinks -remote "openURL($1,new-tab)"
    else
        /usr/bin/elinks "$1"
    fi
}

# Add geocache treasures to garmin GPS navigator
# (c) dimio
geoctonav(){
    if [ $1 ]; then
        sudo gpsbabel -i OZI -f $1 -o garmin,deficon=Geocache -F usb:
    else
        echo "Usage: geoctonav [input_file.wpt]";
    fi
}

# Convert all images in preferred dir to pref. scale
# (c) dimio
aconvert(){
    if [[ -x /usr/bin/convert ]] ; then
        if [[ "$1" && "$2" ]]; then
            EXT=$1;
            SCALE=$2;

            TOTAL=`find ./*.$EXT -type f | wc -l`;
            COUNT=1;

            for i in `ls *.$EXT`; do
                convert $i -scale $SCALE $i;
                echo "scale $i ($COUNT / $TOTAL)";
                COUNT=`expr $COUNT + 1`;
            done
        else
            echo "Usage: aconvert  ";
            echo "Example: aconvert jpg 800x600";
        fi
    else
        echo "Convert is not available, please install ImageMagick before."
    fi
}

# Playing internet-radio on mplayer
# (c) dimio
radio() {
    if [[ -x /usr/bin/mplayer ]] ; then
        case "${1}" in
            ?(-)[Mm]ayak)
                /usr/bin/mplayer 'http://livestream.rfn.ru:8080/mayakfm'
            ;;
            *)
                more < /dev/null
  git_status="$(git status 2> /dev/null)"
  branch_pattern="^# On branch ([^${IFS}]*)"
  remote_pattern="# Your branch is (.*) of"
  diverge_pattern="# Your branch and (.*) have diverged"
  if [[ ! "${git_status}" =~ "working directory clean" ]]; then
    state="${RED}⚡"
  fi
  # add an else if or two here if you want to get more specific
  if [[ "${git_status}" =~ "${remote_pattern}" ]]; then
	if [[ "${BASH_REMATCH[1]}" == "ahead" ]]; then
            remote="${YELLOW}↑"
	else
	    remote="${YELLOW}↓"
        fi
  fi
  if [[ "${git_status}" =~ "${diverge_pattern}" ]]; then
	remote="${YELLOW}↕"
  fi
  if [[ "${git_status}" =~ "${branch_pattern}" ]]; then
	branch="${BASH_REMATCH[1]}"
        echo " (${branch})${remote}${state}"
fi
}
function prompt_func() {
    previous_return_value=$?;
    prompt="${TITLEBAR}${BLUE}[${RED}\w${GREEN}$(parse_git_branch)${BLUE}]${COLOR_NONE} "
    if test $previous_return_value -eq 0
    then
        PS1="${prompt}» "
    else
        PS1="${prompt}${RED}»${COLOR_NONE} "
    fi
}
#>>

#<< Set sudo output format under Tmux
# for correctly Tmux tab naming
if [[ "${TMUX}" ]]; then
    function sudo() {
        echo -ne "\033k$1\033\\"
        $( which sudo ) $*;
        tmux rename-window "${SHELL/*\//}";
    }
fi;
#>>

####### INACTIVE FUNCTIONS #######
#
# Convert images to ISO image format
# (c) Librarian
#to_iso () {
    #if [ $# = 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
        #echo -e "Converts raw, bin, cue, ccd, img, mdf, nrg cd/dvd image files"
        #echo -e "to ISO image file. Usage ${RED_FG}'to_iso file1 file2...'$NC"
    #fi
    #for i in $*; do
        #if [ ! -f "$i" ]; then
            #echo "'$i' is not a valid file; jumping it"
        #else
            #echo -n "converting $i..."
            #OUT=`echo $i | cut -d '.' -f 1`
            #case $i in
            #*.raw)              bchunk -v $i $OUT.iso;; #raw=bin #*.cue #*.bin
            #*.bin|*.cue)        bin2iso $i $OUT.iso;;
            #*.ccd|*.img)        ccd2iso $i $OUT.iso;; #Clone CD images
            #*.mdf)              mdf2iso $i $OUT.iso;; #Alcohol images
            #*.nrg)              nrg2iso $i $OUT.iso;; #nero images
            #*)                  echo "to_iso don't know de extension of '$i'";;
            #esac
            #if [ $? != 0 ]; then
                #echo -e "${RED_FG}ERROR!$NC"
            #else
                #echo -e "${GREEN_FG}done!$NC"
            #fi
        #fi
    #done
#}
#
# Simple sync two files over netcat
# (c) dimio
#hbsync () {
    #SRC="$HOME/.homebank/base.xhb"
    #if [ $2 ]; then
        #SRC=$2
    #fi

    #if [ $1 ]; then
        #case $1 in
            #to)     gzip -c -9 "$SRC" | nc -q 0 192.168.0.101 9087 ;;
            #from)   nc -l 9087 | gzip -d > "$SRC" ;;
        #esac
    #else
        #echo 'You must specified mode - "from" or "to" and target file (optional)'
    #fi
#}