#!/bin/sh
#
# Strips away various tagged lines
#
# (P) & (C) 2001-2002 by Peter Bieringer <pb@bieringer.de>
#
# Version: 2002-01-08
#
# Changes:
#  20010202: initial
#  20010208: add some info, minor fixes
#  20020108: add new tags
#  20020109: fix bug using "#@+RH7@#" (attention: this toolset will procude failure stripping of old versions of scripts)

TAG_REMOVE_DEBUG="#@-DEB@#"
TAG_REMOVE_RH7="#@-RH7@#"
TAG_REMOVE_RH7_START="#@-RH7@start#"
TAG_REMOVE_RH7_END="#@-RH7@end#"
TAG_INSERT_RH7="#@+RH7@#"
TAG_REMOVE_INFO="#@-INF@#"

# Strip functions
function stripfunction () {
	file=$1
	shift
	opt=$*
	egrepotion=""
	rh7=0

	echo "Opt: $opt" >&2

	for o in $opt; do
		case $o in
			rh7)
				echo "Hit rh7" >&2
				egrepoption="$egrepoption|$TAG_REMOVE_RH7"
				rh7=1
				;;
			debug)
				echo "Hit debug" >&2
				egrepoption="$egrepoption|$TAG_REMOVE_DEBUG"
				;;
			info)
				echo "Hit info" >&2
				egrepoption="$egrepoption|$TAG_REMOVE_INFO"
				;;
		esac
	done

	# Strip away leading "|"
	egrepoption=`echo $egrepoption | sed 's/^|//g'`
	echo "egrep option: $egrepoption" >&2

	echo "INFO : File '$file' has lines: `wc -l $file | awk '{ print $1 }'`" >&2

	if [ $rh7 = 1 ]; then
		echo "DEBUG: RH7 insert" >&2
		local rh7_start=0
		local linecounter=0
		cat $file | egrep -v $egrepoption | sed "s/^$TAG_INSERT_RH7//g" | grep -v $TAG_INSERT_RH7 | while IFS="" read line; do
			local linecounter=$[ $linecounter + 1 ]
			#echo -ne "DEBUG: Line: $linecounter\r" >&2
			if echo "$line" | grep -q $TAG_REMOVE_RH7_START; then
				echo "DEBUG: Hit tag $TAG_REMOVE_RH7_START" >&2
				local rh7_start=1
			fi
			if [ $rh7_start -eq 0 ]; then
				echo -e "$line"
			fi
			if echo "$line" | grep -q $TAG_REMOVE_RH7_END; then
				echo "DEBUG: Hit tag $TAG_REMOVE_RH7_END" >&2
				local rh7_start=0
			fi
		done
	else
		cat $file | egrep -v $egrepoption
	fi
}


function help() {
cat <<END
This simple tool strips away lines with special tags or remove only tags

Usage ./striptool4ipv6scripts filename tag1 [tag2 [tag3 ...] ]

I.e. for RH7/rawhide you can use
  ./striptool4ipv6scripts filename rh7 info debug >filename.stripped
 This will do
  * remove all lines with given "-rh7" tag
  * remove only tag with given "+rh7" tag
  * remove all lines with given "-info" tag
  * remove all lines with given "-debug" tag

 Currently supported tags:
  rh7 info debug
END
}
# Main
file=$1
if [ ! -z $1 ]; then
	shift
	options=$*
fi

if [ -z "$file" ]; then
	echo "Missing filename"
	help
	exit 1
fi

if [ -z "$options" ]; then
	echo "Missing strip options"
	help
	exit 1
fi

stripfunction $file $options

