# .bashrc
# cayla fauver <cayla@wehavenoproduct.com>
# Created: Sat Sep 17, 2005  07:55PM
# Last modified: Wed Jun 11, 2008 03:04PM
# Description: SUPER cross platform edition v.01. 
# Written to work on both linux boxes and Macs!  Things not working
# are commented.  Stolen from many place and tweaked to work for me.
# Feel free to take all or some if you like it.

if [ "$PS1" ]; then  # If running interactively, then run till fi at EOF:

########################################################
#-- you shouldn't need to change anything above here --#
########################################################

#-- variables here __#
. ~/.bash_localrc         # settings that vary per workstation
HOST=$(hostname)        # for host info function
OS=$(uname)             # for resolving pesky os differing switches

export EDITOR="vi"
export VISUAL="vi"
export HISTCONTROL=ignoredups
if [ -d $HOME/Maildir/ ]; then
    export MAIL=$HOME/Maildir/
    export MAILPATH=$HOME/Maildir/
    export MAILDIR=$HOME/Maildir/
elif [ -f /var/mail/$USER ]; then
    export MAIL="/var/mail/$USER"
fi
if [ "$TERM" = "screen" ]; then
    export TERM=$TERMINAL
fi
#-- end variables --#

#-- startup programs --#
if [ "$USE_SCREEN" = "Y" ]; then
    if [ "$UID" -ne 0 ]; then
        if [ "$SHLVL" -eq 1 ]; then
            /usr/bin/screen -d -RR
        fi
    fi
fi
if [ -e "/usr/games/fortune" ]; then
    echo "Fortune: "
    /usr/games/fortune
    echo
fi
if [ -e "/usr/bin/uptime" ]; then
    echo "Uptime: ` /usr/bin/uptime`"
fi
echo
#    $HOME/bin/motd.pl
#-- end startup programs --#

#-- PATH __#
if [ "$UID" -eq 0 ]; then
    PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin
fi
PATH=$PATH:$HOME/bin
#-- end PATH --#

#-- aliases --#
if [ -f dircolors ]; then
    eval `dircolors -b`
fi
if [ "$OS" = "Linux" ]; then
    alias ls='ls --color=auto -h'
elif [ "$OS" = "Darwin" ]; then
    alias ls='ls -G'
fi
alias ..="cd .."
alias be="vi ~/.bashrc;source ~/.bashrc"
alias c="clear"
alias cp="cp -i"
alias df="df -h"
alias enote="vi ~/data/misc/motd_data/todo;~/bin/motd.pl"
if [ "$OS" = "Darwin" ]; then
    alias gvim='/Applications/MacVim.app/Contents/MacOS/Vim -g'
fi
alias install="apt-get install"
alias lh="ls -lh .[a-zA-Z0-9]*"
alias ll="ls -lh"
alias lla="ls -lha"
alias logs="tail -f /var/log/messages /var/log/*log"
alias m="~/bin/motd.pl"
alias me="vi ~/.muttrc"
alias mkdir="mkdir -p"
alias mlog="tail -100f /var/log/mail.log"
alias mv="mv -i"
alias newpw="pwgen --no-capitalize"
alias path="env | grep PATH"
alias pcd="cd -"
alias pe="vi ~/.procmailrc"
alias ps="ps aux"
alias rcci="svn ci ~/rc/"
alias rcup="bin/rc_sync.sh"
alias rm="rm -i"
alias se="vi ~/.screenrc"
alias showx="echo USE_X current status = $USE_X"
alias sr="screen -d -RR"
if [ -e "${HOME}/.homeIP.txt" ]; then
    alias sshh="ssh cayla@`cat ~/.homeIP.txt`"
fi
alias sx="screen -x"
alias tc="tar cfvz"
alias tx="tar xfvz"
alias upgrade="apt-get update;apt-get upgrade -y"
alias ve="vi ~/.vimrc"
alias vi="vim"
alias vim="vim -X"
#-- end aliases --#

#-- bash settings --#
#umask 007
ulimit -S -c 0      # Don't want any coredumps
set -o notify       # notify when jobs running in background terminate
#set -o noclobber    # prevents catting over file
#set -o ignoreeof   # can't c-d out of shell
set -o nounset      # attempt to use undefined variable outputs error message and forces exit
# set -o xtrace      # useful for debuging

# Enable options:
shopt -s cdspell         # auto fixes cd / spelling mistakes
shopt -s cdable_vars
shopt -s checkhash
shopt -s checkwinsize
shopt -s cmdhist
shopt -u mailwarn
shopt -s sourcepath
shopt -s no_empty_cmd_completion  # bash>=2.04 only
shopt -s histappend histreedit histverify
shopt -s extglob    # necessary for programmable completion

stty stop undef
stty start undef
#-- end bash settins --#

########################################################
#__ you shouldn't need to change anything below here --#
########################################################

#autocomplete ssh commands
complete -W "$(echo `cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ssh

# remove duplicate path entries
export PATH=$(echo $PATH | awk -F: '
{ for (i = 1; i <= NF; i++) arr[$i]; }
END { for (i in arr) printf "%s:" , i; printf "\n"; } ')

# Make $HOME comfy
if [ ! -d "${HOME}/bin" ]; then
    mkdir ${HOME}/bin
    chmod 700 ${HOME}/bin
    echo "${HOME}/bin was missing.  I recreated it for you."
fi
if [ ! -d "${HOME}/Documents" ]; then
    if ! [  -d "${HOME}/data" ]; then
        mkdir ${HOME}/data
        chmod 700 ${HOME}/data
        echo "${HOME}/data was missing.  I recreated it for you."
    fi
fi
if [ ! -d "${HOME}/tmp" ]; then
    mkdir ${HOME}/tmp
    chmod 700 ${HOME}/tmp
    echo "${HOME}/tmp was missing.  I recreated it for you."
fi

#  color chart:
#  Black       0;30     Dark Gray     1;30
#  Blue        0;34     Light Blue    1;34
#  Green       0;32     Light Green   1;32
#  Cyan        0;36     Light Cyan    1;36
#  Red         0;31     Light Red     1;31
#  Purple      0;35     Light Purple  1;35
#  Brown       0;33     Yellow        1;33
#  Light Gray  0;37     White         1;37
#  No color    0

red='\e[0;31m'
RED='\e[1;31m'
blue='\e[0;34m'
BLUE='\e[1;34m'
cyan='\e[0;36m'
CYAN='\e[1;36m'
green='\e[0;32m'
GREEN='\e[1;32m'
NC='\e[0m'

# X DISPLAY functions
# find available displays unless prohibited by switch NEVER_USE_X
if [ $NEVER_USE_X != 'Y' ]; then
    if [ $OS = "Linux" ]; then
        function get_xserver ()
        {
            case $TERM in
                xterm | xterm-color | linux )
                    XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )
                    XSERVER=${XSERVER%%:*}
                    ;;
            esac
        }
        if [ -z ${DISPLAY:=""} ]; then
            get_xserver
            if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) || ${XSERVER} == "unix" ]]; then
                export DISPLAY=":0.0"
            else
                export DISPLAY=${XSERVER}:0.0
            fi
        fi
    elif [ $OS = 'Darwin' ]; then
        if [[ -z $DISPLAY ]]; then
            disp_no=($( ps -ax | grep X11.app | grep -v grep | awk '{print $9}' ))
            if [[ -n $disp_no ]];then
                export DISPLAY=${disp_no}.0
            else
                export DISPLAY=''
                echo "No running X-Server"
            fi
        fi
    fi
    # check for screen logins if display is found
    if [[ ! -z $DISPLAY ]]; then
        USE_X="Y"
        echo "Using X"
        if [ $SHLVL = 1 ]; then
            rm -f $HOME/.display
            echo $DISPLAY > $HOME/.display
            echo "DISPLAY has been set to $DISPLAY"
        elif [ $SHLVL -gt 1 ]; then
            if [ -e $HOME/.display ]; then
                DISPLAY_FIX=$(cat $HOME/.display)
                if [ $DISPLAY != $DISPLAY_FIX ]; then
                    export DISPLAY=$DISPLAY_FIX
                    echo "screen/DISPLAY mismatch detected.  DISPLAY has been adjusted to $DISPLAY"
                fi
            fi
        fi
    fi
elif [ $NEVER_USE_X = 'Y' ]; then
    USE_X="N"
    echo "Usage of X prohibited by NEVER_USE_X"
else
    USE_X="N"
    echo "Cannot find display.  Not using X"
fi

function togglex()
{
    if [ $USE_X = 'Y' ]; then
        USE_X='N'
        echo "Stop using X..."
    elif [ $USE_X = 'N' ]; then
        USE_X='Y'
        echo "Start using X..."
    fi
}

function set_xtitle()
{
    if [ $TERM == "xterm" ]; then
        echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"
    fi
}

# prompt functions
function host_load()
{
    THRESHOLD_LOAD=50
    COLOUR_LOW=$GREEN
    COLOUR_HIGH=$RED

    if [ $OS = "Linux" ]; then
        ONE=$(uptime | sed -e "s/.*load average: \(.*\...\),\(.*\...\),\(.*\...\)/\1/" -e "s/ //g")
    fi
    if [ $OS = "Darwin" ]; then
        ONE=$(uptime | sed -e "s/.*load averages: \(.*\...\)\(.*\...\)\(.*\...\)/\1/" -e "s/ //g")
    fi
    ONEHUNDRED=$(echo -e "scale=0 \n $ONE/0.01 \nquit \n" | bc)
    if [ $ONEHUNDRED -gt $THRESHOLD_LOAD ]
        then
            HOST_COLOR=$COLOUR_HIGH
        else
            HOST_COLOR=$COLOUR_LOW 
    fi
}
function power_prompt()
{
    host_load
    set_xtitle
    if [ "$UID" -eq 0 ]; then
        PS1="[\[${HOST_COLOR}\]\t\[${NC}\]][\[${red}\]\u@\h:\w]\$\[${NC}\] "
    else
        PS1="[\[${HOST_COLOR}\]\t\[${NC}\]][\[${cyan}\]\u\[${NC}\]@\[${red}\]\h\[${NC}\]:\w]\$ "
    fi
}
if [ $PROMPT = "power" ]; then
    PROMPT_COMMAND=power_prompt
else
    if [ "$UID" -eq 0 ]; then
        PS1="[\t][\[${red}\]\u@\h:\w]\$\[${NC}\] "
    else
        PS1="[\t][\[${cyan}\]\u\[${NC}\]@\[${red}\]\h\[${NC}\]:\w]\$ "
    fi
fi

# on exit function
function _exit()
{
    echo -e "${RED}So long and thanks for all the fish${NC}"
}
trap _exit EXIT

# random useful functions
function ds()
{
    echo 'size of directories in MB'
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo 'you did not specify a directy, using pwd'
        DIR=$(pwd)
        find $DIR -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
    else
        find $1 -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
    fi
}

function ff() { find . -name '*'$1'*' ; }
function fe() { find . -name '*'$1'*' -exec $2 {} \; ; }

function ii()
{
    echo -e "\nYou are logged onto ${RED}$HOST"
    echo -e "\nAdditionnal information:$NC " ; uname -a
    echo -e "\n${RED}Users logged on:$NC " ; w -h
    echo -e "\n${RED}Current date :$NC " ; date
    echo -e "\n${RED}Machine stats :$NC " ; uptime
    echo -e "\n${RED}Disk space :$NC " ; df
    echo -e "\n${RED}Memory stats :$NC " ; free
    my_ip 2>&- ;
    echo -e "\n${RED}Local IP Address :$NC" ; echo ${MY_IP:-"Not connected"}
    echo
}

function my_ip()  # sucky.  interface must be hardcoded.  needs work
{
    MY_IP=$(/sbin/ifconfig $INTERFACE | awk '/inet / { print $2 } ' | sed -e s/addr://)
}

function repeat()
{
    local i max
    max=$1; shift;
    for ((i=1; i <= max ; i++)); do
    eval "$@";
    done
}

# common commands piped through grep
function aptg()  # debian specific.
{
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo search debian package list
        echo usage: aptg [program/keyword]
    else
        apt-cache search $1 | less
    fi
}

function lsofg()
{
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo grep lsof
        echo usage: losfg [port/program/whatever]
    else
        lsof | grep -i $1 | less
    fi
}

function mailg()
{
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then  
        echo search ~Maildir
        echo usage: mg [search pattern]
    else                
        grep -iR $1 $HOME/Maildir | less
    fi      
}

function psg()
{
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo grep running processes
        echo usage: psg [process]
    else                
        ps aux | grep USER | grep -v grep
        ps aux | grep -i $1 | grep -v grep
    fi      
}

function whoisg()
{
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo grep whois lookups for status
        echo usage: whoisg [domain name]
    else
        whois $1 | grep -i -B 3 -A 3 status
    fi
}

# web functions
function www()
{
    if [ $OS = 'Linux' ]; then
        elinks http://$1 
    elif [ $OS = 'Darwin' ]; then
        open -a Safari http://$1
    else 
        echo "Unknown OS"
    fi
}

function gg()
{
    echo "searching google for $*"
    SEARCH=$(echo $* | sed -e 's/ /\%20/g')
    echo "translating search to URL speak...  $SEARCH"
    www www.google.com/search?q="$SEARCH"
}

# ~/ functions

function mnote()
{
    echo -e "- $* \n" >> ~/data/misc/motd_data/todo
    echo -e "- $* \n" >> ~/data/misc/motd_data/todo.perm
    ~/bin/motd.pl
}

function private()
{
    find $HOME -type d -exec chmod 700 {} \;
    find $HOME -type f -exec chmod 600 {} \;
    find $HOME/bin -type f -exec chmod +x {} \;
    public
}

function public()
{
    if [ -d $HOME/public_html ]; then
        chown -R $USER:www-data $HOME/public_html
        chmod 755 $HOME/public_html
        find $HOME/public_html/ -type d -exec chmod 775 {} \;
        find $HOME/public_html/ -type f -exec chmod 664 {} \;
        chmod 755 $HOME
    fi
}

function pw()
{
    gpg $HOME/data/misc/wallet/priv.asc
    vi $HOME/data/misc/wallet/priv
    gpg -ea $HOME/data/misc/wallet/priv
    wipe -f $HOME/data/misc/wallet/priv
}

function wwwrc()
{
    alias mv="mv"
    mv -f ~/.[a-z]*.html ~/public_html/
    chmod 644 ~/public_html/.[a-z]*.html
    chown cayla:www-data ~/public_html/.[a-z]*.html
    alias mv="mv -i"
}

fi  #end interactive check