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

readonly HISTFILE_TMP="${HISTFILE}.tmp.${BSNG_SESSION_TIME}_${BASH_SESSION_PID}"
export HISTFILE_TMP

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' > "${HISTFILE_TMP}"
}

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' > "${HISTFILE_TMP}"
}

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

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 "${HISTFILE_TMP}" ]]; then
				mv "${HISTFILE_TMP}" "${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
