You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
921 B

if [ -n "${2}" ]; then
printf 'Expected only one argument\n'
exit 1
elif [ -z "${1}" ]; then
printf 'No file path provided\n'
exit 1
elif [ "$(id -u)" -eq 0 ]; then
printf 'Cannot be run as root\n'
exit 1
set -eu
tempdir="$(mktemp -d)"
trap 'rm -rf $tempdir' EXIT
srcfile="$(doas realpath "$1")"
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
# create file with "regular" system permissions (root:root 644)
touch "$tempdir"/file
doas chown root:root "$tempdir"/file
$EDITOR "$tempdir"/edit
doas tee "$tempdir"/file 1>/dev/null < "$tempdir"/edit
if doas cmp -s "$tempdir/file" "$srcfile"; then
printf 'Skipping write; no changes.\n'
exit 0
doas mv -f "$tempdir"/file "$srcfile"
exit 0