#!/bin/sh

error() {
  echo "$*" >/dev/stderr
}
usage() {
  cat >/dev/stderr <<EOF
usage: $0 [OPTIONS] <systemd.unit>

displays the output of the last run of the specified systemd unit.

similar to 'systemctl status <systemd.unit>' but more than just the last 10 lines.


OPTIONS:
 -n <lines>	limit output to the last <lines> lines ('0' means no limit)

EOF

  if [ -n "$*" ]; then
    cat >/dev/stderr <<EOF
ERROR: $@

EOF
    exit 1
  fi
  exit 0
}

show_info() {
error "unit: ${unit}"
error "lines: ${lines}"
error "IncocationID: ${invocationid}"
}


lines=0

OPTIND=1 # Reset is necessary if getopts was used previously in the script.  It is a good idea to make this local in a function.
while getopts "hn:" opt; do
	case "${opt}" in
		n)
			lines="$((OPTARG))"
			;;
		h)
			usage
			;;
		?)
			error
			usage "Invalid option!"
			;;
	esac
done
shift "$((OPTIND-1))" # Shift off the options and optional --.

unit="$1"
test -n "${unit}" || usage "No systemd unit specified!"

if test "$#" -ne 1; then
  shift 1
  usage "Stray arguments: $*"
fi

test "${lines}" -gt 0 || lines=""
invocationid="$(systemctl show --value -p InvocationID "${unit}" 2>/dev/null)"
#show_info

if [ -n "${invocationid}" ]; then
  systemctl status --lines=0 "${unit}" && echo
  journalctl ${lines:+--lines=${lines}} _SYSTEMD_INVOCATION_ID="${invocationid}"
else
  systemctl status ${lines:+--lines=${lines}} "${unit}"
fi
