#!/bin/sh

# Demonstrates how to embed awk scripts in plumb without quoting hell.
# Runs netcat on port 9000 and an awk script server that reads input
# from the client connection and talks back.


# First store the awk script in a shell variable to keep the plumb command
# line short and readable. Since we are using single quoting here, it's
# the same for quoting as the common awk 'script' form:
script='
BEGIN {
	print "hello"
	print "I was started at", started
	fflush("/dev/stdout")
}

/hi/ || /hello/ {
	print "hi again!"
	fflush("/dev/stdout")
	next
}

{
	print "echoing: " $0
	fflush("/dev/stdout")
}
'

# Second, we are going to pass in a variable. This is useful for configuration
# or command line arguments that should be made accessible for an embedded
# awk script
now="`date`"

# run plumb, inject the script as a variable and a started=$now string that
# will be given to awk with -v. The plumb script runs process with the
# variable and script passed to awk.
exec plumb   -v ascript "$script"   -v dt "started=$now"   '
include stdio

p1in=[hub]
p2out=[hub]

# start the two processes in 69 setup
p1in:* | p1={netcat -l -p 9000} | p2={awk -v ${dt} ${ascript}} | p2out:*
p2out:* | p1in:*

# make sure stderr of each process is sent to plumb stderr
p1:2 | STDERR:*
p2:2 | STDERR:*
'
