#
# ~/.bashrc
#

export PATH="/opt/control/bin:/opt/control/exec:/opt/admin/bin:$PATH"
[ -d "/opt/admin" ] && cd "/opt/admin" || return
[ -f "/opt/admin/lib/autocomplete.bash" ] && . "/opt/admin/lib/autocomplete.bash"

# If not running interactively, don't do anything
[[ $- != *i* ]] && return

if [[ "$(tty)" =~ "tty2" ]] && ! pidof fbterm; then
  exec fbterm
fi

if [[ "$TERM" == "linux" ]]; then
  export TERM=fbterm
else
  export TERM=xterm-256color
fi

alias ls='TERM=xterm-256color ls -h --color=auto'
alias ll='TERM=xterm-256color ls -al'
alias grep='grep --color=auto'

alias ..='cd ..'
alias ...='cd ...'

export EDITOR=nvim
# To simply build scratch3
export NODE_OPTIONS="--max-old-space-size=8196"

alias v=nvim
alias vim=nvim
alias vimtutor="nvim +Tutor"

alias r=ranger
alias vb='vim ~/.bashrc; . ~/.bashrc'

alias gs='git status'
alias gba='git branch -a'
alias gt='git tag -l'
alias gd='git diff'

set +o noclobber
shopt -s checkwinsize

alias fg='tput setaf'
alias bg='tput setab'
alias reset='tput sgr0'

export PS1='\[$(fg 40)\]\u\[$(reset)\]@\[$(fg 33)\]\h.local\[$(reset)\]:\[$(fg 220)\]$(pwd)\[$(reset)\] $ '

# Autocomplete
if [ -r /opt/admin/lib/autocomplete ]; then
  . /opt/admin/lib/autocomplete
fi

qwer() { pwd >"$HOME/.config/qwer"; }
[[ -f "$HOME/.config/qwer" ]] && cd "$(cat ~/.config/qwer)"

every() { while true; do
  "${@:2}"
  sleep $1
  clear
done; }
wait() { for i in {5..1}; do sleep 1; done; }
hstat() {
  for stat in "/srv/secure/hosts/"*; do
    host="$(basename "$stat")"
    field="$(grep "$1" "$stat" | cut -d' ' -f2)"
    echo "$host $field"
  done \
    | grep -vE "${EXCEPT:-'(hosts_to_skip|pipe_delimited)'}"
}
hosts() {
  if [ -n "$ONLY" ]; then
    echo $ONLY
  else
    hstat host \
      | grep -vE "${EXCEPT:-'(hosts_to_skip|pipe_delimited)'}" \
      | cut -d' ' -f2
  fi
}
hrun() {
  for host in $(hosts); do
    echo "\$ ssh $host.local $*"
    ssh "$host.local" $*
  done
}
hruninline() { for host in $(hosts); do echo "\$ ssh $host.local $* => $(ssh $host.local $* 2>&1)"; done; }
hrunfast() {
  for host in $(hosts); do
    ssh "$host.local" $* &
  done
  wait 5
}
hbg() {
  cmd="$(date +'%Y%m%d-%H%M%S')-$1"
  echo "${@:2}" >"/tmp/automation-$cmd"

  for host in $(hosts); do
    echo "queueing on $host.local as $cmd"
    rsync -aP "/tmp/automation-$cmd" "$host.local:/srv/secure/cmd/queue/$cmd"
  done
}
hbgfast() {
  cmd="$(date +'%Y%m%d-%H%M%S')-$1"
  echo "${@:2}" >"/tmp/automation-$cmd"

  for host in $(hosts); do
    rsync -aP "/tmp/automation-$cmd" "$host.local:/srv/secure/cmd/queue/$cmd" &
  done
  wait 5
}
