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

function list-keybindings () {
	bind -P | sed -e '/is not/d;s/can be found on/:/' | column -s : -t
}

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

		case ${2} in
			complete-path)	ACT='"\eb`which \ef` \e\C-e"' ;;
			rerun-root)	ACT='"\ebsudo !!\e\C-e\C-j"' ;;
			list-keys)	ACT='"\eblist-keybindings\e\C-e\C-j"' ;;
			*)		ACT=${2} ;;
		esac

		if [[ ${MOD} == e ]]; then
			dbg_msg $"ReadlineCFG Setting:" $"${ACT}" $"e-${KEY}"
			bind "\\e${KEY}":self-insert
			echo -E \"\\e${KEY}\":${ACT} >> ${RC_FILE}
		elif [[ ${MOD} == C ]]; then
			dbg_msg $"ReadlineCFG Setting:" $"${ACT}" $"C-${KEY}"
			bind "\\C-${KEY}":self-insert
			echo -E \"\\C-${KEY}\":${ACT} >> ${RC_FILE}
		elif [[ ${MOD} == X ]]; then
			dbg_msg $"ReadlineCFG Setting:" $"${ACT}" $"${KEY}"
			#bind "${KEY}":self-insert
			echo -E ${KEY}:${ACT} >> ${RC_FILE}
		fi
	fi
}

shopt -s nullglob
bsng_keybindingsrc=( "$HOME"/.keybindings.bs-ng.* )
shopt -u nullglob

if (( "${#bsng_keybindingsrc[@]}" == 0 )); 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 menu_complete alias_expand_line \
		backward_char backward_word backward_delete_char delete_char \
		copy_backward_word copy_forward_word forward_char forward_word \
		overwrite_mode menu_complete_backward rerun_root backward_kill_line \
		list_keys; do

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

	done

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

fi
