#!/bin/bash
#########################################################
# 							#
# This is BashStyle-NG  				#
#							#
# Licensed under GNU GENERAL PUBLIC LICENSE v3    	#
#							#
# Copyright 2007 - 2015 Christopher Bratusek		#
#							#
#########################################################

keybindings_unsetter () {

	for key in $(bind -p | grep ${1} | gawk -F \: '{print $1}'); do
		bind "${key}":self-insert
	done
	bind "${2}":self-insert
}

keybindings_setter () {

	if [[ "${1}" != "" ]]; then
		MOD=${1/:*}
		KEY=${1/*:}

		case ${2} in
			complete-path)	ACT='"\eb`which \ef` \e\C-e"' ;;
			*)		ACT=${2} ;;
		esac

		if [[ ${MOD} == e ]]; then
			keybindings_unsetter ${ACT} "\\e${KEY}"
			echo -E \"\\e${KEY}\":${ACT} >> $RC_FILE
		elif [[ ${MOD} == C ]]; then
			keybindings_unsetter ${ACT} "\\C-${KEY}"
			echo -E \"\\C-${KEY}\":${ACT} >> $RC_FILE
		fi
	fi

}


if [[ -e $HOME/.keybindings && ( ! -w $HOME/.keybindings || ! -r $HOME/.keybindings ) ]]; then
	ERR_MSG+="\n * $HOME/.keybindings is not accessible! -- adjust permissions"
elif [[ ! -e $HOME/.keybindings.bs-ng.* ]]; then

	export RC_FILE=$HOME/.keybindings.bs-ng.$(date +%I-%M-%S)
	dbg_msg $"ReadlineCFG Loading:" $"Keybindings"

	for key in undo upcase_word capitalize_word downcase_word transpose_words \
		transpose_chars unix_word_rubout kill_word possible_filename_completions \
		possible_hostname_completions possible_username_completions \
		possible_variable_completions kill_line unix_line_discard \
		beginning_of_line end_of_line clear_screen history_search_forward \
		history_search_backward complete_path; do

			keybindings_setter $(ini_get $key) ${key//_/-}

	done

	mv ${RC_FILE} ${HOME}/.keybindings
	builtin bind -f ${HOME}/.keybindings
	unset RC_FILE

fi
