#!/usr/bin/perl

# $Id: parsetrunk,v 1.3 1998/11/19 21:03:33 akolb Exp $

#
# This script reads Fast EtherChannel configuration data specified in a file in
# a rather free form and builds proper resmgr commands from it.
#
# Format of configuration data is:
#   keyword = value, keyword value; keyword=value
# Lines started with hash sign or semicolon are treated as comments.
#
# Recognized keywords:
#
#    keyword	type	 meaning
#    --------------------------------
#    trunk	integer  Trunk number
#    name	string	 Trunk name
#    slot	integer	 PCI slot.
#
# There may be several slots specified for each trunk. All specified slots will
# be gathered in one FastEtherChannel trunk.
#
# Lines starting with '%' are inserted literally in the output with the leading
# '%' substituted with '#'. The 'echo' keyword behaves the same way.
#


$line = 0;
$next_trunk = 4;
$header=1;

print <<EOF;
#!/bin/sh
PATH=/bin:/usr/bin:/sbin
#
# This file was automatically generated. 
# 
# Fast EtherChannel trunk configuration records for resmgr utility.
# See man(1M) resmgr for more information.
#
EOF

while (<>) {
    y/A-Z/a-z/;		# Canonicalize to lower case.
    # Comment lines are marked with either '#' or ';' in the first position.
    # next if /^[\#;]/;		# Skip comments;
    # next if /^\s*$/;		# Skip empty lines
    if (/^%/) {
	s/^%/\#/;
	print;
	next;
    }
    if (/^echo /) {		# Echo to the output.
	s/^echo /\#/;
	print;
	next;
    }
    next if ! /^\s*trunk/;	# Skip lines not beginning with "trunk" keyword.
    $val = '';
    $param = '';
    $name = '';
    $found = 0;
    # $original = $_;
    while ($_) {
	s/^[\s,:;=]*//;		# Skip initial garbage
	# Parse name argument.
	if (/^[\s]*name[\s=]+(\w[\w\d]+)/) {
	    $name = $1;
	    # print "name = $name\n";
	    s/^[\s]*name[\s=]+\w[\w\d]+//;
	} else {	# All other arguments.
	    ($keyword, $value, $_) = /^[\s]*([\w]+)[\s,;=:]*([\d]+)(.*)/;
	    # print "key = $keyword, val = $value\n";
	    if ($keyword eq "trunk") {
		$found = 1;
		$id = $value;
	    } elsif ($keyword eq "slot") {
		$param .= " SLOT";
		$val .= " $value";
	    }
	}
    }

    if ($found) {
	if ($header--) {
	    &print_header();
	}
	if ($id = 0) { $id = $next_trunk++; }
	if ($name eq '') { $name = "trunk" . "$id"; }
	$out = "resmgr -a -p'MODNAME UNIT name,s ";
	$out .= $param . "' -v 'trunk $id $name " . $val . "'";
	print "echo $out\n$out\n";
    }
}

sub print_header {
	    print <<'End_Of_Header';
#
for key in `resmgr |grep trunk|awk '{print $1}'`; do
    echo "Removing `resmgr -k $key`"     
    resmgr -r -k $key
done
#
End_Of_Header
}
