#!/bin/sh -x
#
# secure-edit [FILE] - secure editing of GPG-encrypted files
#
# ---
# source: https://github.com/sunaku/home

ENCRYPT='gpg2 --encrypt --sign --armor'
DECRYPT='gpg2 --decrypt' # also verifies signature if found
DESTROY='shred --force --zero --remove'
# disable swap file and viminfo
# -n no swap file, use memory only
# -i no .viminfo
EDIT="${EDITOR-} -n -i NONE"

source="$1"
shift
encrypt=$(mktemp)
decrypt=$(mktemp)
trap '$DESTROY "$encrypt" "$decrypt"' EXIT
trap 'exit' TERM INT
echo "secure-edit: source=${source} decrypt=${decrypt} encrypt=${encrypt}"

# create new source file if necessary.  this
# is useful when securely editing a new file
if ! [ -e "${source}" ]; then
  touch "${source}" \
    && ${ENCRYPT} </dev/null >"${source}" \
    || exit "$?"
fi

touch "${decrypt}" "${encrypt}" \
  && chmod 0600 "${decrypt}" "${encrypt}" \
  && ${DECRYPT} <"${source}" >"${decrypt}" \
  && ${EDIT} "${decrypt}" \
  && ${ENCRYPT} <"${decrypt}" >"${encrypt}" \
  && cp -p "${encrypt}" "${source}"
