#!/bin/sh
#
# smistrip --
#
#	extract MIB modules from text files, like RFCs or I-Ds.
#
# Copyright (c) 1999 Frank Strauss, Technical University of Braunschweig.
#
# See the file "COPYING" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# $Id: smistrip,v 1.1 1999/08/01 20:53:39 jochen Exp $
#



do_version () {
    echo "smistrip 0.0.2"
}



do_usage () {
    echo "Usage: smistrip [-d dir] [-m module] [-n] file1 [file2 [...]]"
    echo "          -d dir     write module to directory dir"
    echo "          -m module  strip only the specified module"
    echo "          -n         do not write module files"
    echo "          file1 ...  input files to parse (RFCs, I-Ds, ...)"
}



do_strip () {
    cat $1 | awk -vtest="$test" -vdir="$dir" -vsingle="$single" '

    # start of module
    /^[ \t]*[A-Za-z0-9-]* *DEFINITIONS */ {
	module = $1
	n = 0
    }

    # process each line of a module
    {
	if (length(module) > 0) {
	    if ($0 ~ /\[Page [0-9]*\] */) {
		skip = 3
		while (line[n-1] ~ /^[ \t]*$/) { n-- }
	    } else {
		if (skip == 0) {
		    #
		    # if the first line on a page matches a special
		    # pattern, we insert a blank line.
		    #
		    if (($0 ~ /^[ \t]*[A-Za-z0-9-]+ *MODULE-IDENTITY/) ||
			($0 ~ /^[ \t]*--/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *::=/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *OBJECT-TYPE/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *OBJECT-IDENTITY/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *TRAP-TYPE/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *NOTIFICATION-TYPE/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *OBJECT-GROUP/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *NOTIFICATION-GROUP/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *TEXTUAL-CONVENTION/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *AGENT-CAPABILITIES/) ||
			($0 ~ /^[ \t]*[A-Za-z0-9-]+ *MODULE-COMPLIANCE/)) {
			line[n++] = ""
		    }
		    if ($0 ~ /[^ \t]/) {
		        line[n++] = $0
		    } else {
			skip++
		    }
	    	}
		if (skip < 0) {
		    line[n++] = $0
		}
		skip--
	    }
	}
    }

    # end of module
    /^[ \t]*END[ \t]*$/ {
	if ((length(single) == 0) || (single == module)) {
	    strip = 99
	    for (i=0 ; i < n ; i++) {
	        # find the lowest first column
	        p = match(line[i], "[^ ]")
	        if ((p < strip) && (length(line[i]) > p)) { strip = p }
	    }

	    if (test != "1") {
		if (dir) {
		   f = dir"/"module
		} else {
		   f = module
		}
	        for (i=0 ; i < n ; i++) {
		    print substr(line[i], strip) >f
		}
	    }

	    print module ": " n " lines."
	}
	module = ""
    }
    '
}



while getopts Vhnm:d: c ; do
    case $c in
	n)	test=1
		;;
	m)	single=$OPTARG
		;;
	d)	dir=$OPTARG
		;;
	h)	do_usage
		exit 0
		;;
	V)	do_version
		exit 0
		;;
	*)	do_usage
		exit 1
		;;
    esac
done

shift `expr $OPTIND - 1`



if [ $# -eq 0 ] ; then
    do_strip -
else 
    for f in $@ ; do
	do_strip $f
    done
fi

exit 0
