#!/bin/sh -e
#
# edit - edit a file with appropriate rights, creating parent dirs if necessary

test ! -f "$1" && (mkdir -p "$(dirname "$1")" || sudo mkdir -p "$(dirname "$1")")

echo "Editing $* ..."

if test -w "$1" || { test ! -f "$1" && test -w "$(dirname "$1")"; }; then
  ${EDITOR:-vi} "$@"
else
  if command -v sudoedit >/dev/null 2>&1; then
    sudoedit "$@"
  else
    command sudo --edit "$@"
  fi
fi
