#!/bin/sh
# This script improves the CLI of QGRAF by replacing its config file
# (qgraf.dat) with command line parameters.
# The config is then generated in a temporary directory, and QGRAF is
# executed there.
# Usage:
#   qgraf.sh \
#       --model=<modelfile> \
#       --style=<stylefile> \
#       --output=<outfile> \
#       --<qgraf option>=<value> ...

tmpdir=$(mktemp -d)
trap "rm -rf '$tmpdir'" EXIT
cat >$tmpdir/qgraf.dat <<'EOF'
output='outputfile';
style='stylefile';
model='modelfile';
EOF

for arg in "$@"; do
    case $arg in
        --model=*) cp "${arg#*=}" "$tmpdir/modelfile";;
        --style=*) cp "${arg#*=}" "$tmpdir/stylefile";;
        --output=*) outputfile=${arg#*=};;
        --*=*)
            key=${arg%%=*};
            key=${key#--};
            val=${arg#*=};
            printf "%s=%s;\n" "$key" "$val" >> $tmpdir/qgraf.dat;
            ;;
        *)
            echo "unrecognized option: $arg";
            exit 1
            ;;
    esac
done
QGRAF=$PWD/qgraf/qgraf
(cd "$tmpdir" && $QGRAF) || exit 1
[ -e "$tmpdir/outputfile" ] || exit 1
cp "$tmpdir/outputfile" "$outputfile" || exit 1
