#!/bin/sh


# (c) Jonas Bechtel 2020


#rm -r X/mem # NOT NOW but on start of pd server!!
mkdir -p X/mem

number=0
[ -e X/mem/NUMBER ] && number=`cat X/mem/NUMBER`
search= # (Multi-line)

while read line; do
	number=$((number+1))
	echo $number > X/mem/NUMBER
	
	[ -z "$search" -a -z "$line" ] && continue;
	
	if [ -n "$search" ]; then
		if printf '%s' "$line" | grep -E '^[^{]*[}]' >/dev/null; then
			line="$search
$line"
			search=
		fi
	fi
	
	if printf '%s' "$line" | tail -n 1 | grep -E '[{][^}]*$' >/dev/null; then
		search="$line"
		continue
	fi
	
	
	p1=${line%% *}
	rest="${line#* }"
	p2=${rest%% *}
	
	allowedFile=allowed1/DEFAULT
	name=DEFAULT
	if [ -e X/allowed1/$p1 ]; then
		allowedFile=allowed1/$p1
		name=A1#$p1
	elif [ -e X/allowed2/$p2 ]; then
		allowedFile=allowed2/$p2
		name=A2#$p2
	else
		printf >&2 "%s: WARNING: Cannot handle line '%s'" "$0" "$line"
	fi
	
	policy="`grep policy= X/$allowedFile`"
	policy="${policy#*=}"
	
	[ _"$policy" = _ignore ] && continue;
	
	objdescr="`grep obj= X/$allowedFile`"
	objdescr="${objdescr#*=}"
	
	tagobj=
	if [ \! _"${objdescr#*tags}" = _"$objdescr" ]; then
		lineaftertags="${line#* -tags }"
		lineaftertags="${lineaftertags#[list }"
		tagobj="${lineaftertags%% *}"
	fi
	
	obj="`printf %s "$line" \
	| awk 'NR == 1 {
			tags="'"$tagobj"'";
			obj= '"$objdescr"';
			sub(/{/, "", obj);
			print obj}'`"
	
	[ -z "$obj" ] && obj=DEFAULT#
	
	echo "$line"
#	echo \#$number: allowedFile=$allowedFile policy=$policy tagobj=$tagobj obj=$obj
	
	# Special magic: "delete all" means all
	if [ _"$name" = _A2#delete ]; then
		if printf '%s' "$line" | grep -E 'delete all$' >/dev/null; then
			rm X/mem/*/"${line%% *}"/* 2>/dev/null
			policy=ignore
		elif printf '%s' "$line" | grep -E 'delete commentbar$' >/dev/null; then
			policy=last
			obj="${line%% *}"
		fi
	fi
	
	if [ _"$policy" = _clear ]; then
		rm X/mem/*/"$obj"/*
		
		# Special magic for itemconfigure
		if [ -n "`ls "X/mem/A2#itemconfigure/$obj"%*/* 2>/dev/null`" ]; then
			rm "X/mem/A2#itemconfigure/$obj"%*/*
		fi
		# Special magic for few cases of configure
		if [ -n "`ls X/mem/A2#configure/"$obj"%-cursor/* 2>/dev/null`" ]; then
			rm X/mem/A2#configure/"$obj"%-cursor/*
		fi
		
		continue
	fi
	
	mkdir -p X/mem/"$name/$obj"
	
	if [ _"$policy" = _last ]; then
		rm X/mem/"$name/$obj"/* 2>/dev/null
	fi
	
	printf '%s\n' "$line" > X/mem/"$name/$obj/$number"
	
done




