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

if [ -z "${BSNG_TMP_HISTFILE+x}" ]; then
	readonly BSNG_TMP_HISTFILE="${HISTFILE}.tmp.${BSNG_SESSION_TIME}_${BASH_SESSION_PID}"
	export BSNG_TMP_HISTFILE
fi

bashstyle_history () {
	case "${1}" in
		-D )
			local history_lines_matching
			local internal_counter
			local history_command

			shift
			history_command="${@}"

			if [ -n "${history_command}" ]; then
				history_lines_matching=$(builtin history | gawk -v pattern="^ .*[0-9]  ${history_command}" '$0 ~ pattern{print $1}')
				if [ -z "${history_lines_matching}" ]; then
					echo "$(eval_gettext "no history entry matching ${history_command}")"
				else
					internal_counter=0
					for line in ${history_lines_matching}; do
						builtin history -d $((line-internal_counter))
						builtin history -w
						internal_counter=$((internal_counter+1))
					done
				fi
			else
				echo "$(eval_gettext "no command to delete given!")"
			fi
		;;

		-g )
			shift
			builtin history | grep "${@}"
		;;

		* )
			builtin history "${@}"
		;;
	esac
}

erasehistorydups () {
	gawk '/^#/{if (x)print x;x="";}{x=(!x)?$0:x"HISTDILIMITER"$0;}END{print x;}' "${HISTFILE}" | \
		tac | gawk -F'HISTDILIMITER' '!x[$2]++' | \
		tac | sed -e 's/HISTDILIMITER/\n/g' > "${BSNG_TMP_HISTFILE}"
}

ignorehistorydups () {
	gawk '/^#/{if (x)print x;x="";}{x=(!x)?$0:x"HISTDILIMITER"$0;}END{print x;}' "${HISTFILE}" | \
		gawk -F'HISTDILIMITER' '!x[$2]++' | \
		sed -e 's/HISTDILIMITER/\n/g' > "${BSNG_TMP_HISTFILE}"
}

ignorehistoryspc () {
	gawk '/^#/{if (x)print x;x="";}{x=(!x)?$0:x"HISTDILIMITER"$0;}END{print x;}' "${HISTFILE}" | \
		sed -e '/HISTDILIMITER /d' > "${BSNG_TMP_HISTFILE}"
}

ignorehistoryboth () {
	ignorehistorydups
	ignorehistoryspc
}

bashstyle_history_sync () {
	shopt -s nullglob
	bsng_histfile=( "${HISTFILE}".tmp.* )
	shopt -u nullglob

	if (( "${#bsng_histfile[@]}" == 0 )); then
		if [[ ! ${lastcommand} == *history* ]]; then
			builtin history -a
			builtin history -c

			case ${HISTCONTROL} in
				erasedups )	erasehistorydups ;;
				ignoredups)	ignorehistorydups ;;
				ignorespace)	ignorehistorspc ;;
				ignoreboth)	ignorehistoryboth ;;
			esac

			if [[ -f "${BSNG_TMP_HISTFILE}" ]]; then
				mv "${BSNG_TMP_HISTFILE}" "${HISTFILE}" &>/dev/null && \
				builtin history -r
			fi
		fi
	fi
}

if bt "$(ini_get history_isolate)"; then
	dbg_msg "$(eval_gettext "BashStyle-NG Setting:")" "$(eval_gettext "History Isolation")" "$(eval_gettext "On")"
	dbg_log unset HISTFILE
	dbg_log set +o history
	dbg_log enable -n history
fi
