#!/bin/sh

# scriptdemo.sh
#
# This sample shell script demonstrates how to use MinimServer scripting
# to send programmatic commands to MinimServer and how to capture the
# output from these commands.
#
# In this simple demo, commands are read from standard input and the
# output from each command is printed to standard output. A real scripting
# application would use programmatic logic to generate commands and
# process command output and could use the output from one command to
# determine which command to issue next.
#
# You are free to adapt and modify this sample code in any way.

# create named pipes for communication with the mscript program
rm -f inpipe outpipe
mknod -m a=rw inpipe p
mknod -m a=rw outpipe p

# launch the mscript program with the -i option
SCRIPTDIR="$(dirname "$0")"
"${SCRIPTDIR}/mscript" -i <inpipe >outpipe &

# open the named pipes
exec 4>inpipe
exec 3<outpipe

# main loop: prompt the user for commands and print the output from each
# command to standard output
echo "Enter commands (null line to exit):"
while :
do
    # read the command and exit if null
    read line
    if [ -z "$line" ]; then
        break
    fi
    # send the command to the mscript program
    echo "$line" >&4
    # output loop: read the output returned by the mscript program for
    # this command and print each output line to standard output
    while :
    do
        # read a line of output from the mscript program
        read output <&3
        echo "$output"
        # we are running mscript with the -i option, so the output from each
        # command ends with a status line starting with the characters '+:'
        if echo "$output" | grep -q '^\+:'; then
            break
        fi
    done
done
