# This file is part of shellfire core. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/shellfire-dev/core/master/COPYRIGHT. No part of shellfire core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
# Copyright © 2014-2015 The developers of shellfire core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/shellfire-dev/core/master/COPYRIGHT.


core_usesIn core/variable array

core_trap_initialise()
{
	local trapNames='EXIT|HUP|INT|QUIT|ABRT|PIPE|TERM|TSTP|USR1|USR2'
	local trapName
	local IFS='|'
	for trapName in $trapNames
	do
		trap "_core_trap_executeOnTrap $trapName" "$trapName" 
	done
}
core_functions_register _core_functions core_trap_initialise

core_trap_addOnCleanUp()
{
	#core_trap_addHandler "$1" EXIT INT TERM ABRT QUIT PIPE
	core_trap_addHandler "$1" EXIT INT TERM ABRT QUIT
}

_core_trap_executeOnTrap()
{
	local trapName="$1"
	local arrayName="core_trap_handlers_${trapName}"
	
	if core_variable_array_isUnset "$arrayName"; then
		return 0
	fi
	core_variable_array_iterateAsCallbacks "$arrayName"
}

core_trap_addHandler()
{
	local handler="$1"
	shift 1
	
	local trapName
	for trapName in "$@"
	do
		case "$trapName" in
		
			# DEBUG|ERR|RETURN are not supported
		
			EXIT|HUP|INT|QUIT|ABRT|PIPE|TERM|TSTP|USR1|USR2)
				:
			;;
		
			*)
				core_exitError $core_commandLine_exitCode_SOFTWARE "Unrecognised or unsupported trap '$trapName'"
			;;
		
		esac
	done
	
	for trapName in "$@"
	do
		core_variable_array_append core_trap_handlers_${trapName} "$handler"
	done
}
