#!/usr/bin/env bash
#
# ssh-s - connect to host via SSH, using essential aliases without modifying remote files.
#
# Any further invocations of SSH via "s" from that host should also initialize bash
# and so on through as many connections as I make.
#
# If I forget that this is for interactive use and give it a command to
# run instead, then switch to being a simple SSH alias.
#
# shellcheck shell=bash

if [ -n "$2" ]; then
  exec ssh "$@"
fi

# First, create the configuration script.

# shellcheck disable=SC3045
read -r -d '' rc <<'EOF'

# Aliases

alias b='cat'
# alias d='diff -ur'
alias e="vi &"
alias g="grep -E"
alias la="ls -avCF"
alias l="ls -lvaF"
alias ll="ls -lv"
alias lla="ls -alv"
alias lt="ls -alt"
alias v='"${EDITOR}"'
alias vim='"${EDITOR}"'
alias ,coreon="ulimit -c unlimited"
alias ,coreoff="ulimit -c 0"
ulimit -c 0

# Options for other tools besides bash

export LESS="-i -j.49 -M -R -z-2"
export PAGER=less

# Bash command line behavior

HISTCONTROL=erasedups
unset histchars
unset TMOUT
unset -f command_not_found_handle
echo set revert-all-at-newline on | bind -f /dev/stdin

# Editor.

if hash vim 2>/dev/null; then
  export EDITOR="vim"
elif hash vi 2>/dev/null; then
  export EDITOR="vi"
fi
export VISUAL="${EDITOR}"

# Avoid needing to double-tab to get completions.

bind 'set show-all-if-ambiguous on'

# Custom completions.

_complete_ssh() {
  local curr_arg hostnames;
  curr_arg=${COMP_WORDS[COMP_CWORD]}
  hostnames="$(awk '/^[0-9a-f]/ { $1=""; print }' /etc/hosts)"
  [ -f ~/.ssh/config ] &&
  hostnames="${hostnames} $(awk '/Host +[a-z]/ { print $2 }' ~/.ssh/config)"
  COMPREPLY=( $(compgen -W "${hostnames}" -- ${curr_arg} ) );
}
complete -F _complete_ssh s ssh

# Local my local commands if I defined any where.

if [ -f .localrc ]; then
  source .localrc
fi

escape() { printf "'%s'\\n" "$(printf '%s' "$1" | sed -e "s/'/'\\\\''/g")"; }

# Allow jumping to further hosts, using my normal "s" alias for SSH,
# carrying this configuration with us.

rc="$(cat /dev/fd/3)"
s() {
  echo Connecting...
  ssh -t "$1" 'exec /usr/bin/env bash --rcfile /dev/fd/3 3<<<'$(escape "${rc}")
}
EOF

# shellcheck disable=SC2312
escape() { printf "'%s'\\n" "$(printf '%s' "$1" | sed -e "s/'/'\\\\''/g")"; }

# The "exec" avoids leaving a useless `bash` parent process hanging
# around: the equivalent of shell script tail recursion.

# shellcheck disable=SC2312
exec ssh -t "$1" -- 'exec /usr/bin/env bash --rcfile /dev/fd/3 3<<<'"$(escape "${rc}")"
