#!/bin/sh -e

export TMPDIR=/tmp/

trap 'trap - EXIT HUP QUIT TERM INT ABRT; rm -f "$tmp" "$tmpcopy"' EXIT HUP QUIT TERM INT ABRT

for file; do
  # shellcheck disable=SC2249
  case "${file}" in -*) file=./"${file}" ;; esac

  tmp="$(mktemp)"
  if [ -f "${file}" ] && [ ! -r "${file}" ]; then
    doas cat "${file}" > "${tmp}"
  elif [ -r "${file}" ]; then
    cat "${file}" > "${tmp}"
  fi

  tmpcopy="$(mktemp)"
  cat "${tmp}" > "${tmpcopy}"

  ${EDITOR:-vi} "${tmp}"

  if cmp -s "${tmp}" "${tmpcopy}"; then
    echo 'File unchanged, exiting...'
  else
    doas dd if="${tmp}" of="${file}"
    echo 'Done, changes written'
  fi

  rm "${tmp}" "${tmpcopy}"
done

