#!/pkg/bin/ksh
#------------------------------------------------------------------
# replace parser command funtionality
#
# Copyright (c) 2015 by cisco Systems, Inc.
# All rights reserved.
#------------------------------------------------------------------


echo $1
echo $2
echo $3
nvgen -c -l 1 -t 1 -o 1 > /tmp/replace_run.$3

# The entire config is broken into blocks. Each block consists of
# global command and submodes within that. Some commands like 'hostname'
# are block in itself. on the otherhand something like 'router ospf 10'
# could have multiple submodes within the block.
# example of blocks
#
# 1. Router OSPF block
#router ospf 10
# area 1
#  cost 20
# !
# area 2
#  cost 40
#!
#
# 2.  hostname
#hostname myrouter

sed -r -n -e '
/^ / b insert       #if line starts with space insert to current block
/^!/ b insert       #if line starts with bang insert to current block
/^end/ b insert     #if line starts with 'end' insert to current block

x;                  #we will be here if a block is complete. Pattern buffer 
                    #has a first line of new block. hold buffer has an entire
                    #block. Now swap pattern and hold buffer.
       
/'"$1"'/ {p};       #if pattern1 is found in complete block print it.

x;                  #swap hold buffer and pattern, so pattern has the new line read.
/'"$1"'/ {          #if the line has pattern1 then add two lines, 
                    # a. - with this line and
                    # b. + with pattern1 replaced with pattern2
            s/^/-/g;
            h;
            s/^-/+/g;
            s/'"$1"'/'"$2"'/g;
            H
            $!d
         }
h;                  # overwrite hold buffer with pattern buffer
$!d;

:insert                 #insert the line(s) into the block 
    /'"$1"'/ {          #if the line has pattern1 then add two lines, 
                        # a. - with this line and
                        # b. + with pattern1 replaced with pattern2
                s/^/-/g;
                H;
                s/^-/+/g;
                s/'"$1"'/'"$2"'/g;
             }
    H;                  # append pattern buffer to hold buffer
    $!d;
' < /tmp/replace_run.$3 > /tmp/sed_diff.$3

echo $?
