#!/bin/sh
# options: --help, --version, --debug, -i
version() {
    echo "dwgfilter 0.15"
    exit
}
help() {
    echo "dwgfilter [OPTIONS...] dwgfile"
    echo ""
    echo "Allow custom jq queries on a temporary JSON dump."
    echo ""
    echo "OPTIONS: --help,--version"
    echo "  --debug  keep the tmp json"
    echo "  -i       write back in-place, with an updating JQ query"
    echo "  ...      all other options are passed to jq. See 'man jq'"
    echo ""
    echo "The jq query is a single argument, so quote it. With -i it must"
    echo "return the whole changed JSON."
    echo ""
    echo "Examples:"
    echo "  dwgfilter '[.OBJECTS[] | select(.entity) | .entity] | group_by(.) | map({(.[0]): length}) | add' example.dwg"
    echo "  dwgfilter '.OBJECTS[] | select(.object == \"LAYER\") | .name' example.dwg"
    echo "  dwgfilter '.OBJECTS[] | select(.entity == \"CIRCLE\") | [.handle, .center, .radius]' example.dwg"
    echo "  dwgfilter -i '.HEADER.TEXTSIZE = 5' example.dwg"
    echo "  dwgfilter -i 'del(.OBJECTS[] | select(.entity == \"TEXT\"))' example.dwg"
    exit
}

opts=
# get last arg
for dwg; do true; done
for arg in "$@"
do
    case $arg in
        --help) help ;;
        --version) version ;;
        --debug) debug=1 ;;
        "$dwg") if [ ! -f "$dwg" ]; then echo DWG "$dwg" not found; exit 1; fi ;;
        -i)   writemode=1 ;;
        *)    opts="$opts $arg" ;;
    esac
done
if [ ! -f "$dwg" ]
then
    echo Wrong input DWG "$dwg"
    exit 1
fi
if [ -z "$opts" ]
then
    echo Input JQ query arguments missing
    exit 1
fi

prefix="/usr/local"
exec_prefix="${prefix}"
jq="jq"
jq="${jq:-jq}"
json="$(mktemp "${TMPDIR:-/tmp}/dwgfilter.XXXXXX.json")" || exit 1
if [ -z "$debug" ]; then
    trap 'rm -f "$json"' EXIT
    trap 'exit 2' INT TERM
fi
selfpath="$(realpath "$0")"
if [ "$selfpath" = "${exec_prefix}/bin/dwgfilter" ]; then
    dwgread="${exec_prefix}/bin/dwgread"
    dwgwrite="${exec_prefix}/bin/dwgwrite"
else
    dwgread="$(dirname "$selfpath")/dwgread"
    dwgwrite="$(dirname "$selfpath")/dwgwrite"
fi

if [ -n "$debug" ]; then
    dwgread="$dwgread -v3"
    dwgwrite="$dwgwrite -v3"
fi
echo "$dwgread -O json -o $json $dwg"
$dwgread -O json -o "$json" "$dwg"
echo "$jq $opts $json"
if [ -n "$writemode" ]; then
    # the updating query returns the whole json, which is written back
    $jq "$opts" "$json" >"$json.new"
    fail=$?
    if [ $fail = 0 ]; then
        mv "$json.new" "$json"
    else
        rm -f "$json.new"
    fi
else
    $jq "$opts" "$json"
    fail=$?
fi
if [ $fail = 0 ] && [ -n "$writemode" ]; then
    mv "$dwg" "$dwg.bak"
    echo "$dwgwrite -o $dwg $json"
    if $dwgwrite -o "$dwg" "$json"; then
        :
    else
        mv "$dwg.bak" "$dwg"
        fail=1
    fi
fi
if [ -n "$debug" ]; then
    echo "Keeping JSON dump: $json"
fi
exit $fail
