#!/bin/bash

key_aliases="$HOME/linux-config/aliases/key_aliases"

# Ensure text of argument 1 exists in the file argument 2
ensure() {{{
	if [[ ! -e "$2" ]]; then
		touch "$2"
	fi
	(grep "$1" "$2")>/dev/null 2>&1 || echo "$1" >> "$2"
}}}

# fish
fish_config="$HOME/.config/fish/config.fish"
fish_abbr="$HOME/.config/fish/key_aliases.fish"
ensure "source $fish_abbr" "$fish_config"

# bash/zsh
bashrc="$HOME/.bashrc"
zshrc="$HOME/.zshrc"
aliases="$HOME/.aliases"
ensure "source $aliases" "$bashrc"
ensure "source $aliases" "$zshrc"

# Remove, prepare files
printf "# vim: filetype=sh\\n" > "$fish_abbr"
printf "# vim: filetype=sh\\n" > "$aliases"

sed -e '/^$/d' -e '/^[ \t#].*/d' "$key_aliases" | sort | tee \
	>(awk '{printf "abbr " $1; $1 = ""; print $0; }' >> "$fish_abbr") \
	| awk '{
		printf "alias " $1;
		$1 = "";
		printf "=";
		print gensub(" ", "", 1, $0);
	}' >> "$aliases"