# Servalias: shell-independent alias collection by Luxferre
# This is the core file to be included from the outside world
# (source as . $HOME/.aliases/main)

. $HOME/.profile

# set modules (order matters)
ALIAS_MODULES='core sys net dev media custom'

# detect the current alias file path, hardcode it for non-bash
ALIASES_MAIN="$BASH_SOURCE"
[ -z "$ALIASES_MAIN" ] && ALIASES_MAIN="$HOME/.aliases/main"

# set some editor
[ -z "$EDITOR" ] && EDITOR=vim

# get the alias directory
ALIASDIR="$(dirname "$ALIASES_MAIN")"

# these are the bedrock commands for alias manipulation

# live-reload all aliases from this collection
alias reload-aliases=". $ALIASES_MAIN"

# edit this file and then live-reload all aliases
alias aliases-main="$EDITOR $ALIASES_MAIN && reload-aliases"

# get the most recent command run on this shell
alias lastcmd='history | tail -q -n 2 | head -q -n 1 | sed "s/^[[:space:]]*[0-9]*[[:space:]]*//"'

# define complex, function-like command aliases that can handle positional parameters anywhere
alias defalias='___(){ __="$1";shift;alias $__="_$__(){ $*; };_$__"; };___'

# convert the last run command into an alias
defalias toalias 'defalias "$1" "$(lastcmd)";alias "$1"'

# save any live alias into the custom alias file
defalias savealias "[ -n \"\$1\" ] && echo \"alias \$(alias \$1 | sed 's/^alias //')\" >> ${ALIASDIR}/custom"

# load the alias modules 
for mod in $ALIAS_MODULES; do
  alias aliases-${mod}="$EDITOR ${ALIASDIR}/$mod && reload-aliases"
  . ${ALIASDIR}/$mod
done
