1#!/bin/sh
2# options: --help, --version, --debug, -i
3version() {
4    echo "dwgfilter @PACKAGE_VERSION@"
5    exit
6}
7help() {
8    echo "dwgfilter [OPTIONS...] dwgfile"
9    echo ""
10    echo "Allow custom jq queries on a temporay JSON dump."
11    echo ""
12    echo "OPTIONS: --help,--version"
13    echo "  --debug  keep the tmp json"
14    echo "  -i       write back in-place, with an updating JQ query"
15    echo "  ...      all other options are passed to jq. See 'man jq'"
16    exit
17}
18
19opts=
20# get last arg
21for dwg; do true; done
22for arg in "$@"
23do
24    case $arg in
25        --help) help ;;
26        --version) version ;;
27        --debug) debug=1 ;;
28        $dwg) if [ ! -f "$dwg" ]; then echo DWG "$dwg" not found; exit 1; fi ;;
29        -i)   writemode=1 ;;
30        *)    opts="$opts $arg" ;;
31    esac
32done
33if [ ! -f "$dwg" ]
34then
35    echo Wrong input DWG "$dwg"
36    exit 1
37fi
38if [ -z "$opts" ]
39then
40    echo Input JQ query arguments missing
41    exit 1
42fi
43
44prefix="@prefix@"
45exec_prefix="@exec_prefix@"
46jq="@JQ@"
47jq="${jq:-jq}"
48json="/tmp/dwgfilter-$$.json"
49selfpath="$(realpath "$0")"
50if [ "$selfpath" = "@bindir@/dwgfilter" ]; then
51    dwgread="@bindir@/dwgread"
52    dwgwrite="@bindir@/dwgwrite"
53else
54    dwgread="$(dirname "$selfpath")/dwgread"
55    dwgwrite="$(dirname "$selfpath")/dwgwrite"
56fi
57
58if [ -n "$debug" ]; then
59    dwgread="$dwgread -v3"
60    dwgwrite="$dwgwrite -v3"
61fi
62echo "$dwgread -O json -o $json $dwg"
63$dwgread -O json -o "$json" "$dwg"
64echo "$jq $opts $json"
65$jq "$opts" "$json"
66fail=$?
67if [ $fail = 0 ] && [ -n "$writemode" ]; then
68    mv "$dwg" "$dwg.bak"
69    echo "$dwgwrite -o $dwg $json"
70    if $dwgwrite -o "$dwg" "$json"; then
71        :
72    else
73        mv "$dwg.bak" "$dwg"
74        fail=1
75    fi
76fi
77if [ -z "$debug" ]; then
78    rm "$json"
79fi
80exit $fail
81