#!/bin/bash
#########################################################
# 							#
# This is BashStyle-NG  				#
#							#
# Licensed under GNU GENERAL PUBLIC LICENSE v3    	#
#							#
# Copyright Christopher Roy Bratušek			#
#							#
#########################################################

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
}

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
else
	if [ -z "${BSNG_TMP_HISTFILE+x}" ]; then
		readonly BSNG_TMP_HISTFILE="${HISTFILE}.tmp.${BSNG_SESSION_TIME}_${BASH_SESSION_PID}"
		export BSNG_TMP_HISTFILE
	fi

	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 () {
		if [[ ! ${lastcommand} == history* ]]; then
			builtin history -a
			builtin history -c

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

			mv "${BSNG_TMP_HISTFILE}" "${HISTFILE}" &>/dev/null
			builtin history -r
		fi
	}
fi
