2021-02-03 16:22:41 -05:00
|
|
|
#!/bin/bash
|
|
|
|
if [ ! -z "${2}" ]; then
|
|
|
|
echo "Expected only one argument"
|
|
|
|
exit 1
|
|
|
|
elif [ -z "${1}" ]; then
|
|
|
|
echo "No file path provided"
|
|
|
|
exit 1
|
2021-02-03 17:01:13 -05:00
|
|
|
elif [ "$EUID" -eq 0 ]; then
|
|
|
|
echo "Cannot be run as root"
|
|
|
|
exit 1
|
2021-02-03 16:22:41 -05:00
|
|
|
fi
|
|
|
|
|
2021-02-03 17:23:53 -05:00
|
|
|
set -Eeuo pipefail
|
2021-01-30 17:30:41 -05:00
|
|
|
|
2021-11-30 08:37:07 -05:00
|
|
|
tempdir="$(mktemp -d)"
|
2021-01-30 17:30:41 -05:00
|
|
|
|
2021-02-03 17:23:53 -05:00
|
|
|
trap "rm -rf $tempdir" EXIT
|
2021-02-03 16:22:41 -05:00
|
|
|
srcfile="$(doas realpath $1)"
|
2021-01-30 17:30:41 -05:00
|
|
|
|
2021-02-03 16:22:41 -05:00
|
|
|
if doas [ -f "$srcfile" ]; then
|
2021-09-28 13:39:26 -04:00
|
|
|
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)
|
2021-02-03 17:07:23 -05:00
|
|
|
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
|
|
|
|
2021-02-03 17:07:23 -05:00
|
|
|
$EDITOR $tempdir/edit
|
2021-01-30 17:30:41 -05:00
|
|
|
|
2021-02-03 17:07:23 -05:00
|
|
|
cat $tempdir/edit | doas tee $tempdir/file 1>/dev/null
|
2021-01-30 17:30:41 -05:00
|
|
|
|
2021-09-28 13:39:26 -04:00
|
|
|
if doas cmp -s "$tempdir/file" "$srcfile"; then
|
2021-01-30 17:30:41 -05:00
|
|
|
echo "Skipping write; no changes."
|
2021-02-03 17:23:53 -05:00
|
|
|
exit 0
|
2021-01-30 17:30:41 -05:00
|
|
|
else
|
2021-02-03 17:07:23 -05:00
|
|
|
doas mv -f $tempdir/file $srcfile
|
2021-02-03 17:23:53 -05:00
|
|
|
exit 0
|
2021-01-30 17:30:41 -05:00
|
|
|
fi
|
|
|
|
|