#!/usr/bin/env bash
#
# plview - view plist files in xml or json format

usage() {
  cat <<EOF
view plist files in xml or json format

plview [-xml|-json] <file>.plist

options:
  -xml             - View in xml format (default)
  -json            - View in json format

  -h, --help       - Show this message
EOF
}

fmt=xml
plistfile=

while [ "$#" -gt 0 ]; do
  case "$1" in
    -xml)
      fmt=xml
      shift
      ;;
    -json)
      fmt=json
      shift
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      plistfile="$1"
      shift
      ;;
  esac
done

if [ -z "${plistfile}" ]; then
  printf "Please provide a plist file.\n\n"
  usage
  exit 1
fi
if [ ! -f "${plistfile}" ]; then
  printf "The file %s does not exist.\n\n" "${plistfile}"
  usage
  exit 1
fi

rand="$(xxd -l2 -ps /dev/urandom)"
tmpf=$(mktemp "${TMPDIR:-/tmp}"/plist-"${rand}"."${fmt}")
trap 'command rm -f -- "$tmpf"' EXIT

if [ "${fmt}" = "json" ]; then
  plutil -convert json -o "${tmpf}" "${plistfile}"
else
  plutil -convert xml1 -o "${tmpf}" "${plistfile}"
fi
cat "${tmpf}"
