doasedit/doasedit

45 lines
921 B
Plaintext
Raw Normal View History

#!/bin/sh
if [ -n "${2}" ]; then
2021-12-01 13:44:52 -05:00
printf 'Expected only one argument\n'
exit 1
elif [ -z "${1}" ]; then
2021-12-01 13:44:52 -05:00
printf 'No file path provided\n'
exit 1
elif [ "$(id -u)" -eq 0 ]; then
2021-12-01 13:44:52 -05:00
printf 'Cannot be run as root\n'
2021-02-03 17:01:13 -05:00
exit 1
fi
set -eu
2021-01-30 17:30:41 -05:00
tempdir="$(mktemp -d)"
2021-01-30 17:30:41 -05:00
trap 'rm -rf $tempdir' EXIT
srcfile="$(doas realpath "$1")"
2021-01-30 17:30:41 -05:00
if doas [ -f "$srcfile" ]; then
doas cp -a "$srcfile" "$tempdir"/file
doas cp -a "$tempdir"/file "$tempdir"/edit
# make sure that the file is editable by user
doas chown "$USER":"$USER" "$tempdir"/edit
chmod 600 "$tempdir"/edit
2021-01-31 14:38:31 -05:00
else
# create file with "regular" system permissions (root:root 644)
touch "$tempdir"/file
doas chown root:root "$tempdir"/file
2021-01-31 14:38:31 -05:00
fi
2021-01-30 17:30:41 -05:00
$EDITOR "$tempdir"/edit
2021-01-30 17:30:41 -05:00
doas tee "$tempdir"/file 1>/dev/null < "$tempdir"/edit
2021-01-30 17:30:41 -05:00
if doas cmp -s "$tempdir/file" "$srcfile"; then
2021-12-01 13:44:52 -05:00
printf 'Skipping write; no changes.\n'
exit 0
2021-01-30 17:30:41 -05:00
else
doas mv -f "$tempdir"/file "$srcfile"
exit 0
2021-01-30 17:30:41 -05:00
fi