#!/bin/sh
flags=""
while [ $# -gt 0 ]; do
	[ "$1" = "-n" -o "$1" = "-u" ] || break
	flags="${flags} $1"
	shift
done

if [ $# -le 0 ]; then
	echo "usage: jaq [-n] [-u] <awk expressions...>" >&2
	exit 1
fi
expr="$*"

# POSIX way to simulate -o pipefail if JSON data is invalid.
statusfile="$(mktemp)" || exit 1
trap -- "rm -f \"${statusfile}\"" "EXIT"
{ json2tsv ${flags} -r -F '\x1f' -R '\x1e'; echo $? >"${statusfile}"; } | \
	LC_ALL=C awk "BEGIN { FS = \"\x1f\"; RS = \"\x1e\" }${expr}"
statuscode="$(cat "${statusfile}" 2>/dev/null)$?"
[ "${statuscode}" = "00" ]
