#-------- Environment Variable {{{
#------------------------------------------------------
export HISTCONTROL=ignoreboth			#Remove Extra Commands
export HISTCONTROL=erasedups			#Erase duplicates across the whole history
HISTCONTROL=ignorespace				#Space follow by a cmd,will not be saved in history
HISTCONTROL=ignoredups				#Rm Dupes, the continuous repeated entry from history 
HISTFILESIZE=3000				#Bash history size limit
HISTSIZE=1000
export HISTTIMEFORMAT="%d/%m/%y %T "		#History list shows digital time and date
# Set 256 Colors
# http://blog.sanctum.geek.nz/256-colour-terminals/
# if [ -e /usr/share/terminfo/x/xterm-256color ]; then
#    export TERM='xterm-256color'
# fi

#}}}
#-------- Exports {{{
#------------------------------------------------------
# set display
export DISPLAY=:0

# find alternative apps if it is installed on your system
find_alt() { for i;do which "$i" >/dev/null && { echo "$i"; return 0;};done;return 1; }

# Use the first program that it detects in the array as the default app
export OPENER=$(find_alt xdg-open exo-open gnome-open )
export BROWSER=$(find_alt chromium chromium-browser google-chrome firefox $OPENER )
export BROWSERCLI=$(find_alt w3m links2 links lynx elinks $OPENER )
export COMICER=$(find_alt mcomix comix zathura $OPENER )
export EBOOKER=$(find_alt ebook-viewer $OPENER ) # epub
export EDITOR=$(find_alt vim emacs nano leafpad gedit pluma $OPENER )
export FILEMANAGER=$(find_alt pcmanfm thunar nautilus dolphin spacefm enlightenment_filemanager $OPENER )
export MUSICER=$(find_alt mplayer mpg123 cvlc $OPENER )
export PAGER=$(find_alt less more most)
export PKMGR=$(find_alt yaourt pacman aptitude apt-get yum zypper emerge)
export PLAYER=$(find_alt mplayer cvlc $OPENER )
export READER=$(find_alt mupdf zathura evince $OPENER )
export ROOTER=$(find_alt gksudo kdesudo )
export IMAGEVIEWER=$(find_alt feh display eog $OPENER )

# main path
export path_doc=~/Documents
export path_dl=~/Downloads
export path_pic=~/Pictures
export path_pub=~/Public
export path_storage=~/Storage
export path_vids=~/Videos

# secondary path
export PATH_SCREENCAST=$path_pub/screencast
export PATH_SOUNDFX=$path_pub/sound-effects
export PATH_SCREENSHOT=$path_pic/screenshots

# http://sourceforge.net/projects/lesspipe/
# tutorial video: https://www.youtube.com/watch?v=ZEHxG1OhIFo
#export LESSOPEN='|/usr/bin/lesspipe.sh %s'
#export LESS='-R'

# Source-Highlight
#export LESSOPEN='|/usr/bin/src-hilite-lesspipe.sh %s'
#export LESS='R'

# http://zameermanji.com/blog/2012/12/30/using-vim-as-manpager/
# export MANPAGER="/bin/sh -c \"col -b | vim -c 'set ft=man ts=8 nomod nolist nonu noma' -\""

# http://askubuntu.com/questions/49784/how-is-bin-added-to-my-path
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/.local/bin" ] ; then
	PATH="$HOME/.local/bin:$PATH"
fi

#}}}
#-------- Color {{{
#------------------------------------------------------
# color the manpages
# tutorial video: http://www.youtube.com/watch?v=9BFaLAa428k
export LESS_TERMCAP_mb=$'\E[01;31m'             # begin blinking
export LESS_TERMCAP_md=$'\E[01;31m'             # begin bold
export LESS_TERMCAP_me=$'\E[0m'                 # end mode
export LESS_TERMCAP_se=$'\E[0m'                 # end standout-mode                 
export LESS_TERMCAP_so=$'\E[01;44;33m'          # begin standout-mode - info box 
export LESS_TERMCAP_ue=$'\E[0m'                 # end underline
export LESS_TERMCAP_us=$'\E[01;32m'             # begin underline

# color for common commands
# tutorial video: http://www.youtube.com/watch?v=RbVCzxnKJL4
if [ -x /usr/bin/dircolors ]; then
   eval "`dircolors -b`"
   alias ls='ls --color=auto'
   alias dir='dir --color=auto'
   alias vdir='vdir --color=auto'
   alias grep='grep --color=auto'
   alias fgrep='fgrep --color=auto'
   alias egrep='egrep --color=auto'
fi

# color for grep
# http://linuxaria.com/pills/coloring-grep-to-easier-research
export GREP_COLORS='0;31'

#	Color	Foreground	Background
#	Black	    30	               40
#	Red	    31	               41
#	Green	    32	               42
#	Yellow	    33	               43
#	Blue	    34	               44
#	Magenta	    35	               45
#	Cyan	    36	               46
#	White	    37	               47
#}}}
#-------- Alias {{{
#------------------------------------------------------
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."
alias ......="cd ../../../../.."
alias bc='bc -q -l'					# dont show opening msg, use math library
alias cal='cal -3'					# show 3 months
alias cp='cp -i'					# cp interactive
# alias cmus='DISPLAY=:0 && cmus'				
alias df='df -hT'					# human readable, print filetype
alias du='du -d1 -h'					# max depth, human readable
alias emacs='emacs -nw'					# cli mode
alias feh='feh -B white -g 1360x768'			# background, resolution
alias free='free -h'					# human readable
alias fu='fu -a'					# show all results
alias info='info --vi-keys'				# GNU info act like man command
alias lsblk='lsblk -o "NAME,SIZE,FSTYPE,TYPE,LABEL,MOUNTPOINT,UUID"'    # combo use lsblk or lsblk -f
alias mkdir='mkdir -p -v'				# create if not exist, verbose
alias mount='mount | column -t'				# align in column
alias mplayer='DISPLAY=:0 && mplayer'			
alias mv='mv -i'					# mv interactive
alias nano='nano -c -$'					# word wrapping
alias nvlc='nvlc --no-color'				# black/white color
alias pdfgrep='pdfgrep -in'				# ignorecase, page number
alias rm='rm -i'					# rm interactive
alias sshxforwarding='ssh -XCc blowfish-cbc,arcfour'
alias sshxtrusted='ssh -Y'
alias sr='sr -browser=$BROWSERCLI'			# cli browser
alias surfraw='surfraw -browser=$BROWSER'		# gui browser
alias srb='surfraw -browser=$BROWSER'			# surfraw bookmarks
alias trash='trash-put'
alias wget='wget -c'					# continues/resumes
alias weechat='weechat-curses'
alias youtube-viewer='youtube-viewer -C -f -4 --results=6'	# color, fullscreen, 480p, number of results
alias lsd='ls -1d */'					# ls folders only
alias l='ls -lah'
alias lst='ls -Ggthrc'					# list by time and change, newest at bottom
alias lsa='ls -GghA'	
# list and grep
lsg() {
	keyword=$(echo "$@" |  sed 's/ /.*/g')
	ls -GgthrA | grep -iE $keyword
}
## }}}
#-------- Binary / Shell Scripts {{{
#------------------------------------------------------
# https://code.google.com/p/ass2srt
# convert ass/ssa to srt subtitle
ass2srt() { ~/.scripts/ass2srt.pl $@ ;}

# http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
# display avalible colors
color-avalible() { ~/.scripts/color-avalible.sh ;}

# http://madebynathan.com/2011/08/15/bash-color-index
# display color
color-index() { ~/.scripts/color-index.sh ;}

# https://bbs.archlinux.org/viewtopic.php?pid=658127#p658127
# show color for tput
color-tput() { ~/.scripts/color-tput.sh ;}

# lightweight image viewer
# tutorial video: https://www.youtube.com/watch?v=OMOIZlOEfb8
# https://wiki.archlinux.org/index.php/Feh#File_Browser_Image_Launcher
feh-browser() { ~/.scripts/feh-browser.sh $@ -B white -g 1280x800 & }
feh-slideshow() { ~/.scripts/feh-browser.sh $@ -B white -g 1280x800 -D 3 & }

# https://github.com/bagder/curl/blob/master/perl/contrib/formfind
# easy find web forms to use with curl
formfind() { ~/.scripts/formfind.pl ;}

# searches commandlinefu.com
# tutorial video: https://www.youtube.com/watch?v=Xeni7mHIVPE
# http://samirahmed.github.com/fu/
fu-dev() { python2.7 ~/.scripts/fu/src/fu.py -a $@ ;}

# d/l wallpapers from http://interfacelift.com
# tutorial video: https://www.youtube.com/watch?v=aK4mAAScnAo
# https://github.com/gotbletu/shownotes/blob/master/interfacelift.sh
get-interfacelift() { ~/.scripts/interfacelift.sh ;}

# backup dotfiles on to github
# http://linuxtidbits.wordpress.com/2012/05/30/managing-scripts-and-configurations-on-github-with-a-script/
ghsync() { ~/.scripts/ghsync-script.sh $@ ;}

# d/l music from http://grooveshark.com
# tutorial video: https://www.youtube.com/watch?v=QX4vyEmLhsE
# https://github.com/jacktheripper51/groove-dl
groove-dl-cli() { python2.7 /usr/share/groove-dl/groove.py "$@" ;}

# multiple text highlighter
# tutorial video: https://www.youtube.com/watch?v=KkGMOYoQx6A
# https://github.com/paoloantinori/hhighlighter
# requires: ack
if [ -e ~/.scripts/hhighlighter/h.sh ]; then
	source ~/.scripts/hhighlighter/h.sh
fi

# http://code.google.com/p/imgur-cli
# imgur image uploader http://imgur.com
imgur() { python2 ~/.scripts/imgur-cli/imgur.py $@ ;}

# read apps reviews via cli (from ubuntu software center)
# tutorial video: https://www.youtube.com/watch?v=m6wfVxMTedY
# https://github.com/gotbletu/shownotes/blob/master/package_comments.py
package-comments() { python2.7 ~/.scripts/package_comments.py $@ ;}

# manual tiling (similar compiz grid plugin)
# tutorial video: https://www.youtube.com/watch?v=ZF76DELEpjM
# http://ssokolow.com/quicktile
quicktile() { python2.7 ~/.scripts/quicktile/quicktile.py $@ ;}
quicktile-daemonize() { nohup python2.7 ~/.scripts/quicktile/quicktile.py -d >/dev/null 2>&1& }
quicktile-kill () { kill $(ps -ef | grep '[q]uicktile.py' | awk '{print $2}') ;}

# http://bash.cyberciti.biz/multimedia/linux-rip-audio-cd/
rip-audio-cd() { ~/.scripts/rip_audio_cd.sh ;}

# swagbucks tv 
sbtv() { ~/.scripts/sbtv_v1.sh $@ ;}

# screenshot gallery generator 
# tutorial video: https://www.youtube.com/watch?v=_4G4nMUTzX8
# http://cli-apps.org/content/show.php/Movie+Thumbnailer?content=74676
shot() { ~/.scripts/shot.sh -n 30 -r 80% -s $@ ;}

# take screenshot fullscreen, window, area selection using import command
# http://en.gentoo-wiki.com/wiki/Screenshot
sshot() { ~/.scripts/screenshot.sh area ;}

# stream music from http://www.shoutcast.com
# tutorial video: https://www.youtube.com/watch?v=9T4VtC5Bhmo
# http://crunchbanglinux.org/forums/post/150615
shoutcast-tuner() { ~/.scripts/shoutcast_tuner.sh ;}


# catalog movies; generate html page
# tutorial video: https://www.youtube.com/watch?v=4J-ORBz7gjY
# http://smoviecat.sourceforge.net
simple-movie-catalog() { cd ~/.scripts/SimpleMovieCatalog; perl moviecat-pl -my -mf -origtitle -c config.txt ;}

# todo list manager
# tutorial video: https://www.youtube.com/watch?v=rm12kDVM1ps
# https://github.com/ginatrapani/todo.txt-cli
t() { ~/.scripts/todo.txt-cli/todo.sh $@ ;}


# search magnet links from thepiratebay
# tutorial video: https://www.youtube.com/watch?v=3lbLxx9Vlq8
# http://sourceforge.net/projects/torrtux
torrtux-dev() { ~/.scripts/torrtux-0.0.3/torrtux ;}

# Vim as a pager ( similar to the less command )
# tutorial video: https://www.youtube.com/watch?v=RefWl8I3nBg
	# issue: gg hotkey does not jump to exact line
	vlessold() { /usr/share/vim/vim73/macros/less.sh "$1" ;}
	
	# http://technotales.wordpress.com/2009/05/24/using-vim-as-a-pager/
	# vim readonly; to force write use :w!
	vless() { vim -R "$@" ;}

# search thepiratebay and torrentz.eu
# tutorial video: https://www.youtube.com/watch?v=IY56U1L6FCI
# https://github.com/saironiq/shellscripts/blob/master/thepiratebay_se/tpb.sh
# https://github.com/saironiq/shellscripts/blob/master/torrentz_eu/torrentz_eu.sh
tpb() { ~/.scripts/shellscripts/thepiratebay_se/tpb.sh $@ ;}
trz() { ~/.scripts/shellscripts/torrentz_eu/torrentz_eu.sh $@ ;}

# https://bitbucket.org/antocuni/tty2gif
# convert ttyrec to gif files
tty2gif() { python3 ~/.scripts/tty2gif/tty2gif.py $@ ;}

# https://github.com/saironiq/shellscripts/blob/master/wolframalpha_com/wa.sh 
# http://www.wolframalpha.com
wolframalpha() { ~/.scripts/shellscripts/wolframalpha_com/was.sh ;}

#}}}
#-------- Configurations {{{
#------------------------------------------------------
cfg-ag() { $EDITOR ~/.agignore ;}
cfg-aliases() { $EDITOR ~/.aliases_gotbletu ;}
cfg-amule() { $EDITOR ~/.aMule/amule.conf ;}
cfg-amuleweb() { $EDITOR ~/.aMule/remote.conf ;}
cfg-bashrc() { $EDITOR ~/.bashrc ;}
cfg-blocklist() { $EDITOR ~/.scripts/blocklist.sh ;}
cfg-centerim-binds() { $EDITOR ~/.centerim5/binds.xml ;}
# http://blog.dotsmart.net/2011/09/30/change-font-size-in-chrome-devtools/
cfg-chromium-devtoolsize() { $EDITOR ~/.config/chromium/Default/User\ StyleSheets/Custom.css ;}
cfg-chromium-noscript() { $EDITOR ~/.config/chromium/Default/Extensions/odjhifogjcknibkahlpidmdajjpkkcfn/*/CHANGE__PASSWORD__HERE.js ;}
# https://wiki.archlinux.org/index.php/Cursor_Themes#Choosing_and_Configuring_Cursor_Themes
cfg-cursor() { $EDITOR ~/.icons/default/index.theme ;}
cfg-cursor-list() { ls ~/.icons ;}
cfg-dircolors() { $EDITOR ~/.dircolors ;}
cfg-dmenu() { $EDITOR ~/.cache/dmenu_run ;}
cfg-emacs() { $EDITOR ~/.emacs ;}
cfg-emulationstation() { $EDITOR ~/.emulationstation/es_systems.cfg ;}
cfg-flexget() { $EDITOR ~/.flexget/config.yml ;}
cfg-fstab() { sudo $EDITOR /etc/fstab ;}
cfg-ghsync() { $EDITOR ~/.scripts/ghsync-script.sh ;}
cfg-gift-giftd() { $EDITOR ~/.giFT/giftd.conf ;}
cfg-gift-ui() { $EDITOR ~/.giFT/ui/ui.conf ;}
cfg-group() { sudo $EDITOR /etc/group ;}
cfg-hosts() { sudo $EDITOR /etc/hosts ;}
cfg-i3wm() { $EDITOR ~/.i3/config ;}
cfg-inputrc() { $EDITOR ~/.inputrc ;}
cfg-interfacelift() { $EDITOR ~/.scripts/interfacelift.sh ;}
cfg-lightdm() { sudo $EDITOR /etc/lightdm/lightdm.conf ;}
cfg-livestreamer() { $EDITOR ~/.livestreamerrc ;}
cfg-mcomix() { $EDITOR ~/.config/mcomix/keybindings.conf ;}
cfg-mediatomb() { $EDITOR ~/.mediatomb/config.xml ;}
cfg-mpd() { $EDITOR ~/.mpd/mpd.conf ;}
cfg-mplayer() { $EDITOR ~/.mplayer/config ;}
cfg-muttrc() { $EDITOR ~/.muttrc ;}
cfg-nanorc() { $EDITOR ~/.nanorc;}
cfg-ncmpcpp() { $EDITOR ~/.ncmpcpp/config ;}
cfg-newsbeuter() { $EDITOR ~/.newsbeuter/config ;}
cfg-newsbeuter-queue() { $EDITOR ~/.newsbeuter/queue ;}
cfg-newsbeuter-urls() { $EDITOR ~/.newsbeuter/urls ;}
cfg-pacman() { sudo $EDITOR /etc/pacman.conf ;}
cfg-pacman-mirrorlist() { sudo $EDITOR /etc/pacman.d/mirrorlist ;}
cfg-pastebinit() { $EDITOR ~/.pastebinit.xml ;}
cfg-percol() { $EDITOR ~/.percol.d/rc.py ;}
cfg-periscope() { $EDITOR ~/.config/periscope/config ;}
cfg-pianobar() { $EDITOR ~/.config/pianobar/config ;}
cfg-pianobar-libao() { sudo $EDITOR /etc/libao.conf ;}
cfg-plowshare-depositfiles() { $EDITOR ~/.config/plowshare/depositfiles.txt ;}
cfg-plowshare-netloadin() { $EDITOR ~/.config/plowshare/netloadin.txt ;}
cfg-plowshare-uploaded() { $EDITOR ~/.config/plowshare/uploaded.txt ;}
cfg-plowshare-rapidgator() { $EDITOR ~/.config/plowshare/rapidgator.txt ;}
cfg-plowshare-rapidshare() { $EDITOR ~/.config/plowshare/rapidshare.txt ;}
cfg-plowshare-random() { $EDITOR ~/.config/plowshare/random.txt ;}
cfg-pyload() { $EDITOR ~/.pyload/pyload.conf ;}
cfg-quicktile() { $EDITOR ~/.config/quicktile.cfg ;}
cfg-quicksynergy() { $EDITOR ~/.quicksynergy/synergy.conf ;}
cfg-ranger() { $EDITOR ~/.config/ranger/rc.conf ;}
cfg-ranger-rifle() { $EDITOR ~/.config/ranger/rifle.conf ;} # edit open_with extensions
cfg-ranger-commands() { $EDITOR ~/.config/ranger/commands.py ;} # scripts
cfg-samba() { sudo $EDITOR /etc/samba/smb.conf ;}
cfg-simple-movie-catalog() { $EDITOR ~/.scripts/SimpleMovieCatalog/config.txt ;}
cfg-skippyxd() { $EDITOR ~/.skippy-xd.rc ;}
cfg-sourcelist() { sudo $EDITOR /etc/apt/sources.list ;}
cfg-ssh-client() { sudo $EDITOR /etc/ssh/ssh_config ;}
cfg-ssh-daemon() { sudo $EDITOR /etc/ssh/sshd_config ;}
cfg-sudoers() { sudo $EDITOR /etc/sudoers ;}
cfg-surfraw() { $EDITOR ~/.config/surfraw/bookmarks ;}
cfg-surfraw-conf() { $EDITOR ~/.config/surfraw/conf ;}
cfg-timidity() { sudo $EDITOR /etc/timidity++/timidity.cfg ;}
cfg-tmuxrc() { $EDITOR ~/.tmux.conf ;}
cfg-tpb() { $EDITOR ~/.scripts/shellscripts/thepiratebay_se/tpb.sh ;}
cfg-transmission-daemon() { $EDITOR ~/.config/transmission-daemon/settings.json ;}
cfg-transmission-ncurse() { $EDITOR ~/.config/transmission-remote-cli/settings.cfg ;}
cfg-trz() { $EDITOR ~/.scripts/shellscripts/torrentz_eu/torrentz_eu.sh ;}
cfg-turses() { $EDITOR ~/.turses/config ;}
cfg-urlview() { $EDITOR ~/.urlview ;}
cfg-updatedb() { sudo $EDITOR /etc/updatedb.conf ;}	
cfg-vifmrc() { $EDITOR ~/.vifm/vifmrc ;}
cfg-vimrc() { $EDITOR ~/.vimrc ;}
cfg-vlcrc() { $EDITOR ~/.config/vlc/vlcrc ;}
cfg-w3m() { $EDITOR ~/.w3m/config ;}
cfg-w3m-keymap() { $EDITOR ~/.w3m/keymap ;}
cfg-xdefaults() { $EDITOR ~/.Xdefaults ;}
cfg-xinitrc() { $EDITOR ~/.xinitrc ;}
cfg-xmodmap() { $EDITOR ~/.Xmodmap ;}
cfg-xrdp() { sudo $EDITOR /etc/xrdp/xrdp.ini ;}
cfg-xrdp-xsession() { $EDITOR ~/.xsession ;}
cfg-xresources() { $EDITOR ~/.Xresources ;}
cfg-zshrc() { $EDITOR ~/.zshrc ;}
#}}}
#-------- Configurations Reload {{{
#------------------------------------------------------
rld-bashrc() { source ~/.bashrc ;}
rld-screenlayout() { ~/.screenlayout/reload_monitor.sh ;}
rld-updatedb() { sudo updatedb ;}
rld-xdefaults() { xrdb ~/.Xdefaults ;}
rld-xmodmap() { xmodmap ~/.Xmodmap ;}
rld-xresources() { xrdb -load ~/.Xresources ;}
rld-zshrc() { source ~/.zshrc ;}
# }}}

#-------- Functions {{{
#------------------------------------------------------
# call vim help page from shell prompt
function :h { vim +":h $1" +'wincmd o' +'nnoremap q :q!<CR>' ;}

# searches for manual locally or online
manned() { for arg in "$@"; do man $arg 2> /dev/null \
	|| $arg -H 2> /dev/null || $arg -h 2> /dev/null \
	|| $arg --help-all 2> /dev/null || $arg --help 2> /dev/null \
	|| help $arg 2> /dev/null \
	|| $BROWSERCLI "http://manned.org/browse/search?q=$@" 2> /dev/null \
	|| $BROWSER "http://manned.org/browse/search?q=$@" 2> /dev/null \
	|| open "http://manned.org/browse/search?q=$@" 2> /dev/null \
	|| xdg-open "http://manned.org/browse/search?q=$@" ; done ;}

# convert video to avi container
# usage: vid2avi file.mpg
vid2avi() { ffmpeg -i "$1" -vcodec mpeg4 -sameq "${1%.*}.vid2avi.avi" ;}


# quickly cd out of directories using numbers
up() { local x='';for i in $(seq ${1:-1});do x="$x../"; done;cd $x; }

# convert youtube to mp3
yt2mp3() { youtube-dl -c --restrict-filenames --extract-audio --audio-format mp3 -o "%(title)s.%(ext)s" $@ ;}

# python calculator
# press Ctrl+D to quit
# http://docs.python.org/library/math.html
# tutorial video: http://www.youtube.com/watch?v=JkyodHenTuc
calc() { python2 -ic "from __future__ import division; from math import *; from random import *" ;}

# change font size (guake terminal)
# tutorial video: http://www.youtube.com/watch?v=i9aKFgxOjwQ
chfontsize() { 
	# guake
	gconftool-2 --set '/apps/guake/style/font/style' --type string "Monospace ${1:-14}" 

	#gnome-terminal
	dconf write /org/gnome/terminal/legacy/profiles:/$(dconf list /org/gnome/terminal/legacy/profiles:/)font "'Monospace ${1:-14}'"

}

# search commandlinefu.com
cmdfu() { curl "http://www.commandlinefu.com/commands/matching/$(echo "$@" \
	| sed 's/ /-/g')/$(echo -n $@ | base64)/plaintext" ;}

# display one random command from commandlinefu.com
cmdfu-random() { echo -e "`curl -sL http://www.commandlinefu.com/commands/random/json|sed -re 's/.*,"command":"(.*)","summary":"([^"]+).*/\\x1b[1;32m\2\\n\\n\\x1b[1;33m\1\\x1b[0m/g'`\n" ;}

# check if a website is down
# usage: down4me google.com
down4me() { curl -s "http://www.downforeveryoneorjustme.com/$1" | sed '/just you/!d;s/<[^>]*>//g';}

# combine multiple pdf files into a single pdf file
# tutorial video: http://www.youtube.com/watch?v=eQoOk5Xbt3M
combine-pdf() { gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=combinedpdf_`date +'%F_%Hh%M'`.pdf -f "$@" ;}

# extract pdf pages
# http://www.linuxjournal.com/content/tech-tip-extract-pages-pdf
pdfpextr()
{
    # this function uses 3 arguments:
    #     $1 is the first page of the range to extract
    #     $2 is the last page of the range to extract
    #     $3 is the input file
    #     output file will be named "inputfile_pXX-pYY.pdf"
    #     example: pdfpextr 22 36 inputfile.pdf
    gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \
       -dFirstPage=${1} \
       -dLastPage=${2} \
       -sOutputFile=${3%.pdf}_p${1}-p${2}.pdf \
       ${3}
}





# combine multiple avi files into a single avi file
# tutorial video: https://www.youtube.com/watch?v=EAWGFJoZXAU
combine-avi() { avimerge -o combineavi_`date +'%F_%Hh%M'`.avi -i "$@" ;}

# convert doc/docx to pdf (dont upload sensitive data)
# tutorial video: http://www.youtube.com/watch?v=r90IdQwF-hs
doc2pdf() { curl -# -F inputDocument=@"$1" http://www.doc2pdf.net/convert/document.pdf > "${1%.*}.pdf" ;}

# get the chmod stats of the files
# https://bbs.archlinux.org/viewtopic.php?pid=1280296#p1280296
getmod () { stat --format "%n %a" $* | column -t; }

mkdircd() { mkdir -p -v $1; cd $1 ;}	# create folder then cd into it
cpbak() { cp $1{,.bak} ;}		# create backup copy
open() { xdg-open "$@" > /dev/null 2>&1 ;}

string-lowercase() { echo "$@" | tr '[:upper:]' '[:lower:]' ;}	# converts string to lowercase

# w3m browser with inline images
# https://plus.google.com/102499719144563443986/posts/Vja8W69iHoi
# tutorial video: http://www.youtube.com/watch?v=R2bMUtCOGko
w3mimg() { w3m -o imgdisplay=/usr/lib/w3m/w3mimgdisplay $1 ;}

# mplayer to display webcam; hit 's' to take screenshot
# https://wiki.archlinux.org/index.php/Webcam_Setup#MPlayer
# http://www.amazon.com/Logitech-960-000581-C260-Webcam/dp/B003LVZO8I
# 16:9 ; 1280x720 ; 3MP picture; 
webcam-mplayer() { mplayer tv:// -tv driver=v4l2:width=1280:height=720:device=/dev/video0 -fps 30 -vf screenshot ;}

single-to-doubles() {
# works in bash only
	for i in ?.jpg; do mv $i 0$i; done
	for i in ?.png; do mv $i 0$i; done
	for i in ?.PNG; do mv $i 0$i; done
}
doubles-to-triples() {
	for i in ??.jpg; do mv $i 0$i; done
	for i in ??.png; do mv $i 0$i; done
}
#}}}
#-------- FFMPEG X11GRAB Screencasting {{{
#------------------------------------------------------
# tutorial video: http://www.youtube.com/watch?v=mNz5Lrc06_s
# compile ffmpeg:	http://ubuntuforums.org/showthread.php?t=786095
# 			https://ffmpeg.org/trac/ffmpeg/wiki/UbuntuCompilationGuide
# proper screencast: 	http://ubuntuforums.org/showthread.php?t=1392026
# http://nowardev.wordpress.com/2011/05/23/how-to-screencast/
# https://github.com/gotbletu/shownotes/blob/master/ffmpeg_x11grab_screencast.txt
# https://dl.dropboxusercontent.com/u/28788188/cast.sh (Xpander69)
# https://support.google.com/youtube/answer/1722171?hl=en
# credit: verb3k, MocoPoloX, FakeOutdoorsman, Xpander69
# press q to quit

# Screencasting Variables# {{{
# package select (avconv or ffmpeg)
# FF_RECORDER=/usr/bin/ffmpeg
FF_RECORDER=~/Compile/ffmpeg/bin/ffmpeg

# SoundCard (pulse for pulseaudio; install pavucontrol to change pulse settings)
#            hw:0,1 for directly communicating with your soundcard
#            to get a list of sound device:
#            	arecord -l
#            	aplay -l
#            	cat /proc/asound/pcm
#            	alsamixer and hit F6
# FF_SOUNDCARD=pulse
# FF_SOUNDCARD=hw:0,1
FF_SOUNDCARD=hw:2,0
# FF_SOUNDCARD=hw:0,3

# How many threads used (0 for automatic)
FF_THREADS=0

# Resolution (use xrandr to find your resolution or use xwininfo to auto find your resolution)
#FF_RESO_MON1=1680x1050
#FF_RESO_MON2=1920x1080
#FF_RESO_FULL=$(xwininfo -root | grep 'geometry' |awk '{print $2;}' | cut -d\+ -f1)
 #FF_RESO_ALL=$(xwininfo -root | grep 'geometry' |awk '{print $2;}') #older version


# Xserver Display number(:0.0 is default; use offset for other monitor :0.0+X,Y)
FF_XDISP=:0.0
FF_XDISP_MON2=:0.0+1680,0

# Audio Device
FF_AUDIO=alsa

# Channels (Mono = 1; Dual = 2 ; dual for most devices)
FF_CHANNELS=1
# FF_CHANNELS=2


# Frames per second
FF_FPS=30

# Constant Rate Factor(0 = highest quality; 50 = lowest)
# CRF=22
FF_CRF=0

# libx264 presets (slow, fast, superfast, ultrafast; run "x264 -h" and go to preset section for more)
# additionaly run "sudo find /usr -iname '*.ffpreset'" for others
FF_PRESET=ultrafast

# Video Codec
FF_VCODEC=libx264

# Compatibility ( yuv444p for H.264, yuv420p for compatibility with outdated media players )
FF_PIXFMT=yuv444p

# Audio Codec (libmp3lame, pcm_s16le or libvorbis are most common)
# ACODEC=libvorbis
# ACODEC=pcm_s16le
FF_ACODEC=libmp3lame

# Directory where your video is gonna be saved.(include / at the end)
# DIRECTORY=$HOME/Public/
FF_DIRECTORY=$PATH_SCREENCAST/

# File name
# FILENAME=videocast`$DATE +%d%m%Y_%H.%M.%S`.mkv
FF_FILENAME=aa_screencast_baking.mkv

# ======== OPTIONAL ========
# Scale Video on the fly
# I use this for youtube since my Monitor is 1680x1050 and Youtube 720p video is 1280x720; so i scale down the resolution
# This avoids black bars on left and right side (non-fullscreen); on "fullscreen" the black bars are on top and bottom
# orginal flag: -vf scale=1280:720
FF_SCALE="scale=1280:720"

# Overwrite Output File; ( -y = yes ; -n = no )
# This only works if you use the same filename
FF_OVERWRITE="-y"
# ==========================
# }}}
# Screencasting Commands# {{{
# Monitor 1 = Benq LCD with Scaling 1680x1050 --> 1280x720 Youtube 720p
ffcast_benq() { $FF_RECORDER -f $FF_AUDIO -ac $FF_CHANNELS -i $FF_SOUNDCARD -async 1 -f x11grab -r $FF_FPS -s $FF_RESO_MON1 -i $FF_XDISP -vcodec $FF_VCODEC -pix_fmt $FF_PIXFMT -preset $FF_PRESET -crf $FF_CRF -acodec $FF_ACODEC -ab 128k -threads $FF_THREADS -vf $FF_SCALE $FF_OVERWRITE $FF_DIRECTORY$FF_FILENAME ;}

# Monitor 2 = Proscan LED TV; 1080p - 1920x1080
ffcast_proscantv() { $FF_RECORDER -f $FF_AUDIO -ac $FF_CHANNELS -i $FF_SOUNDCARD -async 1 -f x11grab -r $FF_FPS -s $FF_RESO_MON2 -i $FF_XDISP_MON2 -vcodec $FF_VCODEC -pix_fmt $FF_PIXFMT -preset $FF_PRESET -crf $FF_CRF -acodec $FF_ACODEC -ab 128k -threads $FF_THREADS $FF_OVERWRITE $FF_DIRECTORY$FF_FILENAME ;}

# fullscreen
ffcast_full() { $FF_RECORDER -f $FF_AUDIO -ac $FF_CHANNELS -i $FF_SOUNDCARD -async 1 -f x11grab -r $FF_FPS -s $FF_RESO_FULL -i $FF_XDISP -vcodec $FF_VCODEC -pix_fmt $FF_PIXFMT -preset $FF_PRESET -crf $FF_CRF -acodec $FF_ACODEC -ab 128k -threads $FF_THREADS $FF_OVERWRITE $FF_DIRECTORY$FF_FILENAME ;}
# }}}
# ------ old examples ------# {{{
#E1: ffmpeg -f alsa -ac 2 -i hw:0,1 -f x11grab -r 30 -s 1280x1024 -i :0.0 -acodec pcm_s16le -vcodec libx264 -vpre lossless_ultrafast -threads 0 out.avi
#E2: avconv -f alsa -i pulse -f x11grab -r 25 -s 1920x1080 -i :0.0 -vcodec mpeg4 -b 12000k -g 300 -bf 2 -acodec libmp3lame -ab 256k out.avi
#E3: ffmpeg -threads 0 -f alsa -i pulse -f x11grab -s 1280x720 -r 30 -i :0.0+0,0 -vcodec libx264 -preset superfast -crf 16 -acodec libmp3lame -ab 256k -ar 44100 -f mp4 out.mp4
#E4: ffmpeg -f alsa -ac 2 -i hw:0,0 -f x11grab -r 30 -s $(xwininfo -root | grep 'geometry' | awk '{print $2;}') -i :0.0 -acodec pcm_s16le -vcodec libx264 -preset ultrafast -crf 0 -threads 0 -y out.mkv
#E5: (select window); ffmpeg -f alsa -ac 2 -i hw:0,0 -f x11grab -r 30 -s $(xwininfo -frame | grep -oEe 'geometry [0-9]+x[0-9]+' | grep -oEe '[0-9]+x[0-9]+') -i :0.0+$(xwininfo -frame | grep -oEe 'Corners:\s+\+[0-9]+\+[0-9]+' | grep -oEe '[0-9]+\+[0-9]+' | sed -e 's/\+/,/' ) -acodec pcm_s16le -vcodec libx264 -preset ultrafast -crf 0 -threads 0 -y out.mkv
#E6: ffmpeg -f alsa -ac 2 -i hw:3,0 -async 1 -f x11grab -r 30 -s 1280x1024 -i :0.0 -vcodec libx264 -pix_fmt yuv444p -preset ultrafast -crf 0 -acodec libmp3lame -ab 128k -threads 0 -vf 800x600 -y out.mkv ;}
# --------------------------# }}}

#}}}
#-------- Fasd {{{
#------------------------------------------------------
# jump/open recent files and folder quickly
# https://github.com/clvv/fasd
# tutorial video: http://www.youtube.com/watch?v=ur81Y-mV5Us
if which fasd >/dev/null; then
	eval "$(fasd --init auto)"	# get fasd working, initialization code
	alias m='f -e $PLAYER'		# open with video player
	alias o='a -e $OPENER'		# open any file
	alias v='f -e $EDITOR'		# open with text editor
fi
#}}}
#-------- Plowshare {{{
#------------------------------------------------------
# d/l cyberlocker files like rapidshare, mediafire ..etc
# tutorial video: http://www.youtube.com/watch?v=5AzFdX-EyeI
# http://code.google.com/p/plowshare/
# PPA: https://launchpad.net/~plowsharepackagers
plowdown-depositfiles() { plowdown -r 3 --max-rate 900K -m ~/.config/plowshare/depositfiles.txt ;}
plowdown-uploaded() { plowdown -r 3 --max-rate 900K -m ~/.config/plowshare/uploaded.txt ;}
plowdown-netloadin() { plowdown -r 3 --max-rate 900K -m ~/.config/plowshare/netloadin.txt ;}
plowdown-rapidgator() { plowdown -r 3 --max-rate 900K -m ~/.config/plowshare/rapidgator.txt ;}
plowdown-rapidshare() { plowdown -r 3 --max-rate 900K -m ~/.config/plowshare/rapidshare.txt ;}
plowdown-random() { plowdown -r 3 --max-rate 900K -m ~/.config/plowshare/random.txt ;}

#}}}
#-------- Simple HTTP Server {{{
#------------------------------------------------------
# python http server
# tutorial video: http://www.youtube.com/watch?v=FFIjMYzkHhc
# default port = 8000
alias SimpleHTTPServer2="python2 -m SimpleHTTPServer"
alias SimpleHTTPServer3="python3 -m http.server"

# http://ubuntuguide.net/http-server-support-uploading-files-from-windows-in-ubuntu
# wget http://bones7456.googlecode.com/svn/trunk/SimpleHTTPServerWithUpload.py
# tutorial video: http://www.youtube.com/watch?v=au8DlTAHx5o
SimpleHTTPServerWithUpload() { python2 ~/.scripts/SimpleHTTPServerWithUpload.py ;}

#}}}
#-------- Ubooquity Comic Server # {{{
#------------------------------------------------------
# tutorial Video: https://www.youtube.com/watch?v=qfLG9nKt3ew
# http://vaemendis.net/ubooquity/
PATH_UBOOQUITY=~/.scripts/ubooquity
ubooquity() { cd $PATH_UBOOQUITY && nohup java -jar $PATH_UBOOQUITY/Ubooquity.jar -webadmin -headless >/dev/null 2>&1& }
ubooquity-gui() { cd $PATH_UBOOQUITY && nohup java -jar $PATH_UBOOQUITY/Ubooquity.jar -webadmin >/dev/null 2>&1& }
ubooquity-quit() { kill $(ps -ef | grep '[U]booquity.jar' | awk '{print $2}') ;}
ubooquity-status() { 
	if ps -ef | grep '[U]booquity.jar' > /dev/null
	then
		echo "Ubooquity is running on http://localhost:2202"
		echo "To change settings use http://localhost:2202/admin"
	else
		echo "Ubooquity has stopped"
	fi
}

# }}}
#-------- Transmission CLI {{{
#------------------------------------------------------
# lightweight torrent daemon, has option for cli, webui, ncurses, and gui frontend 
# tutorial video: http://www.youtube.com/watch?v=ee4XzWuapsE
# WebUI:	http://localhost:9091/transmission/web/
# 		http://192.168.1.xxx:9091/transmission/web/
tsm-clearcompleted() {
        transmission-remote -l | grep 100% | grep Done | \
        awk '{print $1}' | xargs -n 1 -I % transmission-remote -t % -r ;}
tsm() { transmission-remote --list ;}
	# numbers of ip being blocked by the blocklist
	# credit: smw from irc #transmission
tsm-count() { echo "Blocklist rules:" $(curl -s --data \
	'{"method": "session-get"}' localhost:9091/transmission/rpc -H \
	"$(curl -s -D - localhost:9091/transmission/rpc | grep X-Transmission-Session-Id)" \
	| cut -d: -f 11 | cut -d, -f1) ;}
# tutorial video: http://www.youtube.com/watch?v=TyDX50_dC0M
tsm-blocklist() { ~/.scripts/blocklist.sh ;}		# update blocklist
tsm-daemon() { transmission-daemon ;}
tsm-quit() { killall transmission-daemon ;}
tsm-altdownloadspeed() { transmission-remote --downlimit "${@:-900}" ;}	# upload default to 900K, else enter your own
tsm-altdownloadspeedunlimited() { transmission-remote --no-downlimit ;}	
tsm-limitupload() { transmission-remote --uplimit "${@:-10}" ;}	# upload default to 10kpbs, else enter your own
tsm-limituploadunlimited() { transmission-remote --no-uplimit ;}
tsm-add() { transmission-remote --add "$1" ;}
tsm-askmorepeers() { transmission-remote -t"$1" --reannounce ;}
tsm-pause() { transmission-remote -t"$1" --stop ;}		# <id> or all
tsm-start() { transmission-remote -t"$1" --start ;}		# <id> or all
tsm-purge() { transmission-remote -t"$1" --remove-and-delete ;} # delete data also
tsm-remove() { transmission-remote -t"$1" --remove ;}		# leaves data alone
tsm-info() { transmission-remote -t"$1" --info ;}
tsm-speed() { while true;do clear; transmission-remote -t"$1" -i | grep Speed;sleep 1;done ;}
tsm-grep() { transmission-remote --list | grep -i "$1" ;}

# https://github.com/fagga/transmission-remote-cli
# tutorial video: http://www.youtube.com/watch?v=hLz7ditUwY8
tsm-ncurse() { transmission-remote-cli ;}

#}}}

#-------- iPod 5G Device {{{
#------------------------------------------------------
# convert to ipod 5g compatible video format
# tutorial video: http://www.youtube.com/watch?v=gVVeR9KizBk

ipod5g() { HandBrakeCLI -i "$1" -o "${1%.*}.ipod5g.mp4" --preset="iPod" ;}
ipod5g-tsp() { tsp HandBrakeCLI -i "$1" -o "${1%.*}.ipod5g.mp4" --preset="iPod" ;}
ipod5g-rsync() { 
# https://gist.github.com/nekobato/5998548
# including trailing slashes on $SRC
# rsync $SRC/Music/ $DEST/media/Ipod
rsync -avrm --delete-excluded --modify-window=2 --include '*/' --include '*.mp3' --exclude '*' "$1" "$2" 
}

tsp-handbrake-normal() { tsp HandBrakeCLI -i "$1" -o "${1%.*}.normal.mp4" --preset="Normal" ;}
tsp-handbrake-high() { tsp HandBrakeCLI -i "$1" -o "${1%.*}.high.mp4" --preset="High Profile" ;}

# }}}
#-------- Sopcast CLI {{{
#------------------------------------------------------
# tutorial Video: http://www.youtube.com/watch?v=Dm7cFjhzgHo
# http://forum.wiziwig.eu/forums/14-Sopcast
# http://www.sopcast.com/chlist.xml
# http://sopcast.ucoz.com
# http://streams.magazinmixt.ro
# google keyword: sop://broker.sopcast

# install sopcast commandline version
# 	Archlinux: sopcast ( x64 https://www.archlinux.org/packages/multilib/x86_64/sopcast/)
# 	Archlinux: sopcast ( x32 https://www.archlinux.org/packages/community/i686/sopcast/)
# 	Ubuntu/Debian: sp-auth (https://launchpad.net/~jason-scheunemann/+archive/ppa)

# choose a players (cvlc is default)
# SP_VIDPLAYER=cvlc
SP_VIDPLAYER=(cvlc --file-caching=10000)
# SP_VIDPLAYER=vlc
# SP_VIDPLAYER=(vlc --control=lirc)
# SP_VIDPLAYER=mplayer
# SP_VIDPLAYER=(mplayer -cache 1000)

# wait X seconds to stabilize channel (make it longer if u got slower connection)
SP_SLEEP=15

# sopcast port and player port
SP_LOCAL_PORT=55050
SP_PLAYER_PORT=55051

# manually kill sopcast (sometimes it doesnt exit properly and still uses bandwidth in the background)
sppc-kill() { killall sp-sc ;}

# kills existing connection, starts a new connection, sleep X sec to stabilize the stream, waits to player to exit and kill itself
sppc() {
	killall sp-sc &>/dev/null
	(sp-sc "$1" $SP_LOCAL_PORT $SP_PLAYER_PORT &>/dev/null &)
	sleep $SP_SLEEP
	($SP_VIDPLAYER http://localhost:$SP_PLAYER_PORT) 
	wait
	killall sp-sc
}

#### eng = english, ro = romanian, esp = espanol/spanish
# added on February 06, 2014
spp-doc-explorer.eng,ro() { sppc "sop://broker.sopcast.com:3912/149269" ;}
spp-doc-history.eng,ro() { sppc "sop://broker.sopcast.com:3912/148253" ;}
spp-doc-history2.eng,ro() { sppc "sop://broker.sopcast.com:3912/149268" ;}
spp-doc-natgeo.eng,ro() { sppc "sop://broker.sopcast.com:3912/148248" ;}
spp-doc-natgeowild.eng,ro() { sppc "sop://broker.sopcast.com:3912/148259" ;}
spp-doc-nature.eng,ro() { sppc "sop://broker.sopcast.com:3912/149267" ;}
spp-movie-hbo.eng,ro() { sppc "sop://broker.sopcast.com:3912/148883" ;}
spp-movie-hbo2.eng,ro() { sppc "sop://broker.sopcast.com:3912/120702" ;}
spp-tv-universal.eng,ro() { sppc "sop://broker.sopcast.com:3912/148255" ;}
spp-tv-axn.eng,ro() { sppc "sop://broker.sopcast.com:3912/148257" ;}
spp-tv-axncrime.eng,ro() { sppc "sop://broker.sopcast.com:3912/149261" ;}

#}}}
#-------- Capture RTMP Streams {{{
#------------------------------------------------------
# tutorial video: http://www.youtube.com/watch?v=u1dQ81HT4AU
# https://github.com/gotbletu/shownotes/blob/master/rtmpdump_sniff_your_own_tutorial.txt
# http://pclosmag.com/html/Issues/201104/page19.html
sniff-begin() { sudo iptables -t nat -A OUTPUT -p tcp --dport 1935 -m owner \! --uid-owner root -j REDIRECT ;}
sniff-capture-rtmpsrv() { rtmpsrv ;}
sniff-capture-rtmpsuck() { rtmpsuck ;}
sniff-end() { sudo iptables -t nat -D OUTPUT -p tcp --dport 1935 -m owner \! --uid-owner root -j REDIRECT ;}
tsniff-begin() { sudo tcpdump -ieth0 -nn -A | grep -e"rtmp" -e"connect" -e"play" > /tmp/tcpoutput.txt ;}
tsniff-less() { less /tmp/tcpoutput.txt ;}
#}}}
#-------- Internet Videos - Porn {{{
#------------------------------------------------------
# requirements:
# 	1. install mplayer vim youtube-dl
# 	2. add this to your ~/.vimrc
# 		map <F8> :exec '!mplayer $(youtube-dl -g ' . shellescape(getline('.')) . ')' <CR><CR>
# how to use:
# 	1. fap-youporn ashlynn brooke
# 		note: if it doesnt play, try hitting right arrow key
# 	2. hit F8 on the link you want to play
# 	3. q to quit mplayer
# 	4. hit ZZ to quit vim

fap-youporn() { 
	grepmatch=$(echo "$@" | sed 's/ /.*/g')
        keyword="$(echo "http://www.youporn.com/search?query=$@&type=straight" | sed 's/ /\+/g')"
	pagenum=3
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo "$keyword&page=$num"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -dump "$line" \
	| awk '/watch/ {print $2}' | cut -d\/ -f1-6 | grep -iE $grepmatch | awk '!x[$0]++' ; done)

	echo $videourl | sed 's/\ /\n/g' | awk '!x[$0]++' | vim -R -
}

fap-youjizz() {
        keyword="$(echo "http://www.youjizz.com/search/$@" | sed 's/ /\-/g')"
	pagenum=5
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo "$keyword-$num".html""; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -dump "$line" \
	| awk '/\.com\/videos/ {print $2}' | awk '!x[$0]++' ; done)
	
	echo $videourl | sed 's/\ /\n/g' | awk '!x[$0]++' | vim -R -
}

fap-pornotube() {
        keyword="$(echo "http://www.pornotube.com/search.php?q=$@" | sed 's/ /\+/g')"
	pagenum=3
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo "$keyword&page=$num"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do	curl -s "$line" \
	| awk '/pornotube.com\/m/ && !/class/' | cut -d\" -f 2 | awk '!x[$0]++' ; done)

	echo $videourl | sed 's/\ /\n/g' | awk '!x[$0]++' | vim -R -
}

fap-xvideos() {
        keyword="$(echo "http://www.xvideos.com/?k=$@" | sed 's/ /\+/g')"
	pagenum=5
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo "$keyword&p=$num"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -dump "$line" \
	| awk '/xvideos\.com\/video/ {print $2}' | awk '!x[$0]++' ; done)

	echo $videourl | sed 's/\ /\n/g' | awk '!x[$0]++' | vim -R -
}

fap-jizzhut() {
        keyword="$(echo "http://www.jizzhut.com/search/$@" | sed 's/ /\-/g')"
	pagenum=3
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo "$keyword-$num.html"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -dump "$line" \
	| awk '/jizzhut\.com\/videos/ {print $2}' | awk '!x[$0]++' ; done)

	echo $videourl | awk '!x[$0]++' | vim -R -
}

fap-redtube() {
        keyword="$(echo "http://www.redtube.com/?search=$@" | sed 's/ /\+/g')"
	pagenum=3
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo "$keyword&page=$num"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -source "$line" \
	| awk -F\" '/class="s"/ {print $4, "http://redtube.com"$2}' | awk '!x[$0]++' ; done)

	echo $videourl | awk '!x[$0]++' | vim -R -
}


fap-spankwire() {
        keyword="$(echo "http://www.spankwire.com/search/straight/keyword/$@" | sed 's/ /\%20/g')"
	pagenum=5
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo "$keyword?Sort=Relevance&Page=$num"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -dump "$line" \
	| awk '/www\.spankwire\.com/ && /video/ {print $2}' | awk '!x[$0]++' ; done)

	echo $videourl | sed 's/\ /\n/g' | vim -R -
}

# quvi not supported anymore
fap-tnaflix() {
        keyword="$(echo "&what=$@&category=&sb=relevance&su=anytime&sd=all&dir=desc" | sed 's/ /\%20/g')"
	pagenum=3
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo \
		"http://www.tnaflix.com/search.php?page=$num$keyword"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -dump "$line" \
	| awk '/video[0-9]/ {print $2}' | awk '!x[$0]++' ; done)

	echo $videourl | sed 's/\ /\n/g' | vim -R -
}
fap-empflix() {
        keyword="$(echo "&what=$@&category=&sb=relevance&su=anytime&sd=all&dir=desc" | sed 's/ /\%20/g')"
	pagenum=3
	pagenum_to_url=$(for num in $(seq 1 "$pagenum"); do echo \
		"http://www.empflix.com/search.php?page=$num$keyword"; done )
	videourl=$(echo "$pagenum_to_url" | while read line; do lynx -dump "$line" \
	| awk '/empflix\.com\/videos/ {print $2}' | awk '!x[$0]++' ; done)

	echo $videourl | sed 's/\ /\n/g' | vim -R -
}

#}}}
#-------- Youtube Viewer {{{
#------------------------------------------------------
# tutorial video: http://www.youtube.com/watch?v=FnJ67oAxVQ4
# watch/login/comment/search/download...etc video on youtube, all from cli 
# https://github.com/trizen/youtube-viewer
yt-listen() { youtube-viewer -n $@ ;}	# no video, music/audio only
yt-music() { youtube-viewer -n --category=Music --top ;}	# show top music list
yts-movie-movieclipstrailer() { youtube-viewer -u UCi8e0iOVk1fEOogdfu4YgfA ;}
yts-amcmovietalk() { youtube-viewer -p PLBFB97E5B9494EEBD ;}
yts-amcmovietalk-mailbag() { youtube-viewer -p PLYNW0PN4_jrqlBqzAVRv3rfpo6nhzJnKp ;}
yts-amctheatres() { youtube-viewer -u amctheatres ;}
yts-afterbuzz-arrowaftershow() { youtube-viewer -p PL6THzna6gLceNeZoXKUOoDeO7cwI57rJn ;}
yts-afterbuzz-gameofthrones() { youtube-viewer -p PL0404DAD1AD037666 ;}
yts-afterbuzz-revolution() { youtube-viewer -p PL6THzna6gLccSY_0Cmoy6DvfH0iC8fyLR ;}
yts-arrowaftershow-johncampea() { youtube-viewer -p PLGYmtexynt_Egz8kNR1HbA2kiRzhM0FKv ;}
yts-alwayson() { youtube-viewer "Always On" --author=CNETTV --orderby=published --duration=long ;}
yts-btt-beyondthetrailer() { youtube-viewer -u beyondthetrailer ;}
yts-btt-thinkabouttheink() { youtube-viewer -u thinkabouttheink ;}
yts-cannatajeff() { youtube-viewer -u cannatajeff ;}
yts-comic-watchmojo() { youtube-viewer -u watchmojo ;}
yts-game-cinemassacre() { youtube-viewer -u cinemassacre ;}
yts-game-craigslistgamefinds() { youtube-viewer -u craigslistgamefinds ;}
yts-game-happyconsolegamer() { youtube-viewer -u happyconsolegamer ;}
yts-game-jamesnintendonerd() { youtube-viewer -u jamesnintendonerd ;}
yts-game-metaljesusrocks() { youtube-viewer -u metaljesusrocks ;}
yts-game-mcfrosticles() { youtube-viewer -u mcfrosticles ;}
yts-game-retroliberty() { youtube-viewer -u retroliberty ;}
yts-greatmilitarybattles() { youtube-viewer -u greatmilitarybattles ;}
yts-greentvgreentv() { youtube-viewer -u greentvgreentv ;}
yts-homeorganizing() { youtube-viewer -u homeorganizing ;}
yts-lifehacker() { youtube-viewer -u lifehacker ;}
yts-linuxgamecast() { youtube-viewer -u linuxgamecast ;}
yts-jupiterbroadcasting() { youtube-viewer -u jupiterbroadcasting ;}
yts-minimalism-carriesimple() { youtube-viewer -u UCtauuxrTG1yon8CNsgqhDkg ;}
yts-minimalism-poetskinny() { youtube-viewer -u UC4O0Vd3UxFXGX-UQNelwTag ;}
yts-minimalism-ticoandtina() { youtube-viewer -u ticoandtina ;}
yts-minimalism-unconventionalliving() { youtube-viewer -u UC7uuFb0QztC-yC2CrcS-lJw ;}
yts-minimalism-zenminimalism() { youtube-viewer -u UCpD5Hqe60AJ79fupvuA6F1Q ;}
yts-midwaysimplicity() { youtube-viewer -u midwaysimplicity ;}
yts-midwaysimplicity-mtohami() { youtube-viewer -u mtohami ;}
yts-mma-arielhelwani() { youtube-viewer -u arielhelwani ;}
yts-mma-fueltv() { youtube-viewer -u fueltv ;}
yts-mma-gracieacademy() { youtube-viewer -u gracieacademy ;}
yts-mma-graciebreakdown() { youtube-viewer -u graciebreakdown ;}
yts-mma-karynbryant() { youtube-viewer -u karynbryant ;}
yts-mma-mmaheat() { youtube-viewer -u mmaheat ;}
yts-mma-mmafightingonsbn() { youtube-viewer -u mmafightingonsbn ;}
yts-mma-thefightnetwork() { youtube-viewer -u thefightnetwork ;}
yts-mma-themmanuts() { youtube-viewer -u themmanuts ;}
yts-mma-ufc() { youtube-viewer -u ufc ;}
yts-mma-uncutsports() { youtube-viewer -u uncutsports ;}
yts-peakmoment() { youtube-viewer -u peakmoment ;}
yts-poetskinny() { youtube-viewer -u poetskinny ;}
yts-PoetskinnyUnleashed() { youtube-viewer -u PoetskinnyUnleashed ;}
yts-tinyhouse-kirstendirksen() { youtube-viewer -u kirstendirksen ;}
yts-tinyhouse-livingbigtinyhouse() { youtube-viewer -u livingbigtinyhouse ;}
yts-tinyhouse-relaxshacksDOTcom() { youtube-viewer -u relaxshacksDOTcom ;}
yts-tinyhouse-tinyhousegj() { youtube-viewer -u tinyhousegj ;}
yts-tmw-askhodgetwins() { youtube-viewer -u askhodgetwins ;}
yts-tmw-fastingtwins() { youtube-viewer -u fastingtwins ;}
yts-tmw-getfit4women() { youtube-viewer -u getfit4women ;}
yts-tmw-hodgetwins() { youtube-viewer -u hodgetwins ;}
yts-tmw-hodgetwinsonsports() { youtube-viewer -u hodgetwinsonsports ;}
yts-tmw-twinmuscleworkout() { youtube-viewer -u twinmuscleworkout ;}
yts-walkingdead() { youtube-viewer -p PLC7EC9FB2E211A261 ;}
yts-walkingdead-talkingdead() { youtube-viewer -p PLP63B9XPsQt3H_5xGXifFxFJE7-RsKFb6 ;}
yts-walkingdead-webisodes() { youtube-viewer -p PLC09448134D906619 ;}
yts-wwefannation() { youtube-viewer -u wwefannation ;}
## }}}
#-------- i3 / Openbox {{{
#------------------------------------------------------
# wallpaper path
PATH_WALLPAPER=~/Pictures/Wallpapers

chwallpaper() { 
	# http://askubuntu.com/a/125066
	# http://askubuntu.com/a/227669
	CURRENT_WM="$(wmctrl -m | grep "Name:" | awk '{print $2}')"

	# i3
	if [ $DESKTOP_SESSION = i3 ]; then
	feh --randomize --bg-fill "$PATH_WALLPAPER"/*
	fi

	# gnome shell
	# tutorial video: http://www.youtube.com/watch?v=B_VnPXy3VCw
	if [ $DESKTOP_SESSION = GNOME ]; then
	gsettings set org.gnome.desktop.background picture-uri file://"$(find $PATH_WALLPAPER -type f | shuf -n1)"
	fi

	# gnome2
	if [ $DESKTOP_SESSION = GNOME ]; then
	gconftool-2 -t str -s /desktop/gnome/background/picture_filename "$(find $PATH_WALLPAPER -type f | shuf -n1)"
	fi

	# xfce
	# tutorial video: http://www.youtube.com/watch?v=tL9uVT8D6k4
	if [[ $DESKTOP_SESSION = Xfwm4 ]] || [[ $DESKTOP_SESSION = "Xfce Session" ]]; then
	xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s \
	"$(find $PATH_WALLPAPER -type f -iregex '.*\.\(bmp\|gif\|jpg\|png\)$' | sort -R | head -1)"
	fi

	# lxde
	# tutorial video: http://www.youtube.com/watch?v=5xzfBiHuknk
	if [ $DESKTOP_SESSION = LXDE ]; then
	pcmanfm -w "$(find $PATH_WALLPAPER -type f | shuf -n1)"
	fi
	}

#}}}
#-------- System Information {{{
#------------------------------------------------------
m-sound() { cat /proc/asound/pcm && arecord -l ;} #List audio capture card
m-distro() { uname -a && lsb_release -a ;}

# uses ip or ifconfig, good on older or newer system
m-ip() {
        echo "--------------- Network Information ---------------"
	# newer system like arch
	ip addr | awk '/global/ {print $1,$2}' | cut -d\/ -f1
	ip addr | awk '/global/ {print $3,$4}'
	ip addr | awk '/ether/ {print $1,$2}'
	ip addr | awk '/scope link/ {print $1,$2}' | cut -d\/ -f1
	# older system like debian
        ifconfig | awk '/inet addr/ {print $1,$2}' | awk -F: '{print $1,$2}'
        ifconfig | awk '/Bcast/ {print $3}' | awk -F: '{print $1,$2}'
        ifconfig | awk '/inet addr/ {print $4}' | awk -F: '{print $1,$2}'
        ifconfig | awk '/HWaddr/ {print $4,$5}'
        ifconfig | awk '/Scope:Link/ {print $1,$3}' | cut -d\/ -f1
	echo Current IP $(curl -s http://checkip.dyndns.org/ | grep -o "[[:digit:].]\+")
        echo "---------------------------------------------------"
}
#}}}
#-------- Gotbletu Universal Package Manager {{{
#------------------------------------------------------
# legends# {{{
# https://wiki.archlinux.org/index.php/Pacman_Rosetta
# http://old-en.opensuse.org/Software_Management_Command_Line_Comparison
# https://bbs.archlinux.org/viewtopic.php?pid=1281605#p1281605
# Arch			-- pacman, yaourt
# Debian/Ubuntu		-- apt-get(apt), aptitude, dpkg
# Gentoo		-- eclean, emerge, equery, layman
# OpenSuse		-- zypper
# Red Hat/Fedora	-- package-cleanup, rpm, yum
# Suse			-- rug
# Not finish, only tested on Debian, Arch, Fedora so far

# cleanold; removes certain packages that can no longer be downloaded
# cleanall; remove all local cached packages
# list; show the content of an installed package
# localinstall; install package manually such as deb, rpm files downloaded
# own; find a command a package belongs to; ex: pkm-own convert
# purge; uninstall package and purge configuration files (not in /home)
# query; search for an already installed package
# refresh; update repository list
# upgrade; install the newest version from the repositories
# hold/unhold; stop/allow a package from being update
# }}}
# missing
# emerge: autoclean, purge, list, query
# rug: pkm-info, clean, autoremove, autoclean, purge, list, query
# zypper: pkm-info, autoremove, autoclean, purge, list, query
# yum: autoclean, purge
# {{{ apt-get
if [ "$PKMGR" = "apt-get" ]; then
        pkm-cleanallall() { sudo apt-get clean ;}
        pkm-cleanallold() { sudo apt-get autoclean ;}
	pkm-dependsreverse() { apt-cache rdepends "$@" ;}
	pkm-download() { wget $(apt-get --print-uris -y install "$@" | grep ^\'| cut -d\' -f2) ;}
	pkm-extract() { ar vx "$@" | tar -zxvf data.tar.gz ;}
	# same as; echo "pkgname hold" | dpkg --set-selections
	pkm-hold() { sudo apt-mark hold "$@" ;}
	pkm-hold-status() { dpkg --get-selections | awk "/${@:-hold}/" ;}
        pkm-info() { apt-cache show "$@" ;}
        pkm-install() { sudo apt-get install --no-install-recommends "$@" ;}
	pkm-list() { dpkg -L "$@" ;}
	pkm-listcache() { ls -1 /var/cache/apt/archives "$@" && \
		echo "pwd: /var/cache/apt/archives" ;}
        pkm-localinstall() { sudo dpkg -i "$@" ;}
	pkm-own() { dpkg -S $(which "$@") ;}
        pkm-pkgsearch() { apt-file search "$@" ;}
        pkm-purge() { sudo apt-get purge "$@" ;}
	pkm-query() { dpkg --get-selections | grep "$@" ;}
	pkm-refresh() { sudo apt-get update ;}
	pkm-remove() { sudo apt-get remove "$@" ;}
        pkm-remove-orphans() { sudo apt-get autoclean ;}
	pkm-search() { apt-cache search "$@" ;}
	pkm-unhold() { sudo apt-mark unhold "$@" ;}
	pkm-upgrade() { sudo apt-get update && sudo apt-get upgrade ;}
	# PPA on ubuntu base distro (not compatible with debian)
	ppa-add() { sudo add-apt-repository $@ ;}
	ppa-del() { sudo add-apt-repository -r $@ ;}
	ppa-key() { sudo apt-key add $@ ;}
	ppa-list() { ls /etc/apt/sources.list.d ;}
	ppa-purge() { sudo ppa-purge $@ ;}
	# auto get missing gpg keys from launchpad
	ppa-autokey() { sudo apt-get update 2> /tmp/keymissing; \
		for key in $(grep "NO_PUBKEY" /tmp/keymissing |sed "s/.*NO_PUBKEY //"); \
		do echo -e "\nProcessing key: $key"; gpg --keyserver pool.sks-keyservers.net \
		--recv $key && gpg --export --armor $key | sudo apt-key add -; done ;}
		# these are extra servers, just replace it if one is down
		# keyserver.ubuntu.com
		# pool.sks-keyservers.net
		# subkeys.pgp.net
		# pgp.mit.edu
		# keys.nayr.net
		# keys.gnupg.net
		# wwwkeys.en.pgp.net #(replace with your country code fr, en, de,etc)
	# }}}
# {{{ aptitude
elif [ "$PKMGR" = "aptitude" ]; then
        pkm-cleanallall() { sudo aptitude clean ;}
        pkm-cleanallold() { sudo aptitude autoclean ;}
	pkm-dependsreverse() { aptitude why "$@" ;}
	pkm-download() { aptitude download "$@" ;} # need a better 1; deb w/ depends
	pkm-extract() { ar vx "$@" | tar -zxvf data.tar.gz ;}
	pkm-hold() { echo "$1 hold" | sudo dpkg --set-selections && \
		dpkg --get-selections | awk "/$1/ && /hold/" ;}
	pkm-hold-status() { dpkg --get-selections | awk "/${@:-hold}/" ;}
        pkm-info() { aptitude show "$@" ;}
        pkm-install() { sudo aptitude install --without-recommends "$@" ;}
	pkm-list() { dpkg -L "$@" ;}
	pkm-listcache() { ls -1 /var/cache/apt/archives "$@" && \
		echo "pwd: /var/cache/apt/archives" ;}
        pkm-localinstall() { sudo dpkg -i "$@" ;}
	pkm-own() { dpkg -S $(which "$@") ;}
        pkm-pkgsearch() { apt-file search "$@" ;}
        pkm-purge() { sudo aptitude purge "$@" ;}
	pkm-query() { dpkg --get-selections | grep "$@" ;}
	pkm-refresh() { sudo aptitude update ;}
        pkm-remove() { sudo aptitude remove "$@" ;}
        pkm-remove-orphans() { sudo aptitude autoclean ;}
	pkm-search() { aptitude search "$*" ;}
		# fix  maybe with keyword $@ | sed / / ~d/ 
	pkm-search-description() { aptitude search ~d"$1"~d"$2"~d"$3"~d"$4"~d"$5"~d"$6"~d"$7" ;} 
	pkm-unhold() { echo "$1 install" | sudo dpkg --set-selections && \
		dpkg --get-selections | awk "/$1/ && /install/" ;}
	pkm-upgrade() { sudo aptitude update && sudo aptitude upgrade ;}
	# PPA on ubuntu base distro (not compatible with debian)
	ppa-add() { sudo add-apt-repository $@ ;}
	ppa-del() { sudo add-apt-repository -r $@ ;}
	ppa-key() { sudo apt-key add $@ ;}
	ppa-list() { ls /etc/apt/sources.list.d ;}
	ppa-purge() { sudo ppa-purge $@ ;}
	ppa-autokey() { sudo apt-get update 2> /tmp/keymissing; \
		for key in $(grep "NO_PUBKEY" /tmp/keymissing |sed "s/.*NO_PUBKEY //"); \
		do echo -e "\nProcessing key: $key"; gpg --keyserver pool.sks-keyservers.net \
		--recv $key && gpg --export --armor $key | sudo apt-key add -; done ;}
# }}}
# {{{ emerge
elif [ "$PKMGR" = "emerge" ]; then
        pkm-remove-orphans() { sudo emerge --depclean ;}
        pkm-cleanall() { sudo eclean distfiles ;}
        pkm-info() { emerge -S "$@" ;}
        pkm-install() { sudo emerge "$@" ;}
        pkm-pkgsearch() { equery belongs "$@" ;}
	pkm-refresh() { sudo layman -f ;}
        pkm-remove() { sudo emerge -C "$@" ;}
        pkm-search() { emerge -S "$@" ;}
        pkm-upgrade() { sudo emerge -u world ;}
# }}}
# {{{ pacman
elif [ "$PKMGR" = "pacman" ]; then
	pkm-build() { tar xvzf "$1" && cd "${1%%.tar.gz}" && makepkg -csi ;}
        pkm-cleanall() { sudo pacman -Sc ;}
        pkm-cleanold() { sudo pacman -Scc ;}
	if type -p downgrade > /dev/null; then
	# require: https://aur.archlinux.org/packages/downgrade/
		pkm-downgrade() { downgrade "$@" ;}
	fi
	pkm-download() { sudo pacman -Sw "$@" ;}
	pkm-info() { for arg in "$@"; do
		pacman -Qi $arg 2> /dev/null \
		|| pacman -Si $arg; done ;}
        pkm-install() { sudo pacman -S "$@" ;}
	pkm-key() { sudo pacman-key --init \
		&& sudo pacman-key --populate archlinux \
		&& sudo pacman-key --refresh-keys ;}
	pkm-list() { pacman -Qql "$@" ;}
	pkm-listlocal() { pacman -Qm ;}
	pkm-listcache() { ls -1 /var/cache/pacman/pkg "$@" && \
		echo "pwd: /var/cache/pacman/pkg" ;}
	pkm-localinstall() { sudo pacman --noconfirm -U "$@" ;}
	pkm-own() { pacman -Qo "$@" ;}
        pkm-pkgsearch() { pkgfile -s "$@" ;}
        pkm-purge() { sudo pacman -R "$@" ;}
        pkm-query() { pacman -Qqs "$@" ;}
        pkm-query-detail() { pacman -Qs "$@" ;}
	pkm-refresh() { sudo pacman -Syy ;}
        pkm-remove() { sudo pacman -Rcs "$@" ;}
	pkm-remove-nodepends() { sudo pacman -Rdd "$@" ;}
	pkm-remove-orphans() { sudo pacman -Rs $(pacman -Qqtd) ;}
	pkm-search() { pacman -Ss "$@" ;}
	pkm-search-local() { pacman -Qs "$@" ;}
        pkm-upgrade() { sudo pacman -Syu ;}
# }}}
# {{{ rug
elif [ "$PKMGR" = "rug" ]; then
	pkm-install() { sudo rug install "$@" ;}
	pkm-refresh() { sudo rug refresh ;}
        pkm-remove() { sudo rug remove "$@" ;}
	pkm-search() { rug search "$@" ;}
	pkm-upgrade() { sudo rug update ;}
# }}}
# {{{ yaourt
elif [ "$PKMGR" = "yaourt" ]; then
	pkm-build() { tar xvzf "$1" && cd "${1%%.tar.gz}" && makepkg -csi ;}
	pkm-cleanall() { yaourt -Sc ;}
	pkm-cleanold() { yaourt -Scc ;}
	if type -p downgrade > /dev/null; then
	# require: https://aur.archlinux.org/packages/downgrade/
		pkm-downgrade() { downgrade "$@" ;}
	fi
	pkm-download() { sudo pacman -Sw "$@" ;} # need better shit to dl from aur also
	pkm-info() { for arg in "$@"; do
		yaourt -Qi $arg 2> /dev/null \
		|| yaourt -Si $arg; done ;}
	pkm-install() { yaourt --noconfirm -S "$@" ;}
	# https://wiki.archlinux.org/index.php/Pacman-key#Resetting_all_the_keys
	pkm-key() { sudo pacman-key --init \
		&& sudo pacman-key --populate archlinux \
		&& sudo pacman-key --refresh-keys ;}
	pkm-list() { yaourt -Qql "$@" ;}
	pkm-listlocal() { yaourt -Qm ;}
	pkm-listcache() { ls -1 /var/cache/pacman/pkg "$@" && \
		echo "pwd: /var/cache/pacman/pkg" ;}
	pkm-localinstall() { sudo pacman --noconfirm -U "$@" ;}
	pkm-own() { pacman -Qo "$@" ;}
        pkm-pkgsearch() { pkgfile -s "$@" ;}
	pkm-purge() { yaourt -R "$@" ;}
	pkm-query() { pacman -Qqs "$@" ;}
	pkm-query-detail() { yaourt -Qs "$@" ;}
	pkm-refresh() { yaourt -Syy ;}
	pkm-remove() { yaourt -Rcs "$@" ;}
	pkm-remove-nodepends() { yaourt -Rdd "$@" ;}
	pkm-remove-orphans() { yaourt -Rs $(pacman -Qqtd) ;}
	pkm-search() { yaourt --noconfirm "$@" ;}
	pkm-search-local() { yaourt -Qs "$@" ;}
	pkm-upgrade() { yaourt --noconfirm -Syu ;}	# upgrade everything except aur package
	pkm-upgrade-aur() { yaourt --noconfirm -Sbua ;} # only upgrade aur package
# }}}
# {{{ yum
elif [ "$PKMGR" = "yum" ]; then
	pkm-cleanall() { sudo yum clean ;}
	pkm-depends() { sudo yum deplist "$@" ;}
	pkm-dependsreverse() { sudo yum resolvedep "$@" ;}
	pkm-info() { for arg in "$@"; do
		rpm -qi $arg 2> /dev/null || yum info $arg; done ;}
	pkm-install() { sudo yum install "$@" ;}
	pkm-list() { for arg in "$@"; do
		rpm -ql $arg 2> /dev/null || repoquery -ql --plugins $arg; done ;}
	pkm-localinstall() { sudo yum localinstall "$@" ;}
	pkm-own() { rpm -qf $(which "$@") ;}
        pkm-pkgsearch() { yum whatprovides "$@" ;}
	pkm-query() { rpm -q "$@" ;}
	pkm-refresh() { sudo yum clean expire-cache && sudo yum check-update ;}
	pkm-remove() { sudo yum remove "$@" ;}
	pkm-remove-orphans() { sudo package-cleanup --leaves ;}
	pkm-search() { yum search "$@" ;}
	pkm-upgrade() { sudo yum update ;}
# }}}
# {{{ zypper
elif [ "$PKMGR" = "zypper" ]; then
	pkm-cleanall() { sudo zypper clean ;}
	pkm-install() { sudo zypper install "$@" ;}
        pkm-pkgsearch() { zypper what-provides "$@" ;}
	pkm-refresh() { sudo zypper refresh ;}
	pkm-remove() { sudo zypper remove "$@" ;}
	pkm-search() { zypper search "$@" ;}
	pkm-upgrade() { sudo zypper update ;}
fi
# }}}
#}}}
#-------- Pastebin / Clipboard / Screenshot {{{
#------------------------------------------------------
# cli pastebin client
# tutorial video: http://www.youtube.com/watch?v=Ww7Sl4d8F8A

# http://ix.io
post-ix() { "$@" | curl -F 'f:1=<-' ix.io ;}

# copy/paste for linux machines (Mac style)
# tutorial video: http://www.youtube.com/watch?v=fKP0FLp3uW0
alias pbcopy='xclip -selection clipboard'	# copy to clipboard, ctrl+c, ctrl+shift+c
alias pbpaste='xclip -selection clipboard -o'	# paste from clipboard, ctrl+v, ctrl+shitt+v
alias pbselect='xclip -selection primary -o'	# paste from highlight, middle click, shift+insert
alias pbdump='pbpaste | pastebinit | pbcopy'	# dump text from clipboard to pastebin server and copy link


# take screenshot fullscreen, single window or draw a box
# tutorial video: http://www.youtube.com/watch?v=Hh8G1aBp8gc
pix() { scrot -d 2 "$PATH_SCREENSHOT/fullscr_`date +'%F_%Hh%Ms%S'`.png" ;}
pix-winarea() { sleep 2 && scrot -s "$PATH_SCREENSHOT/windowed_`date +'%F_%Hh%Ms%S'`.png" ;}
# take screenshot ( method 2 )
pixx() { import -pause 2 -window root "$PATH_SCREENSHOT/fullscr_`date +'%F_%Hh%Ms%S'`.png" ; }
pixx-winarea() { import -pause 2 "$PATH_SCREENSHOT/windowed_`date +'%F_%Hh%Ms%S'`.png" ;}
#screenshot-window() { import -pause 2 -frame -strip -quality 75 "$HOME/Pictures/Screenshots/pscreen-win_`date +'%F_%Hh%M'`.png" ;}


# upload to image hosting server
# tutorial video: http://www.youtube.com/watch?v=7-9uYSGyvU0
# http://www.commandlinefu.com/commands/view/9341
upl-imgur() { 
	curl -# -F image=@"$1" -F "key=1913b4ac473c692372d108209958fd15" \
	http://api.imgur.com/2/upload.xml | grep -Eo "<original>(.)*</original>" \
	| grep -Eo "http://i.imgur.com/[^<]*"
}

# }}}
#-------- Spell Checking / Translation Related {{{
#------------------------------------------------------
# spell checking
# tutorial video: http://www.youtube.com/watch?v=UEwz5eeaZzc
check-word() { echo "$1" | aspell -a ;}
check-list() { cat "$1" | aspell list ;}
check-file() { aspell check "$1" ;}

# text to speech using google
# tutorial video: http://www.youtube.com/watch?v=UhVKuAozSMc
# 	 	http://www.youtube.com/watch?v=kAjZ-6KNteU
say() { 
	# limit to 100 character or less
	# language code: http://developers.google.com/translate/v2/using_rest#language-params
	# useage: say <language code> <phase>
	# example: say es come with me
	mplayer -user-agent Mozilla \
	"http://translate.google.com/translate_tts?ie=UTF-8&tl="$1"&q=$(echo "$@" \
	| cut -d ' ' -f2- | sed 's/ /\+/g')" > /dev/null 2>&1 ;}

say-translation() { 
	# requires: http://www.soimort.org/google-translate-cli/
	# limit to 100 character or less
	# language code: http://developers.google.com/translate/v2/using_rest#language-params
	# useage: say-translation <language code> <phase>
	# example: say-translation es come with me
	lang=$1
	trans=$(translate {=$lang} "$(echo "$@" | cut -d ' ' -f2- | sed 's/ /\+/g')" )	
	echo $trans
	mplayer -user-agent Mozilla \
	"http://translate.google.com/translate_tts?ie=UTF-8&tl=$lang&q=$trans" > /dev/null 2>&1 ;}
#}}}
#-------- Fuzzy Finder {{{
#------------------------------------------------------
# https://github.com/junegunn/fzf
# tutorial video: https://www.youtube.com/playlist?list=PLqv94xWU9zZ2fMsMMDF4PjtNHCeBFbggD
fzf-dmenu() { 
	# note: xdg-open has a bug with .desktop files, so we cant use that shit
	selected="$(ls /usr/share/applications | fzf -e -i )"
	nohup `grep '^Exec' "/usr/share/applications/$selected" | tail -1 | sed 's/^Exec=//' | sed 's/%.//'` >/dev/null 2>&1&
	# disown if exit 0 successfully
	if [[ $? = 0 ]] ; then disown; fi
}
fzf-surfraw() { surfraw "$(cat ~/.config/surfraw/bookmarks | sed '/^$/d' | sort -n | fzf -e -i )" ;}
fzf-locate() { xdg-open "$(locate "*" | fzf -e -i )" ;}
fzf-playonlinux() { playonlinux --run '$(ls ~/.PlayOnLinux/shortcuts | fzf -e -i )' ;}

# edit single line snippet
cfg-snippetrc() { $EDITOR ~/.snippetrc ;}
cfg-multisnippetrc() { $EDITOR ~/.multisnippet/"$(ls ~/.multisnippet | fzf -e -i)" ;}
multisnippet() { $EDITOR ~/.multisnippet/"$1" ;}
fzf-snippet() { 
	selected="$(cat ~/.snippetrc | sed '/^$/d' | sort -n | fzf -e -i )"
	# remove tags, leading and trailing spaces, also no newline
	echo "$selected" | sed -e s/\;\;\.\*\$// | sed 's/^[ \t]*//;s/[ \t]*$//' | tr -d '\n' | xclip -selection clipboard
}
fzf-multisnippet() { 
	# location of snippets
	dir=~/.multisnippet

	# merge filename and tags into single line
	results=$(for FILE in $dir/*
	do
		getname=$(basename $FILE)
		gettags=$(head -n 1 $FILE)

		echo "$getname \t $gettags" 

	done)

	# copy content into clipboard without tags
	filename=$(echo "$(echo $results | fzf -e -i )" | cut -d' ' -f 1)
	sed 1d $dir/$filename | xclip -selection clipboard
}

#}}}
#-------- Calibre CLI v2 {{{
#------------------------------------------------------
# cross platform ebook manager supports many formats and devices
# tutorial video: http://www.youtube.com/watch?v=FeoVsC4U_0A
# http://manual.calibre-ebook.com/cli/calibredb.html
# zshrc has autocompletion
# usage:	cmx-list <library>
# 		cmx-add <library> <file>
# 		cmx-remove <library> <id> ; cmx-remove <library> <range>
# 					23,50-55; last number dont count
# 		cmx-search <library> <string> ; cmx-search <library> "<multi strings>"

# library
cbcomic=~/MA_Calibre/Comic
cbdojinshi=~/MA_Calibre/Dojinshi
cbeurotica=~/MA_Calibre/Eurotica
cbhanime=~/MA_Calibre/Hanime
cbnormal=~/MA_Calibre/Normal
cbtextbook=~/MA_Calibre/Textbook

# <command> <library> <input>
cmx-list() { calibredb list -f authors,title,tags,rating --library-path "$1" ;}
cmx-search() { calibredb list -s "${@:2}" -f authors,title,tags,rating --library-path "$1" ;}
cmx-add() { calibredb add "${@:2}" --library-path "$1" ;}
cmx-remove() { calibredb remove "${@:2}" --library-path "$1" ;}
cmx-show() { calibredb show_metadata "${@:2}" --library-path "$1" | html2text ;} #id number
cmx-recipes() { ebook-convert --list-recipes | less ;}

# content server
# http://manual.calibre-ebook.com/cli/calibre-server.html
# http://192.168.1.xxx:port
cmx-quit() { kill $(ps -ef | grep -i '[C]alibre-server' | awk '{print $2}') ;}
cmx-server() { 	calibre-server -p 57770 --daemonize --with-library "$cbcomic"
		calibre-server -p 57771 --daemonize --with-library "$cbdojinshi"
		calibre-server -p 57772 --daemonize --with-library "$cbeurotica"
		calibre-server -p 57773 --daemonize --with-library "$cbhanime"
		calibre-server -p 57774 --daemonize --with-library "$cbnormal"
		calibre-server -p 57775 --daemonize --with-library "$cbtextbook"
}

#}}}
#-------- Flexget {{{
#------------------------------------------------------
# tutorial video: http://www.youtube.com/playlist?list=PLqv94xWU9zZ0pVGrgKtMuhFHun8-MahSY
flexget-list() { flexget series list && flexget movie-queue list waiting && flexget movie-queue list downloaded ;}
flexget-check() { flexget check ;}			# check if config file has any errors
flexget-test() { flexget --test execute ;}		# dry run
flexget-execute() { flexget execute ;}
flexget-cron() { flexget execute --cron ;}		# skip writing to logs
flexget-version() { flexget -V ;}
flexget-learnall() { flexget execute --learn ;}		#bypass dling old torrents
flexget-add() { flexget movie-queue add "$@" ;}
flexget-del() { flexget movie-queue del "$@" ;}
flexget-forget() { flexget movie-queue forget "$@" ;}	# allow redownloading on waiting list
#}}}
#-------- PulseAudio Switcher CLI {{{
#------------------------------------------------------
# tutorial video: https://www.youtube.com/watch?v=jhv-2pNWfr4

pa-list() { pacmd list-sinks | awk '/index/ || /name:/' ;}
pa-set() { 
	# list all apps in playback tab (ex: cmus, mplayer, vlc)
	inputs=($(pacmd list-sink-inputs | awk '/index/ {print $2}')) 
	# set the default output device
	pacmd set-default-sink $1 &> /dev/null
	# apply the changes to all running apps to use the new output device
	for i in ${inputs[*]}; do pacmd move-sink-input $i $1 &> /dev/null; done
}
pa-playbacklist() { 
	# list individual apps
	echo "==============="
	echo "Running Apps"
	pacmd list-sink-inputs | awk '/index/ || /application.name /'

	# list all sound device
	echo "==============="
	echo "Sound Devices"
	pacmd list-sinks | awk '/index/ || /name:/'
}
pa-playbackset() { 
	# set the default output device
	pacmd set-default-sink "$2" &> /dev/null
	# apply changes to one running app to use the new output device
	pacmd move-sink-input "$1" "$2" &> /dev/null
}

# http://askubuntu.com/a/18210
pa-swap() { ~/.scripts/pulseaudio_toggle.sh ;}


#}}}
#-------- Extraction / Archive Related {{{
#------------------------------------------------------
# usage: combine-zip file.zip -- join splited zip (z01, z02 ..etc)
combine-zip() { zip -s- "$1" -O "${1%.*}"-combined.zip ;}

# usage: combine-001 file.avi.001 -- only requires the 1st file
combine-001() { lxsplit -j "$1" ;}

# compress folder into cbr/cbz
cbrit() { rar a -r "${1%/}.cbr" "$1" ;}
cbzit() { zip -r "${1%/}.cbz" "$1" ;}

atool-extract() { atool -x $@ ;}
atool-add() { apack "${1%.*}.zip" "$@" ;}
atool-append() { apack "$@" ;}	# apack foo.zip my_additional_file.jpg
atool-list() { atool -l "$1" | less -N ;}
atool-delete() { 
	local zipfilename="$1"	
	local deletefile="$(atool -l "$zipfilename" | tail -n +4 | head -n -2 | cut -d':' -f2 | cut -d' ' -f4- | sed 's/\ /\\ /g' | sed -n "${2}p")"
	
	zip -d "$zipfilename" "$deletefile"
	
	
	}

atool-zip-delete() { zip -d "$@" \*.txt ;}


imguralbum_cbz() { 
	# usage: imguralbum [link] [filename]
	
	local IMGUR_SAVE_PATH=/tmp

	# make a temp folder
	# mkdir -p "$IMGUR_SAVE_PATH"/"$2"

	#download album
	python ~/.scripts/imgur-album-downloader/imguralbum.py "$1" "$IMGUR_SAVE_PATH"/"$2"

	#create zip archive using .cbz extension for comics
	zip -r "${2%/}.cbz" "$IMGUR_SAVE_PATH"/"$2"

	#delete temp folder
	rm -rf "$IMGUR_SAVE_PATH"/"$2"
}







#}}}


mp3skull() {
        keyword="$(echo "http://mp3skull.com/mp3/$@.html" | sed 's/ /\_/g')"
	music_url=$(lynx -source "$keyword" | awk '/href/ && /\.mp3/' \
		| cut -d\" -f4 | sed 's/ /\%20/g' | awk '!x[$0]++')
	echo $music_url | sed 's/\ /\n/g' | sed 's/\%20/ /g' | vim -R -
}




# http://www.walkingrandomly.com/?p=2850
# adds leading zeros to digits in filenames

padme() {
	num=`expr match "$1" '[^0-9]*\([0-9]\+\).*'`
	paddednum=`printf "%03d" $num`
	echo ${1/$num/$paddednum}
}
zeropad() { for i in "$@" ;do mv $i `padme $i`; done ;}


# zeropad() { for i in "$@" ;do mv $i `~/.scripts/zeropad.sh $i`; done ;}



# http://www.youtube.com/watch?v=rE7ISiKoNec
web2png() { CutyCapt --url="$1" --out=web2png_output.png ;}


# url shortener
tiny-isgd() { wget -qO - "http://is.gd/create.php?format=simple&url=$1" ;}
# create qrcode
qrcode() { link=$(echo "http://qrcode.kaywa.com/img.php?s=8&d=$@" | sed 's/ /+/g'); $BROWSER $link ;}
swiggle() { find . -name *~ -delete ;}
quicktime() { mplayer -rtsp-stream-over-tcp -user-agent QuickTime/7.6.4 ;}	# -cache 3072


# http://blog.metamatt.com/blog/2013/01/09/previewing-markdown-files-from-the-terminal/
mdless(){
pandoc -s -f markdown -t man "$*" | groff -T utf8 -man | less;
}



# tutorial video: https://www.youtube.com/watch?v=Yi3JKyL-hxk
sharelin-daemon() { sharelin -d ;}
sharelin-quit() { killall sharelin ;}



# tutorial video: https://www.youtube.com/watch?v=LCr_0zFcbaM
aria2c-quit() {

	killall aria2c
	kill $(ps -ef | grep '[h]ttp.server' | awk '{print $2}')
	#kill $(ps -ef | grep '[S]impleHTTPServer' | awk '{print $2}')
	}

aria2c-webui() {

	# download location
	DIR_DL=~/Downloads

	# run as daemon
	aria2c --enable-rpc --rpc-listen-all -D -d "$DIR_DL"


	# use python simplehttpserver to host the webui 
	# this avoids download the index.html file on each computer
	# https://github.com/ziahamza/webui-aria2
	
	# path to the webui index.html
	DIR_WEBUI=~/.scripts/webui-aria2/

	# webui-aria2c uses port 6800 so we use 6801 for python_simple_http_server
	PORT=6801
	cd "$DIR_WEBUI"
	nohup python3 -m http.server "$PORT" >/dev/null 2>&1&

	# for older distro
	# nohup python2 -m SimpleHTTPServer "$PORT" >/dev/null 2>&1&
	
	echo "connect via http://localhost:$PORT or http://ip_address_of_server:$PORT"

	}



# tutorial video: https://www.youtube.com/watch?v=NG13yOTPgfY
PFLIX_PORT=55055
pfx() { ~/.scripts/peerflix_script/thepiratebay_se/tpb.sh $@ ;}
pfx-trz() { ~/.scripts/peerflix_script/torrentz_eu/torrentz_eu.sh $@ ;}
pfx-vlc() { vlc http://localhost:$PFLIX_PORT ;}
pfx-mplayer() { mplayer http://localhost:$PFLIX_PORT ;}	
    


quicksynergy-daemon() { /usr/bin/synergys --daemon --config ~/.quicksynergy/synergy.conf ;}


cleanlinks() {
	# not in the repos: inspired by http://www.xfree86.org/4.8.0/cleanlinks.1.html
	# delete empty folder
	find . -type d -empty -print0 | xargs -0 rmdir
	# delete broken symlinks
	find . -type l -xtype l | xargs -l rm 
}











# imgur album downloader
# https://github.com/alexgisby/imgur-album-downloader
# tutorial video: https://www.youtube.com/watch?v=dW4co9f5Ors
imguralbum() { python ~/.scripts/imgur-album-downloader/imguralbum.py "$@" ;}

imguralbum_cbz() { 
	# usage: imguralbum [link] [filename]
	
	local IMGUR_SAVE_PATH=/tmp

	# make a temp folder
	# mkdir -p "$IMGUR_SAVE_PATH"/"$2"

	#download album
	python ~/.scripts/imgur-album-downloader/imguralbum.py "$1" "$IMGUR_SAVE_PATH"/"$2"

	#create zip archive using .cbz extension for comics
	zip -r "${2%/}.cbz" "$IMGUR_SAVE_PATH"/"$2"

	#delete temp folder
	rm -rf "$IMGUR_SAVE_PATH"/"$2"
}



menu() { 
  { tput smcup ; clear; } >/dev/tty
  [ -n "$LINES" ] || local LINES=$(tput lines)
  local val; val=$(slmenu -i -l $((LINES-1)) -p "${1:->}")
  local ret=$?
  tput rmcup > /dev/tty
  printf %s\\n "$val"
  return $ret
}

wget-ext-url() { 
	# download all extension on a webpage
	# http://stackoverflow.com/a/18709707
	wget -r -l1 -H -t1 -nd -N -np -A "$1" -erobots=off "$2"
}

hint-bash-hotkey() { # {{{
cat <<EOF
Ctrl + A	Go to the beginning of the line you are currently typing on
Ctrl + E	Go to the end of the line you are currently typing on
Ctrl + L       	Clears the Screen, similar to the clear command
Ctrl + U	Clears the line before the cursor position. If you are at the end of the line, clears the entire line.
Ctrl + H	Same as backspace
Ctrl + R	Let’s you search through previously used commands
Ctrl + C	Kill whatever you are running
Ctrl + D	Exit the current shell
Ctrl + Z	Puts whatever you are running into a suspended background process. fg restores it.
Ctrl + W	Delete the word before the cursor
Ctrl + K	Clear the line after the cursor
Ctrl + T	Swap the last two characters before the cursor
Esc + T		Swap the last two words before the cursor
Alt + F		Move cursor forward one word on the current line
Alt + B		Move cursor backward one word on the current line
Tab		Auto-complete files and folder names
EOF
}
# }}}
hint-youtube-tagging() { # {{{
cat <<EOF
"windows 7" windows xp win vista seven win7 winxp desktop news help tips tricks tutorial review operating system software free howto guide notoolrush "Windows XP" "Windows 7"

android,droid,linux,touchscreen,smartphone,tablet,phablet,phone,operating,system,touch,screen,mobile,device,open,source,tips,tricks,apps,review,free,software,application,howto,guide,gotbletu,computer,foss,help,tutorial

lxde,lubuntu,lite,openbox,lightweight,desktop,environment,quick,interface
xfce,xubuntu,xfce4,desktop environment,gtk,interface

kubuntu,kde,kde4,plasma,desktop,kwin,qt,interface,sc,software,compilation,plasmoid,desktop,environment,widget,plasmoid

enlightenment,e17,efl,bodhi

cinnamon cinnamon2d desktop shell linux mint from freedom comes elegance gnome3

command,line,bash,sh,zsh,zshell,shell,script,cli,terminal,ncurses,curses,tui,console,text,user,interface,based,cygwin,scripting,framebuffer

unity shell unity2d unity3d desktop interface lens launcher gnome3

gnome shell gnome3 mutter clutter extension fallback mode

ubuntu debian arch linux mint computer tips tricks tutorial review open source operating system software free applications programs howto guide gotbletu distro distributions desktop news help gui

EOF
}
# }}}
hint-vim-folding() { # {{{
cat <<EOF
Vim folding commands
au BufWinLeave * mkview
au BufWinEnter * silent loadview

{visual mode} zf
zf#j creates a fold from the cursor down # lines.
zf/string creates a fold from the cursor to string .
za When on a closed fold, open it.and vice-versa.
zA When on a closed fold, open it recursively.and vice-versa
zj moves the cursor to the next fold.
zk moves the cursor to the previous fold.
zo opens a fold at the cursor.
zO opens all folds at the cursor.
zm increases the foldlevel by one.
zM closes all open folds.
zr decreases the foldlevel by one.
zR decreases the foldlevel to zero -- all folds will be open.
zd deletes the fold at the cursor.
zE deletes all folds.
[z move to start of open fold.
]z move to end of open fold.
EOF
}
# }}}
hint-vim-search-replace() { # {{{
cat <<EOF
:s/foo/bar/g		 Change each 'foo' to 'bar' in the current line.
:%s/foo/bar/g		 Change each 'foo' to 'bar' in all lines.
:5,12s/foo/bar/g	 Change each 'foo' to 'bar' for all lines from line 5 to line 12 inclusive.
:'a,'bs/foo/bar/g	 Change each 'foo' to 'bar' for all lines from mark a to mark b inclusive.
:.,$s/foo/bar/g		 Change each 'foo' to 'bar' for all lines from the current line (.)
						to the last line ($) inclusive.
:.,+2s/foo/bar/g	 Change each 'foo' to 'bar' for the current line (.) and the two next lines (+2).
:%s/foo/bar/g		 Equivalent to :1,$s/foo/bar/g (change all lines).
:g/^baz/s/foo/bar/g	 Change each 'foo' to 'bar' in each line starting with 'baz'.

/copyright oppositeslashC   	Case sensitive
/Copyright oppositeslashc     	Case insensitive
daw			delete the word under the cursor    
caw			delete the word under the cursor and put you in insert mode
diSYMBOL		delete between qoutes; or other symbols; like brackets, single qoutes ..etc
ciSYMBOL
dtSYMBOL		delete until charator
dTSYMBOL		delete until charator; backwards
EOF
}
# }}}
hint-vim-pane() { # {{{
cat <<EOF
Master key: Ctrl+W
:vsplit		:vs	v		split vertical
:split		:sp	s		split horizontal
hjkl					move between panes
q					kill a pane
:ls					show open buffer
:b [number]				open buffer with number
'}
function h-vim-hotkey() {
echo -e "
Hotkeys
--------------------
/^fred.*joe.*bill  : line beginning with fred, followed by joe then bill
/^[A-J]            : line beginning A-J
/^[A-J][a-z]\+\s   : line beginning A-J then one or more lowercase characters then space or tab
/fred\_.\{-}joe    : fred then anything then joe (over multiple lines)
/fred\_s\{-}joe    : fred then any whitespace (including newlines) then joe
/fred\|joe         : fred OR joe
#G              Go to line
C-r             redo

Navigate
C-F, C-D	pagedown
C-B, C-U	pageup
f,F	move to 1st occurance of that letter, leftwards
 : or ,		move to next or previous, using f or F

Copy / Pasting
mx then y'x     	# copy mutli lines
mx then d'x     	# cut multi lines
yw              	# copy until end of single word
y$              	# copy until end of single line
C-v,jj,I,text,Esc	#Visual Block insert front of liness
C-v,jj,$,A,text,Esc	#Visual Block append end of line

C-v,jj,x,Esc		#Visual Block delete from liness
c		change
ct<letter>	change until letter
s, S		delete char then go into insertmode, delete line then insertmode
Repeat
j.
o, O 		insert new line below, above	
c, C		change line go into insert mode
\"+y or 5\"+y	copy to x clipboard (can be used in visual mode also
EOF
}
# }}}
hint-github() { # {{{
cat <<EOF
Loginto Github make new repo then

Global setup:
 Set up git - https://help.github.com/articles/set-up-git
  git config --global user.name "Your Name"
  git config --global user.email gotbletu@gmail.com

Next steps:
  mkdir dotfiles
  cd dotfiles
  git init
  touch README
  git add README
  git commit -m 'first commit'
  git remote add origin https://github.com/gotbletu/dotfiles.git
  git push -u origin master

Existing Git Repo?
  cd existing_git_repo
  git remote add origin https://github.com/gotbletu/dotfiles.git
  git push -u origin master

Importing a Subversion Repo?
  Check out the guide for step by step instructions.
     https://help.github.com/articles/importing-from-subversion 
When youre done:
  Continue
   https://github.com/gotbletu/dotfiles

==================
mkdir code-dump
cd code-dump
git init
touch README
git add README
git commit -m 'first commit'
git remote add origin git@github.com:gotbletu/code-dump.git
git push -u origin master


------
add new ssh key; make sure openssh is installed

https://help.github.com/articles/generating-ssh-keys
EOF
}
# }}}
hint-dollarsign() { # {{{
cat <<EOF
http://linuxsig.org/files/bash_scripting.html
\$#	Stores the number of command-line arguments that were passed to the shell program.
\$_	Stores the last input
\$?	Stores the exit value of the last command that was executed.
\$0	Stores the first word of the entered command (the name of the shell program).
\$*	Stores all the arguments that were entered on the command line ($1 $2 ...).
"\$@"	Stores all the arguments that were entered on the command line, individually quoted ("\$1" "\$2" ...).
EOF
}
# }}}
hint-crontab() { # {{{
cat <<EOF
# Example 0 */5 * * * ~/Scripts/timebomb.sh > /tmp/timebomb_error.log 2>&1
alias crontab.root.gui='sudo env EDITOR=xdg-open crontab -e'                    #Root Crontab
PATH=/usr/bin:/bin:/usr/sbin:/sbin

#ArchLinux
@hourly export DISPLAY=:0 && flexget
@daily ~/Scripts/beta/interfacelift.sh          # Interfacelift.com Wallpapers
#-------- Apps
#* * * * * DISPLAY=:0.0 pcmanfm -w "$(find ~/Pictures/Wallpapers -type f | shuf -n1)"
@hourly flexget --cron
*/3 * * * * if pidof -x /usr/bin/irexec; then exit; else /usr/bin/irexec; fi &
#@hourly if pidof -x /usr/bin/transmission-daemon; then exit; else /usr/bin/transmission-daemon; fi &
#------- Scripts
@daily ~/Public/Dropbox/ShellScripts/scripts/interfacelift.sh
@daily ~/Public/Dropbox/ShellScripts/packages/Wallbase-Downloader/wallbase.sh
@weekly ~/Public/Dropbox/ShellScripts/scripts/bleachbit_cleanlist.sh
#-------- Cleanup
0 */6 * * * find ~/.local/share/Trash/files/* -mtime +14 -exec rm {} \;         #Empty Trashbin
0 */3 * * * find ~/Downloads/* -depth -type d -empty -exec rmdir {} \;          #Rm Empty folders
0 */4 * * * find ~/Downloads/* -mtime +7 -exec trash-put {} \;                  #Send to trash, older than 7days
#@hourly find ~/Downloads/* -type f -iregex [.*\.\(nzb\|torrent\)$] -exec rm {} +

#Importo
@hourly export DISPLAY=:0 && /media/Genjutsu/Scripts/packages/flexget-dev/bin/flexget
*/3 * * * * export DISPLAY=:0 && if pidof -x /usr/bin/irexec; then exit; else /usr/bin/irexec; fi &

#Cleanup
*/5 * * * * find ~/Downloads/* -iname *.nzb -exec rm {} +   #Perm Delete All NZB files
*/10 * * * * find ~/Downloads/* -iname *.torrent -exec rm {} +   #Perm Delete All Torrent files
0 */3 * * * find ~/Downloads/* -depth -type d -empty -exec rmdir {} \;  #Perm Delete Empty folders
0 */4 * * * find ~/Downloads/* -mtime +7 -exec trash {} \;      #Delete Downloaded files to trash
0 */6 * * * find ~/.local/share/Trash/files/* -mtime +14 -exec rm {} \; #Perm Delete All Trashbin files


#KDE
*/30 * * * * export DISPLAY=:0 && if pidof -x /usr/bin/transmission-qt; then exit; else /usr/bin/transmission-qt -m; fi &

#Gnome
*/30 * * * * export DISPLAY=:0 && if pidof -x /usr/bin/transmission-gtk; then exit; else /usr/bin/transmission-gtk -m; fi &

#Scripts
0 */3 * * * ~/Scripts/cronjobs/wallpaper.sh
0 3 * * * cd ~/Storage/.blackbox/dojin_incoming && sh ~/Scripts/cronjobs/rename.sh


GUI
use echo $DISPLAY
# use current screen
* * * * * DISPLAY=:0 app_name
* * * * * env DISPLAY=:0 app_name
* * * * * export DISPLAY=:0 app_name
# multiple monitors
* * * * * DISPLAY=:0.0 app_name

Common Mistake
http://askubuntu.com/questions/23009/reasons-why-crontab-does-not-work
# use absolute path
ffmpeg > to > /usr/bin/ffmpeg
# newline
older versions requires a empty line at the end of the crontab file

Ranges	use hyphens
8-11		For 8 9 10 11 hours only

List	use commas
2,3,4,5 or 0-4,8-13

Special Strings:
@reboot			Run once, at startup.
@yearly / @annually	Run once a year, "0 0 1 1 *".
@monthly		Run once a month, "0 0 1 * *".
@weekly			Run once a week, "0 0 * * 0".
@daily / @midnight	Run once a day, "0 0 * * *".
@hourly			Run once an hour, "0 * * * *".

*    *    *    *    *  command to be executed
┬    ┬    ┬    ┬    ┬
│    │    │    │    │
│    │    │    │    │
│    │    │    │    └───── day of week	(0 - 7)		[0 or 7 is Sunday, or use names - sun, mon, tue]
│    │    │    └────────── month	(1 - 12)	[or names - jan, feb, mar]
│    │    └─────────────── day of month	(1 - 31)
│    └──────────────────── hour		(0 - 23)
└───────────────────────── min		(0 - 59)
EOF
}
# }}}

# function h-framebuffer() {
# echo -e '
# mplayer -vo fbdev -fs -vf scale=1280:-3 FileName
# mplayer -vo fbdev -fs -vf scale=-3:1024 FileName
#
# on Arch linux use fbdev2
# mplayer -vo fbdev2
#
# vlc video_file
# vlc --vout fb video_file
# '}
# function h-gconf-tweaks() {
# echo -e "
# #Wallpaper Changer
# bash -c 'gconftool-2 -t str -s /desktop/gnome/background/picture_filename "$(find ~/Pictures/Wallpapers -type f | shuf -n1)"'
#
# compiz --replace
# metacity --replace
# emerald --replace
# xkill
# wineserver -k
# gnome-system-monitor
# gnome-search-tool --hidden
#
# #Dont Dim When Asking for Password
# gconftool-2 --type boolean --set /apps/gksu/disable-grab "True"
# gconftool-2 --set "/apps/metacity/general/button_layout" --type string ":close"
#
# #Button Placement
# gconftool-2 --set "/apps/metacity/general/button_layout" --type string ":minimize,maximize,close"
# gconftool-2 --set "/apps/metacity/general/button_layout" --type string ":close"
#
# #Middle Click Minimize
# gconftool-2 --set "/apps/metacity/general/action_middle_click_titlebar" --type string "minimize"
#
# #Hide Desktop Icon Drives
# gconftool-2 --set "/apps/nautilus/desktop/volumes_visible" --type boolean "false"
#
# #Disable Lock on Idle
# gconftool-2 --set "/apps/gnome-power-manager/lock/gnome_keyring_hibernate" --type boolean "false"
# gconftool-2 --set "/apps/gnome-power-manager/lock/hibernate" --type boolean "false"
# gconftool-2 --set "/apps/gnome-power-manager/lock/suspend" --type boolean "false"
#
# #Enable Metacity Compositing
# gconftool-2 --set '/apps/metacity/general/compositing_manager' --type boolean "true"
#
# #Disable Screensaver
# gconftool-2 --set '/apps/gnome-screensaver/idle_activation_enabled' --type boolean "false"
# gconftool-2 --set '/apps/gnome-screensaver/lock_enabled' --type boolean "false"
#
# #Clock Format
# gconftool-2 --set '/apps/panel/applets/clock_screen0/prefs/format' --type string "custom"
# gconftool-2 --set '/apps/panel/applets/clock_screen0/prefs/custom_format' --type string "%a %b/%d/%y, %I:%M %p"
#
# #AWN Auto Hide
# Set awn setting behavior: Custom | Autohide mode: Fade Out | Icon Effects: Simple
# gconftool-2 --set '/apps/instances/avant-window-navigator/panel-1/panel/intellihide_mode' --type string "0"
#
# #AWN OLD WAY TO AUTO HIDE
# gconftool-2 --set '/apps/awn-applet-taskmanager/intellihide' --type boolean "false"
#
# # Default Open App, LINK CLICK
# gconftool-2 -t string -s /desktop/gnome/url-handlers/magnet/command "/usr/bin/transmission-gtk %s"
# gconftool-2 -s /desktop/gnome/url-handlers/magnet/needs_terminal false -t bool
# gconftool-2 -t bool -s /desktop/gnome/url-handlers/magnet/enabled true
#
#
# "}



# mutt background fix
COLORFGBG="default;default"

jdownloader() { nohup java -jar ~/.scripts/JDownloader/JDownloader.jar >/dev/null 2>&1& }

#-------- MO SHITS {{{
#------------------------------------------------------
lxde-obkey() { obkey ~/.config/openbox/lxde-rc.xml ;}


# query wikipedia via console over dns
# http://www.commandlinefu.com/commands/view/7772
mwiki () { dig +short txt `echo $*|sed 's|  *|_|g'`.wp.dg.cx; }

# get streamed flv from chrome with lsof
# http://www.bashoneliners.com/oneliners/oneliner/159/
getchromeflv() { 
	psid=$(pgrep -f libflashplayer.so)
	cp /proc/$psid/fd/$(lsof -p $psid | grep eleted \
	| awk {' print $4 '} | sed -e "s/[a-z]//g") output.flv
}



# surfraw completions testing
# https://blogs.oracle.com/AlejandroVargas/entry/awk_examples
# removes empty line, removes comments, prints 1st word, sort abc ordered
#
showbookmarks() { awk 'NF != 0 && !/#/ {print $1}' ~/.config/surfraw/bookmarks | sort -n ;}




#http://nowardev.wordpress.com/2013/06/11/how-to-screencast-with-vlc-using-shell-on-linux-kububuntu-cvlc-with-microphone/
vlc-record() { 
cvlc screen:// --screen-fps=12 --input-slave=alsa://hw:0,0 --sout "#transcode{venc=libx264,quality:100,scale=1,fps=30,acodec=mp4a,ab=128,channels=2, samplerate=44100}:duplicate{dst=std{access=file,mux=mp4,dst=desktop.mp4}}}"
}
#-------- WINE Gaming {{{
#------------------------------------------------------
# get newest version
syu-winetrickz() { cd ~/Programs/appz/winetricks; rm -f winetricks; \
      	wget http://www.kegel.com/wine/winetricks; chmod +x winetricks ;}

# http://wiki.winehq.org/winetricks
# change wineprefix location so winetricks can be use on it
set-wineprefix() { 
	WINEPREFIX="$PWD"
	echo "ex: /home/username/.PlayOnLinux/wineprefix/Office2007" 
	echo "wineprefix is now set to: $WINEPREFIX" 
}


#}}}
#-------- VimWiki {{{
#------------------------------------------------------
wikiapps() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikiapps/index.wiki ;}
wikidroid() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikidroid/index.wiki ;}
wikigame() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikigame/index.wiki ;}
wikihaiku() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikihaiku/index.md ;}
wikimd() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikimd/index.md ;}
wikinote() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikinote/index.wiki ;}
wikislitaz() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikislitaz/index.md ;}
wikisuper() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikisuper/index.wiki ;}
wikivista() { $EDITOR $path_pub/dotfiles/private/.vimwiki/wikivista/index.wiki ;}
# }}}
#-------- Recordmydesktop CLI {{{
#------------------------------------------------------
# http://www.pclinuxos.com/forum/index.php/topic,97181.msg822796.html#msg822796
# Screen capture software
# Ctrl+C	Stop
# Ctrl+C x2	Cancle rendering
# BUG: RMD Adjusted recording window, which cuts 10 pixel from the height, thus we have to use offset -x -y
# https://wiki.archlinux.org/index.php/RecordMyDesktop
# http://sourceforge.net/p/recordmydesktop/discussion/590957/thread/cf788e96/
# https://groups.google.com/forum/#!topic/linux.debian.bugs.dist/reE8_9fqqAw
# native reso 1680x1050 -- > rmd reso 1080x1040, offset y axis -y 6
# SOUND LAG? lower the freq; 45000, 44100, 22050
# http://www.kkoncepts.net/blog/fixing-out-sync-audio-and-video-ffmpeg
RMD_OUTPUT=$PATH_SCREENCAST/bb_screencast_output.ogv

# Frequency; lower to fix sound lag; 45000, 44100, 22050
RMD_FREQ=22050

# Frames per second
RMD_FPS=30

# Channel (mono = 1 ; dual = 2)
RMD_CHANNELS=1

# SoundCard (pulse for pulseaudio; install pavucontrol to change pulse settings)
#            hw:0,1 for directly communicating with your soundcard
#            to get a list of sound device:
#            	arecord -l
#            	aplay -l
#            	cat /proc/asound/pcm
#            	alsamixer and hit F6
# FF_SOUNDCARD=pulse
# FF_SOUNDCARD=hw:0,1
RMD_SOUNDCARD=hw:3,0

rmd-all() { recordmydesktop --no-wm-check --no-frame --full-shots --fps $RMD_FPS --channels $RMD_CHANNELS --device $RMD_SOUNDCARD --freq $RMD_FREQ --overwrite -o $RMD_OUTPUT ;}

# Benq Monitor; 1680x1050 (make sure 2nd monitor is higher res)
# Initial recording window is set to:
# X:0   Y:0    Width:1680    Height:1050
# Adjusted recording window is set to:
# X:0   Y:0    Width:1680    Height:1056
rmd-benq() { recordmydesktop --no-wm-check --no-frame --full-shots --width 1680 --height 1050 --fps $RMD_FPS --channels $RMD_CHANNELS --device $RMD_SOUNDCARD --freq $RMD_FREQ --overwrite -o $RMD_OUTPUT ;}


# ProscanTV; 1920x1080 --> 1920x1072 ; X offset by 1680
# Initial recording window is set to:
# X:0   Y:0    Width:1920    Height:1080
# Adjusted recording window is set to:
# X:0   Y:4    Width:1920    Height:1072
rmd-proscantv() { recordmydesktop --no-wm-check --no-frame --full-shots -x 1680 --width 1920 --height 1072 --fps $RMD_FPS --channels $RMD_CHAN --device $RMD_DEV --freq $RMD_FREQ --overwrite -o $RMD_OUTPUT ;}

# Examples
# select window
# E1: (select window); recordmydesktop --no-frame --full-shots --fps 30 --channels 2 --freq 44100 --windowid $(xwininfo | awk '/Window id:/ {print $4}') --overwrite -o out.ogv ;}
# E2: recordmydesktop --no-wm-check --no-frame --width 1680 --height 1050 --fps 30 --channels 1 --device hw:3,0 --freq 44100 --overwrite -o out.ogv ;}
#E3: (fullscreen); recordmydesktop --no-frame --full-shots --fps 30 --channels 2 --freq 44100 --overwrite -o out.ogv ;}

#}}}
#-------- Air Comic Server # {{{
#------------------------------------------------------
# tutorial Video: http://www.youtube.com/watch?v=YceW_VcGA4A
# http://gnomewarrior32.blogspot.kr/2013/03/air-comic-server-english.html
ACSJar=~/.scripts/aircomic/AirComicServer.jar
ACSConf=~/.scripts/aircomic/AirComicServer.xml

cfg-aircomicserver() { $EDITOR $ACSConf ;}
aircomicserver() { nohup java -jar $ACSJar -c $ACSConf -n >/dev/null 2>&1& }
aircomicserver-lite() { nohup java -XX:+UseSerialGC -Xms32M -Xminf=5 -Xmaxf=10 -jar $ACSJar -c $ACSConf -n >/dev/null 2>&1& }
aircomicserver-gui() { nohup java -XX:+UseSerialGC -Xms32M -Xminf=5 -Xmaxf=10 -jar $ACSJar -c $ACSConf >/dev/null 2>&1& }
aircomicserver-quit() { kill $(ps -ef | grep '[A]irComicServer.jar' | awk '{print $2}') ;}


# }}}
#-------- Cherry Music Server # {{{
#------------------------------------------------------
# tutorial Video: https://www.youtube.com/watch?v=X2goFerMJDY

BIN_CHERRYMUSIC=~/.scripts/cherrymusic/cherrymusic
cherrymusic() { nohup python $BIN_CHERRYMUSIC --port 8442 >/dev/null 2>&1& }
cherrymusic-setup() { python $BIN_CHERRYMUSIC --setup --port 8442 ;}
cherrymusic-quit() { kill $(ps -ef | grep -i '[C]herrymusic' | awk '{print $2}') ;}
cfg-cherrymusic() { $EDITOR ~/.config/cherrymusic/cherrymusic.conf ;}

# }}}
#-------- Internet Music {{{
# http://whatnotlinux.blogspot.com/2013/02/somafm-and-digitally-imported-bash.html
somafm() {
while true; do local station;echo "Select a station to listen to:";select station in "Doomed" "Groove Salad" "Lush" "Suburbs of Goa" "Secret Agent" "Drone Zone" "Space Station" "cliqhop idm" "Digitalis" "Sonic Universe" "Boot Liquor" "Covers" "Illinois Street Lounge" "indie pop rocks" "PopTron" "Tags Trip" "Beat Bender" "Mission Control";do station=$(echo -n "$station"|tr '[:upper:]' '[:lower:]'|sed 's/ //g');break;done; mplayer -playlist http://somafm.com/startstream=${station}.pls; done;
}

difm() {
while true; do local station;echo "Select a station to listen to:";select station in "trance" "vocaltrance" "electro" "chillout" "eurodance" "house" "soulfulhouse" "funkyhouse" "tribalhouse" "harddance" "minimal" "techno" "progressive" "goapsy" "hardstyle" "hardcore" "djmixes" "lounge" "drumandbass" "classictechno" "ambient" "breaks" "futuresynthpop";do station=$(echo -n "$station"|tr '[:upper:]' '[:lower:]'|sed 's/ //g');break;done; mplayer -playlist http://www.di.fm/mp3/${station}.pls; done; 
}

#}}}
#-------- Color Bash Prompt {{{
#------------------------------------------------------
# {{{
#https://wiki.archlinux.org/index.php/Color_Bash_Prompt
# Reset
Color_Off='\e[0m'       # Text Reset

# Regular Colors
Black='\e[0;30m'        # Black
Red='\e[0;31m'          # Red
Green='\e[0;32m'        # Green
Yellow='\e[0;33m'       # Yellow
Blue='\e[0;34m'         # Blue
Purple='\e[0;35m'       # Purple
Cyan='\e[0;36m'         # Cyan
White='\e[0;37m'        # White

# Bold
BBlack='\e[1;30m'       # Black
BRed='\e[1;31m'         # Red
BGreen='\e[1;32m'       # Green
BYellow='\e[1;33m'      # Yellow
BBlue='\e[1;34m'        # Blue
BPurple='\e[1;35m'      # Purple
BCyan='\e[1;36m'        # Cyan
BWhite='\e[1;37m'       # White

# Underline
UBlack='\e[4;30m'       # Black
URed='\e[4;31m'         # Red
UGreen='\e[4;32m'       # Green
UYellow='\e[4;33m'      # Yellow
UBlue='\e[4;34m'        # Blue
UPurple='\e[4;35m'      # Purple
UCyan='\e[4;36m'        # Cyan
UWhite='\e[4;37m'       # White

# Background
On_Black='\e[40m'       # Black
On_Red='\e[41m'         # Red
On_Green='\e[42m'       # Green
On_Yellow='\e[43m'      # Yellow
On_Blue='\e[44m'        # Blue
On_Purple='\e[45m'      # Purple
On_Cyan='\e[46m'        # Cyan
On_White='\e[47m'       # White

# High Intensity
IBlack='\e[0;90m'       # Black
IRed='\e[0;91m'         # Red
IGreen='\e[0;92m'       # Green
IYellow='\e[0;93m'      # Yellow
IBlue='\e[0;94m'        # Blue
IPurple='\e[0;95m'      # Purple
ICyan='\e[0;96m'        # Cyan
IWhite='\e[0;97m'       # White

# Bold High Intensity
BIBlack='\e[1;90m'      # Black
BIRed='\e[1;91m'        # Red
BIGreen='\e[1;92m'      # Green
BIYellow='\e[1;93m'     # Yellow
BIBlue='\e[1;94m'       # Blue
BIPurple='\e[1;95m'     # Purple
BICyan='\e[1;96m'       # Cyan
BIWhite='\e[1;97m'      # White

# High Intensity backgrounds
On_IBlack='\e[0;100m'   # Black
On_IRed='\e[0;101m'     # Red
On_IGreen='\e[0;102m'   # Green
On_IYellow='\e[0;103m'  # Yellow
On_IBlue='\e[0;104m'    # Blue
On_IPurple='\e[10;95m'  # Purple
On_ICyan='\e[0;106m'    # Cyan
On_IWhite='\e[0;107m'   # White
#}}}

# Bash Prompts 2012
#PS1="\[$BBlue\]\u \t \[$BWhite\]\w \n\[$BRed\]$\[$BGreen\] "

#  \n \[\e[1;37m\]+-[\[\e[1;36m\] \d \[\e[1;31m\]\T \[\e[1;37m\]] \n\[\e[1;37m\] +-[ \[\e[1;34m\]@ \[\e[1;32m\]\w \[\e[1;37m\]]\[\e[1;35m\]---> \[\e[0;37m\]  


# Newest, use man strftime - Tron
#PS1="\n \[$BWhite\]+-[ \[$BCyan\]\u \D{%F %a %r} \w \n \[$BWhite\]+-[ ---> \[$BGreen\]"
#}}}
#-------- Load External {{{
#------------------------------------------------------
#loadbash() {
#	# checks if links is valid then dl from supported sites
#	if [[ $0 == *bash* ]]; then
#		if [ -f ~/.scripts/todo.txt-cli/todo_completion ]; then
#    			. ~/.scripts/todo.txt-cli/todo_completion
#		fi
#		#if [ -f /etc/bash_completion ]; then
#		#    . /etc/bash_completion
#		#fi
#	fi
#}
#}}}
#-------- OTHER SHIT {{{
#------------------------------------------------------

r-kde() { kbuildsycoca4 && kquitapp plasma-desktop && kstart plasma-desktop ;}
alias db='debuild -S -i -I -sa'
alias pydeb='sudo python setup.py --command-packages=stdeb.command debianize'
# --// Cleanup //--
cleanup () {
    echo -e "$red * Cleaning Thumbnails * $nc"
    rm -rfv ~/.thumbnails/*
    echo -e "$red * Removing Chromium cache *$nc"
    rm -rfv ~/.cache/chromium/*
    echo -e "$red * Removing Opera cache *$nc"
    rm -rfv ~/.opera/cache/*
    echo -e "$red * Removing Flash Player cache *$nc"
    rm -rfv ~/.adobe/Flash_Player/*
    rm -rfv ~/.macromedia/Flash_Player/*
    echo -e "$red * Cleaning Trash *$nc"
    rm -rfv ~/.local/share/Trash/*
    rm -rfv /media/kooka/.Thrash-1000/*
    echo
}
#------------------------------------------////
#		Dpkg
#------------------------------------------////

alias dp-installed='dpkg --get-selections | grep $1'
alias dp-deb-show='dpkg --info'			#to examine archive files 
alias dp-deb-content='dpkg --contents'		#to list their contents.
whichpkg() { dpkg -S $( which $1 ); }		#lookup for what package uses this command
cmdpkg() { PACKAGE=$(dpkg -S $(which $1) | cut -d':' -f1); echo "[${PACKAGE}]"; dpkg -s "${PACKAGE}" ;}


alias dp-history-install='cat /var/log/dpkg.log | grep "install "'
alias dp-history-upgrade='cat /var/log/dpkg.log | grep upgrade'
alias dp-history-remove='cat /var/log/dpkg.log | grep remove'
dp-history-rollback() { cat /var/log/dpkg.log | grep upgrade | grep "$2" -A10000000 | grep "$3" -B10000000 |awk '{print $4"="$5}';}


dp-hold()
{
echo -n "Please enter the package you wish to put a hold on:
"
read progID
echo "$progID hold" |sudo dpkg --set-selections
}

dp-unhold()
{
echo -n "Please enter the package you wish to remove the hold on:
"
read progID
echo "$progID install" |sudo dpkg --set-selections
}


#------------------------------------------////
#		Aptitude
#------------------------------------------////

killkernel() { #Removes all unused kernel, except the newest one
	dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r \
	| sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' \
	| xargs sudo apt-get -y purge ;}



# https://bbs.archlinux.org/viewtopic.php?pid=511509#p511509
ex() {
    for file in "$@"; do
        if [ -f "$file" ]; then
            local file_type=$(file -bizL "$file")
            case "$file_type" in
                *application/x-tar*|*application/zip*|*application/x-zip*|*application/x-cpio*)
                    bsdtar -x -f "$file" ;;
                *application/x-gzip*)
                    gunzip -d -f "$file" ;;
                *application/x-bzip*)
                    bunzip2 -f "$file" ;;
                *application/x-rar*)
                    7z x "$file" ;;
                *application/octet-stream*)
                    local file_type=$(file -bzL "$file")
                    case "$file_type" in
                        7-zip*) 7z x "$file" ;;
                        *) echo -e "Unknown filetype for '$file'\n$file_type" ;;
                    esac ;;
                *)
                    echo -e "Unknown filetype for '$file'\n$file_type" ;;
            esac
        else
            echo "'$file' is not a valid file"
        fi
    done
}


# https://bbs.archlinux.org/viewtopic.php?pid=769431#p769431
fls() { find "$@" -printf "\033[38;5;172m%M\033[38;5;104m %TY-%Tm-%Td\033[0m ▎ \033[38;5;100m%d\033[38;5;197m%y\033[0m ▎ %f\033[38;5;190m ->\033[0m(\033[38;5;166m%.20P\033[0m) \n" ;}

# https://bbs.archlinux.org/viewtopic.php?pid=813074#p813074
blight() { sudo sh -c "echo $1 > /sys/class/backlight/psblvds/brightness" ;}


#curl -s http://tinyurl.com/create.php?url=http://<website.url>/ | sed -n 's/.*\(http:\/\/tinyurl.com\/[a-z0-9][a-z0-9]*\).*/\1/p' | uniq



alias magnet-to-torrent="aria2c -q --bt-metadata-only --bt-save-metadata"



#gen-cron-trim() {
#sudo echo '
##!/bin/sh
#LOG=/var/log/trim.log
#echo "*** $(date -R) ***" >> $LOG
#fstrim -v / >> $LOG 
## check if it works for each parition before saving this
## use: sudo fstrim -v $1 to check
#' >> /etc/cron.daily/trim
#echo 'created /etc/cron.daily/trim'
#;}


# http://www.webupd8.org/2013/01/enable-trim-on-ssd-solid-state-drives.html
trim-check() {
#	sudo hdparm -I /dev/sda | grep "TRIM supported"
	sudo hdparm -I /dev/"$1" | awk '/.*TRIM supported.*/{ if ($1 == "*") print "Yes, TRIM is enabled"; else print "No, TRIM is not enabled." ;}'
}
trim-fstrim() { sudo fstrim -v "$1" ;}
gen-cron-trim() { sudo cp ~/.scripts/trim /etc/cron.daily/ ;}




alias dog='src-hilite-lesspipe.sh'


midplayer() { adlmidi "$1" > /dev/null 2>&1 ;}

# https://wiki.archlinux.org/index.php/FluidSynth#Standalone_mode
midi-fluidsynth() { fluidsynth -a alsa -m alsa_seq -l -i /usr/share/soundfonts/fluidr3/FluidR3GM.SF2 "$1" ;}







ocr2clipboard() { 
	# folder to dump it to
	DIR=/tmp
	
	# scale up the image resolution for better ocr-ing
	convert "$1" -resize 5000 "$DIR"/image_out.png
	# ocr the scaled image
	tesseract "$DIR"/image_out.png "$DIR"/result
	# copy to the clipboard
	xclip -selection clipboard -i "$DIR"/result.txt
}


#}}}
#-------- DUMPSTER {{{
#------------------------------------------------------

# https://bbs.archlinux.org/viewtopic.php?pid=601946#p601946
function define ()
{
    dictionary="english"
    [[ "$2" != "" ]] && dictionary=$2
    echo "DEFINE $dictionary $1\nQUIT" | netcat dict.org 2628
}

aptsearch() { apt-cache search ^$1 | egrep --color=always "^[^-]+ "; }




function apt-history(){
      case "$1" in
        install)
              cat /var/log/dpkg.log | grep 'install '
              ;;
        upgrade|remove)
              cat /var/log/dpkg.log | grep $1
              ;;
        rollback)
              cat /var/log/dpkg.log | grep upgrade | \
                  grep "$2" -A10000000 | \
                  grep "$3" -B10000000 | \
                  awk '{print $4"="$5}'
              ;;
        *)
              cat /var/log/dpkg.log
              ;;
      esac
}

#List files only, the advantage is that it works just like normal 'ls' so you could do 'lf -al | grep blah' etc.
lf () {
ls -1p $@ | grep -v '\/$'
}

#Compression (cd into dir, will compress every single folder)
alias tardir='for i in *; do if [ -d "$i" ]; then tar czf "$i".tar.gz  "$i"; fi; done'
alias rardir='find * -maxdepth 0 -type d -exec rar a {}.rar {} \;'
	#Warning: removes dir after compression (below)
alias rarkill='find * -maxdepth 0 -type d -exec rar a -df {}.rar {} \;'
#http://www.commandlinefu.com/commands/view/5198
# $ ls | while read filename; do tar -czvf "$filename".tar.gz "$filename"; rm "$filename"; done
 
function    osr              { shutdown -r now; }
function    osh              { shutdown -h now; }
 
function    mfloppy          { mount /dev/fd0 /mnt/floppy; }
function    umfloppy         { umount /mnt/floppy; }
 
function    mdvd             { mount -t iso9660 -o ro /dev/dvd /mnt/dvd; }
function    umdvd            { umount /mnt/dvd; }
 
function    mcdrom           { mount -t iso9660 -o ro /dev/cdrom /mnt/cdrom; }
function    umcdrom          { umount /mnt/cdrom; }
 
 
function    dub              { du -sclb $@; }
function    duk              { du -sclk $@; }
function    dum              { du -sclm $@; }
 
function    dfk              { df -PTak $@; }
function    dfm              { df -PTam $@; }
function    dfh              { df -PTah $@; }
function    dfi              { df -PTai $@; }

#}}}
#-------- POOPER {{{
#------------------------------------------------------

qrdecode() { zbarimg -S\*.disable -Sqrcode.enable "$1" -q | sed '1s/^[^:]\+://'; }

#checkexist() {
#if which lynx >/dev/null; then
#    echo exists
#else
#    echo does not exist
#fi
#}

pvcp() {
	# a better cp with pv; http://jrenard.info/blog/a-better-cp-with-pv.html
	SOURCE=$1
	
	if [ -d $2 ]
	then
	    DESTINATION=$2/`basename $SOURCE`
	else
	    DESTINATION=$2
	fi
	
	pv ${SOURCE} | > ${DESTINATION}
}

# http://www.falsyana.com/2010/linux/cp-mv-with-a-progress-bar/
# http://unix.stackexchange.com/questions/2577/move-files-with-progress-bar
# slower then regular mv or cp
#alias cp='rsync --progress -ah'
#alias mv='rsync --progress -ah --remove-sent-files'



# Readablity CLI
# Removes junk from websites and just give you the body of the post
# requires python2-2.7 & python2-chardet
# https://github.com/buriy/python-readability
# ebook-convert from http://manual.calibre-ebook.com/cli/ebook-convert.html
readability2html() { 
	python2.7 -m readability.readability -u "$1" > /tmp/"$2".html
	ebook-convert /tmp/"$2".html ~/Downloads/"$2".epub
}


#http://www.reddit.com/r/commandline/comments/19ept5/open_discussion_cool_trick_thursday_what_are_your/c8neljz
#cd to mp3 ripper
audiocd_to_mp3() { cdparanoia -B ; for f in *.wav ; do sox -S $f "${f%.wav}.mp3" ; rm $f ; done ;}
audiocd_to_iso() { use dd or ddrescure or readom ;}

unlock() { keepassc -d $path_pub/dotfiles/private/.keepass/masterlock.kdb ;}

ripit-mydefault() { 
	ripit -o ~/Downloads -p 0 -c 0 --nointeraction "$@"
	# -p ; playlist (m3u file) 0=disable
	# --nointeraction; use 1st CDDB it finds
	# -c ; 0 - Lame (for mp3), 1 - Oggenc, 2 - Flac, 3 - Faac,
	# 	4 - mp4als, 5 - Musepack, 6 - Wavpack, 7 - ffmpeg
	# $@ ; specfic tracks like 1-4,5,8
	}

# }}}
#-------- One Off {{{
#------------------------------------------------------
compile-cpp() { g++ -Wall -o "${1%.cpp}" "$1" ; }



# Arch linux
alias update-grub='sudo grub-mkconfig -o /boot/grub/grub.cfg'

# http://www.commandlinefu.com/commands/view/954
symlinks() { find . -type l ! -exec test -e {} \; -print ;}
symlinks-delete() { find . -type l ! -exec test -e {} \; -print0 | xargs -0 rm ;}
#mplayer playlist
mplist(){ mplayer -playlist <(tree -aif "$1" | awk '/\.(mp3|wav|ogg|avi|mpg|iso)$/'); }
#mplist(){ mplayer -playlist <(find "$1" -regex '.*\.\(mp3\|wav\|ogg\|avi\|mpg\|iso\)' | sort); }
#}}}
#-------- More Junk {{{
#------------------------------------------------------

zombie-process() { ps aux | awk '{ print $8 " " $2 }' | grep -w Z ;}

#------------------------------------------////
#		DUMP
#------------------------------------------////

rm-except() {
	find . -type f -not -name '*copy*' | xargs rm
}


alias showexe='~/Scripts/beta/exeplz.sh'
getexe() {
	TEMPFILE1=$(mktemp)
	TEMPFILE2=$(mktemp)
	INPUTFILE="$1"
	        # Extract raw version resource:
        wrestool --extract --raw --type=version "$INPUTFILE" > $TEMPFILE1

        if [ -s $TEMPFILE1 ]
        then
                # Search for a sane version string.
                # This (especially the final regexp) took me really long time to figure out. Am I that lame?
                VERSION=$(< $TEMPFILE1 \
                        tr '\0, ' '\t.\0' \
                        | sed 's/\t\t/_/g' \
                        | tr -c -d '[:print:]' \
                        | sed -r -n 's/.*Version[^0-9]*([0-9]+\.[0-9]+(\.[0-9][0-9]?)?).*/\1/p'
                )
		echo $VERSION
        fi
}






function etym(){
    for term in "$@"
    do
        url="etymonline.com/index.php?term=$term"
        curl -s $url | grep "<dd " |
                sed -e 's/<a[^>]*>\([^<]*\)<[^>]*>/:\1:/g' -e 's/<[^>]*>//g' |
                fold -sw `[ $COLUMNS -lt 80 ] && echo $COLUMNS || echo 79 `
        echo
    done
}

alias kde-refresh='kbuildsycoca4'


alias rardir='find * -maxdepth 0 -type d -exec rar a {}.rar {} \;'

DISTRO=$(cat /etc/*-release | head -1 | awk -F\" '{print $(NF-1)}')

alias stackexchange='lynx http://column80.com'

alias cls='printf "\033c"' # real clear screen, no scroll back buffer

iso-mount() {
	DIR=/tmp/ISO_Mounted_Image
	# check if directory doesnt exist then create
	if [ ! -d "$DIR" ]; then
		mkdir "$DIR"
	fi
	sudo mount -o loop "$1" "$DIR"
	echo "Your Image is mounted at: \e[0;33m $DIR"
}
iso-unmount() {
	DIR=/tmp/ISO_Mounted_Image
	sudo umount "$DIR"
}

alias m-windowmanager="wmctrl -m | grep "Name:" | awk '{print $2}'"
mbuffer() {
	mplayer -vo fbdev $1 -fs -subcp ${2:-cp1251} -vf scale=${3:-1280:720}
}
# MPlayer on /dev/ttyN
  alias fbmplayer='mplayer -vo fbdev2 -vf scale=1280:1024 "$@"'
d-swiggle() { find . -type f -name '*~' -exec rm -v {} \; ;}
d-url() { find . -type f -iname '*.url' -exec rm -v {} \; ;}
d-thumbsdb() { find . -type f -iname 'Thumbs.db' -exec rm -v {} \; ;}
findopen() { local PS3="select file: "; select file in $(find "$1" -iname "$2"); do ${3:-xdg-open} $file; break; done ;}
alias renameit="ls | rename -v 's/ /_/g'"	#change files with spaces to underscore
alias podget-cleanup='find ~/Downloads/.podget -mtime +7 -type f -name "*.mp3" -exec rm -fv {} \;'


#if [ "$PS1" ]; then                             #Add Auto Complete to commands that dont work normally
#complete -cf ebook-convert 
#fi


lanshare() {
	echo "Test Server: http://127.0.0.1:8000 or http://localhost:8000"
	echo "Server IP (LAN): $(ifconfig eth0 | awk '/inet / {print $2}' | cut -d\: -f2):8000"
	echo "Server IP (WWW): $(curl -s http://checkip.dyndns.org/ | grep -o "[[:digit:].]\+"):8000"
	echo "Hit Ctrl+C to Stop Sharing"
	python -m SimpleHTTPServer
}

function whichpkgi2() { readlink -f "$(which $1)" | xargs --no-run-if-empty dpkg -S; }

#alias mplall="mplayer -loop 0 -playlist <(find \"$PWD\" -type f | egrep -i '(\.mp3|\.wav|\.flac|\.ogg|\.avi|\.flv|\.mpeg|\.mpg)'| sort)"



fail-upgrade() { # When Fail upgrade, reinstalls all packages and reconfigures automatically
	sudo dpkg-reconfigure -phigh -a; }
fail-install() { sudo apt-get install -f; } # Fix broken package

alias unity.support.test='/usr/lib/nux/unity_support_test -p'
alias unity.reset='unity --reset &'
alias unity.reset.icon='unity --reset-icons'
alias compiz.reset.config='gconftool-2 --recursive-unset /apps/compiz-1 && unity --reset'
alias compiz.replace.ccp='compiz --replace ccp &' #ccp loads last config setting
alias alien.fakeroot='fakeroot alien'
alias startup.apps.root='cd /etc/xdg/autostart'
alias startup.apps.local='cd ~/.config/autostart'
alias autologin.shell='sudo /usr/lib/lightdm/lightdm-set-defaults -s gnome-shell'
alias krunner.restart='killall krunner && krunner &'
gcl.docs.list() { google docs list | cut -d\, -f1 | awk '{ x = $0 "\n" x } END { printf "%s", x }' ;}
gcl.docs.edit() { google docs edit --title ""$1"" --editor vim ;}

#}}}
#-------- Web Search Prefix {{{
#------------------------------------------------------
# Custom seaches
gg-comic() { sitelist=$(echo "avaxhome.ws h33t.com mycomicpost.com bdcomics.bdgamers.net" \
	  	| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-cyberlocker() { sitelist=$(echo "hotfile.com rapidshare.com mediafire.com 
	uploading.com depositfiles.com zshare.net filepost.com filefactory.com 
	2shared.com zippyshare.com slingfile.com wuala.com filetram.com 
	4shared.com rabidfiles.com" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-dojin() { sitelist=$(echo "hentairules.net fakku.net hentaifromhell.net" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-icons() { sitelist=$(echo "iconseeker.com iconarchive.com iconfinder.com 
	deviantart.com veryicon.com iconspedia.com" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-keygen() { sitelist=$(echo "crack.ms/cracks/crack.ms?id" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-music() { url=$(echo "https://encrypted.google.com/search?hl=en&q=
	intitle:index.of+mp3+"$@"+-html+-htm+-txt"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-packages() { sitelist=$(echo "sourceforge.net github.com archlinux.org/packages 
	freecode.com/projects gnome.org/extension python.org/pypi gentoo.org/package" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-pastebin() { sitelist=$(echo "pastebin.com paste2.org pastie.org snipt.net 
	heypasteit.com/clip pastee.org shell-fu.org commandlinefu.com catonmat.net 
	linuxconfig.net github.com bitbucket.org slexy.org stackoverflow.com 
	askubuntu.com superuser.com dotfiles.org dotshare.it gitorious.org 
	serverfault.com wikia.com stackexchange.com" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-piratebay() { url=$(echo "http://thepiratebay.org/search/$@" \
		| sed 's/ /+/g'); $BROWSER $url; }
gg-porn() { sitelist=$(echo "youporn.com redtube.com xvideos.com xhamster.com 
	tube8.com grayvee.com pornhub.com/view_video.php?viewkey tnaflix.com 
	youjizz.com hardsextube.com/video drtuber.com/video pornoxo.com limesteam.com
       	motherless.com xnxx.com cliphunter.com extremetube.com/video" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-reader() { url=$(echo "https://encrypted.google.com/reader/view/#search/$@" \
		| sed 's/ /+/g'); $BROWSER $url; }
gg-search() { url=$(echo "https://encrypted.google.com/search?hl=en&q=$@" \
		| sed 's/ /+/g'); $BROWSER $url; }
gg-serial() { sitelist=$(echo "freeserials.com/serials/download.php?id= serials.ws/d.php?n" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-torrent() { sitelist=$(echo "eztv.it thepiratebay.se torrentzap.com fenopy.com 
	torrindex.com h33t.com tokyotosho.info nyaa.eu" \
		| sed 's/ /\+OR\+site\:/g')
	url=$(echo "https://encrypted.google.com/search?hl=en&q=$@+site:$sitelist"\
		| sed 's/ /+/g'); $BROWSER $url; }
gg-translate() {
	$BROWSER http://translate.google.com/#auto/en/"$*" ;}

#}}}
#-------- MPS-Youtube {{{
#------------------------------------------------------
# tutorial video: https://www.youtube.com/watch?v=VE2iCBkIs8E
mpsyt-amcmovietalk() { mpsyt pl "http://www.youtube.com/playlist?list=PLBFB97E5B9494EEBD" ;}
mpsyt-amcmovietalk-mailbag() { mpsyt pl "http://www.youtube.com/playlist?list=PLYNW0PN4_jrqlBqzAVRv3rfpo6nhzJnKp" ;}
mpsyt-amctheatres() { mpsyt user amctheatres ;}
mpsyt-afterbuzz-arrowaftershow() { mpsyt pl PL6THzna6gLceNeZoXKUOoDeO7cwI57rJn ;}
mpsyt-afterbuzz-gameofthrones() { mpsyt pl PL0404DAD1AD037666 ;}
mpsyt-afterbuzz-revolution() { mpsyt pl PL6THzna6gLccSY_0Cmoy6DvfH0iC8fyLR ;}
mpsyt-arrowaftershow-johncampea() { mpsyt pl PLGYmtexynt_Egz8kNR1HbA2kiRzhM0FKv ;}
mpsyt-btt-beyondthetrailer() { mpsyt user beyondthetrailer ;}
mpsyt-btt-thinkabouttheink() { mpsyt user thinkabouttheink ;}
mpsyt-cannatajeff() { mpsyt user cannatajeff ;}
mpsyt-comic-watchmojo() { mpsyt user watchmojo ;}
mpsyt-game-cinemassacre() { mpsyt user cinemassacre ;}
mpsyt-game-craigslistgamefinds() { mpsyt user craigslistgamefinds ;}
mpsyt-game-happyconsolegamer() { mpsyt user happyconsolegamer ;}
mpsyt-game-jamesnintendonerd() { mpsyt user jamesnintendonerd ;}
mpsyt-game-mcfrosticles() { mpsyt user mcfrosticles ;}
mpsyt-game-metaljesusrocks() { mpsyt user metaljesusrocks ;}
mpsyt-game-retroliberty() { mpsyt user retroliberty ;}
mpsyt-greatmilitarybattles() { mpsyt user greatmilitarybattles ;}
mpsyt-greentvgreentv() { mpsyt user greentvgreentv ;}
mpsyt-homeorganizing() { mpsyt user homeorganizing ;}
mpsyt-kirstendirksen() { mpsyt user kirstendirksen ;}
mpsyt-knucklegame() { mpsyt user knucklegame ;}
mpsyt-lifehacker() { mpsyt user lifehacker ;}
mpsyt-linuxgamecast() { mpsyt user linuxgamecast ;}
mpsyt-jupiterbroadcasting() { mpsyt user jupiterbroadcasting ;}
mpsyt-midwaysimplicity() { mpsyt user midwaysimplicity ;}
mpsyt-midwaysimplicity-mtohami() { mpsyt user mtohami ;}
mpsyt-mma-arielhelwani() { mpsyt user arielhelwani ;}
mpsyt-mma-fueltv() { mpsyt user fueltv ;}
mpsyt-mma-gracieacademy() { mpsyt user gracieacademy ;}
mpsyt-mma-graciebreakdown() { mpsyt user graciebreakdown ;}
mpsyt-mma-karynbryant() { mpsyt user karynbryant ;}
mpsyt-mma-mmaheat() { mpsyt user mmaheat ;}
mpsyt-mma-mmafightingonsbn() { mpsyt user mmafightingonsbn ;}
mpsyt-mma-thefightnetwork() { mpsyt user thefightnetwork ;}
mpsyt-mma-themmanuts() { mpsyt user themmanuts ;}
mpsyt-mma-ufc() { mpsyt user ufc ;}
mpsyt-mma-uncutsports() { mpsyt user uncutsports ;}
mpsyt-peakmoment() { mpsyt user peakmoment ;}
mpsyt-poetskinny() { mpsyt user poetskinny ;}
mpsyt-PoetskinnyUnleashed() { mpsyt user PoetskinnyUnleashed ;}
mpsyt-rallisp() { mpsyt user rallisp ;}
mpsyt-tmw-askhodgetwins() { mpsyt user askhodgetwins ;}
mpsyt-tmw-fastingtwins() { mpsyt user fastingtwins ;}
mpsyt-tmw-getfit4women() { mpsyt user getfit4women ;}
mpsyt-tmw-hodgetwins() { mpsyt user hodgetwins ;}
mpsyt-tmw-hodgetwinsonsports() { mpsyt user hodgetwinsonsports ;}
mpsyt-tmw-twinmuscleworkout() { mpsyt user twinmuscleworkout ;}
mpsyt-walkingdead() { mpsyt pl "http://www.youtube.com/playlist?list=PLC7EC9FB2E211A261" ;}
mpsyt-walkingdead-talkingdead() { mpsyt pl "http://www.youtube.com/playlist?list=PLP63B9XPsQt3H_5xGXifFxFJE7-RsKFb6" ;}
mpsyt-walkingdead-webisodes() { mpsyt pl "http://www.youtube.com/playlist?list=PLC09448134D906619" ;}
mpsyt-wwefannation() { mpsyt user wwefannation ;}

# }}}
#-------- Music Tagging CLI {{{
#------------------------------------------------------
lltag-artist() { lltag --yes -a "$1" "$2" ;}
lltag-album() { lltag --yes -A "$1" "$2" ;}
lltag-date() { lltag --yes -d "$1" "$2" ;}
lltag-genre() { lltag --yes -g "$1" "$2" ;}
lltag-comment() { lltag --yes -c "$1" "$2" ;}
lltag-number() { lltag --yes -n "$1" "$2" ;}
lltag-show() { lltag -S "$1" ;}
lltag-rename() { lltag --yes --rename '%n - %t' "$1" ;}


#Mp3 id3 tagger
tag-show() { eyeD3 "$@" ;}
tag-artist() { eyeD3 -a "$1" "${@:2}" ;}
tag-album() { eyeD3 -A "$1" "${@:2}" ;}
tag-title() { eyeD3 -t "$1" "${@:2}" ;}
tag-number() { eyeD3 -n "$1" "${@:2}" ;}
tag-genre() { eyeD3 -G "$1" "${@:2}" ;}
tag-listgenre() { eyeD3 --plugin=genres ;}
tag-year() { eyeD3 -Y "$1" "${@:2}" ;}
tag-comment() { eyeD3 -c "$1" "${@:2}" ;}
tag-image-remove() { eyeD3 --remove-all-images "$@" ;}		# remove embedded album art
tag-image-add() { eyeD3 --add-image "$1":FRONT_COVER "${@:2}" ;}	# add album art
tag-image-extract() { eyeD3 --write-images=. "$@" ;}		# extract album art to current dir
tag-rename() { eyeD3 --rename '$track:num - $title' "$@" ;}
tag-rename-alt() { eyeD3 --rename '$artist - $album - $track:num - $title' "$@" ;}
tag-full() { 
	tempfile=/tmp/eyed3tag.txt
	echo "eyeD3 --artist --album --title --track --genre --release-year "$@"" > "$tempfile"; $EDITOR "$tempfile"; source "$tempfile" ;}



# }}}
#-------- Podcast Audio / Video {{{
#------------------------------------------------------
# tutorial video: https://www.youtube.com/watch?v=7y_58wpHuFE
# vlc 2.0.5 Twoflower; seems like newer version kills the RSS feature
nvlc-player() { nvlc ${1:-cdda://} ;}		# other cdrom; cdda:///dev/cdrom ; cdda:///dev/sr0 ; cdda:///dev/sr1
nvlc-podcast() { nvlc -S podcast --podcast-urls "$@" ;}
pod-sports-mmahour() { nvlc-podcast "http://aolradio.podcast.aol.com/fanhouse/mma_audio_podcast.xml" ;}
pod-tech-mintcast() { nvlc-podcast "http://www.mintcast.org/feed/podcast/?format=mp3" ;}
pod-sports-mmaproradio() { nvlc-podcast "http://feeds.feedburner.com/ProMmaRadio" ;}
pod-bid() { nvlc-podcast "http://revision3.com/catherinereitman/feed/mp4-large" ;}
#}}}
#-------- IPTV {{{
#------------------------------------------------------
# http://livetvstreaming.ucoz.com/
# http://database.freetuxtv.net/WebStream/
# http://www.thestreamdb.com/
# http://pclosmag.com/html/Issues/201104/page19.html

# https://www.youtube.com/user/aljazeeraenglish
# http://www.aljazeera.com/watch_now/
IPTVPLAYER=mplayer
itv-doc-pbs() { "$IPTVPLAYER" "http://winstream.kamu.tamu.edu/kamu-tv?mswmext=.asf" ;}
itv-gov-cspan() { rtmpdump -v -r "rtmp://cp82346.live.edgefcs.net:1935/live" -y "CSPAN1@14845" -W "http://www.c-span.org/cspanvideohd.swf" -p "http://www.c-span.org/live-video/c-span/" | "$IPTVPLAYER" - ;}
itv-gov-cspan2() { rtmpdump -v -r "rtmp://cp82347.live.edgefcs.net:1935/live" -y "CSPAN2@14846" -W "http://www.c-span.org/cspanvideohd.swf" -p "http://www.c-span.org/live-video/c-span2/" | "$IPTVPLAYER" - ;}
itv-gov-cspan3() { rtmpdump -v -r "rtmp://cp82348.live.edgefcs.net:1935/live" -y "CSPAN3@14847" -W "http://www.c-span.org/cspanvideohd.swf" -p "http://www.c-span.org/live-video/c-span3/" | "$IPTVPLAYER" - ;}
itv-gov-pentagon() { rtmpdump -v -r "rtmp://cp114761.live.edgefcs.net:443/live/" -y "tpc-live_1@44263" -W "http://www.pentagonchannel.mil/swf/flvplayer.swf" -p "http://www.pentagonchannel.mil/library.html" | "$IPTVPLAYER" - ;}
itv-gov-wisconsineye() { "$IPTVPLAYER" "mms://71.87.25.133/AirV" ;}
itv-news-aljazeeraenglish() { rtmpdump -v -r "rtmp://aljazeeraflashlivefs.fplive.net:1935/aljazeeraflashlive-live" -y "aljazeera_english_2" -W "http://admin.brightcove.com/viewer/us1.25.04.00.2011-05-19124744/federatedvideoui/brightcoveplayer.swf" -p "http://english.aljazeera.net/watch_now/" | "$IPTVPLAYER" - ;}
itv-news-aljazeeraenglish.high() { rtmpdump -v -r "rtmp://media2.lsops.net/live/" -y "aljazeer_en_high.sdp" -W "http://www.livestation.com/flash/player/5.4/player.swf" -p "http://www.livestation.com/channels/3-al-jazeera-english-english" | "$IPTVPLAYER" - ;}
itv-news-aljazeeraenglish.veryhigh() { rtmpdump -v -r "rtmp://media2.lsops.net/live/" -y "aljazeer_en_veryhigh.sdp" -W "http://www.livestation.com/flash/player/5.4/player.swf" -p "http://www.livestation.com/channels/3-al-jazeera-english-english" | "$IPTVPLAYER" - ;}
itv-news-russiatoday.medium() { rtmpdump -r "rtmp://rt.fms-04.visionip.tv/live" -a "live" -f "LNX 11,2,202,261" -W "http://rt.com/s/swf/player5.4.viral.swf" -p "http://rt.com/on-air/rt-america-air/" -y "RT_US_2" | "$IPTVPLAYER" - ;}
itv-news-unrefugeeagency() { rtmpdump -v -r "rtmp://media2.lsops.net/unhcr/" -y "liveloop.sdp" -W "http://www.livestation.com/flash/player/5.4/player.swf" -p "http://www.livestation.com/channels/68-unhcr-english" | "$IPTVPLAYER" - ;}
itv-shows-oc16hawaii() { rtmpdump -v -r "rtmp://24.165.45.209/oc16live/" -y "oc16" -a "oc16live/" -W "http://www.oc16.tv/videoplayer/jw/player.swf" -p "http://www.oc16.tv/" | "$IPTVPLAYER" - ;}
itv-tech-thisweekintech() { "$IPTVPLAYER" "http://bglive-a.bitgravity.com/twit/live/high" ;}
#}}}
#-------- Search for Files {{{
#------------------------------------------------------
# find files
@find() { 
        keyword=$(echo "*$@*" |  sed -e 's/ /*/g')
	find /home /media -type f -iname $keyword | vim -R - ;}

# find starting at current dir and go recursively to sub dir
@search() { 
        keyword=$(echo "*$@*" |  sed -e 's/ /*/g')
	find -type f -iname $keyword | vim -R - ;}

# find current dir files bigger than X size
# useage: @size <filesize> <keyword>
@size() { 
	keyword=$(echo "*${@:2}*" |  sed -e 's/ /*/g')
	find -type f -size +${1}M -iname $keyword  | vim -R - ;} 

# search pdf files in current dir for keywords inside the pdfs
# http://www.commandlinefu.com/commands/view/9189
@pdfgrep() { find -iname \*.pdf -print0 | xargs -0 pdfgrep -in "$@" ;}

# search using the mlocate database
@locate() {
	# tutorial video: http://www.youtube.com/watch?v=X0KPl5O006M
	# 'bleach (mkv|avi)$' , '(naruto|shingeki) (mkv|avi)$' , naruto shippudden mkv$
	# quit vim:  shift + zz
	
	# escape spaces, pipe and parentheses
        keyword=$(echo "$@" |  sed -e 's/ /.*/g' -e 's:|:\\|:g' -e 's:(:\\(:g' -e 's:):\\):g')
	locate -ir "$keyword" | vim -R -
}


#}}}
#-------- Internet Videos - Castalba.tv {{{
#------------------------------------------------------
# http://castalba.tv/channels
# Animation, Documentary, Entertainment, Sports, News

# sample of fail capture links
#rtmpdump -r "rtmp://live.castalba.tv/calive" -a "calive" -f "LNX 11,2,202,243" -W "http://static.castalba.tv/player.swf" -p "http://castalba.tv/channel/6768" -y "174956" -o 174956.flv

CTVPLAYER=mplayer
ctv-news-aljazeera() { rtmpdump -v -r "rtmp://aljazeeraflashlivefs.fplive.net/aljazeeraflashlive-live" -a "aljazeeraflashlive-live" -f "LNX 11,2,202,261" -W "http://static.castalba.tv/player.swf" -p "http://castalba.tv/channel/4182" -y "aljazeera_eng_low" | "$CTVPLAYER" - ;}
ctv-news-bloomberg() { rtmpdump -V -v -r "rtmp://cp.116697.live.edgefcs.net:1935" -a "live" -f "LNX 11,2,202,261" -W "http://static.castalba.tv/player.swf" -p "http://castalba.tv/channel/4190" -y "aljazeera_eng_low" | "$CTVPLAYER" - ;}

#}}}



date-global() {
# use tzselect to find timezone listing
	local SHOWTIMEZONE="$(
	alias date='date +"%a %D %l:%M %p"'
	echo "Current Location:" "$(date)"
	echo "USA LosAngeles:" "$(TZ='America/Los_Angeles' date)"
	echo "USA NewYork:" "$(TZ='America/New_York' date)"
	echo "EU London:" "$(TZ='Europe/London' date)"
	echo "Bangladesh Dhaka:" "$(TZ='Asia/Dhaka' date)"
	echo "China Xinjiang:" "$(TZ='Asia/Urumqi' date)"
	echo "Vietnam Saigon:" "$(TZ='Asia/Ho_Chi_Minh' date)"
	echo "China Beijing:" "$(TZ='Asia/Shanghai' date)"
	echo "HK HongKong:" "$(TZ='Asia/Hong_Kong' date)"
	echo "Japan Tokyo:" "$(TZ='Asia/Tokyo' date)"
	)"
	echo "$SHOWTIMEZONE" | column -t

}

myBackup() {
    sudo rsync -avr --exclude 'veewee/' --exclude 'oses/' --exclude 'Downloads/' --exclude '.cache/' --exclude '.Genymobile/' --exclude 'Projects/' --exclude 'VirtualBox Vms/' --exclude '.local/*' --exclude 'Videos/' --delete-excluded /home/maotora/ /mnt
}

take(){
    mkdir $1; cd $1
}

retake(){
    current=$(basename `pwd`)
    files=$(ls)

    if [ -z $files ]
    then
        cd ..; rmdir $current
    else
        mv --verbose * ../; cd ..; rmdir $current
    fi
}

utube(){
    url=$1
    youtube-dl --continue --retries 3 --format best "$url"
}

#sysChecking(){
    #dstat -tvin --noupdate 5 > dstat.log &" and "(while /bin/true; do ps axlf >> ps.log; sleep 30; done) &
#}
alias cat=lolcat
#rip me..
ripme-cli() { java -jar /usr/share/java/ripme-git-1.2.8.jar -l ~/Pictures/Downloaded -u "$@" ;}

figl() { figlet "$1" | lolcat ;}

alias screenfetch="screenfetch | lolcat ; figl \"Me : $USER\" ; echo "" ; cal | lolcat"
