doasedit/doasedit

53 lines
1.2 KiB
Plaintext
Raw Normal View History

#!/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
fi
set -Eeuo pipefail
2021-01-30 17:30:41 -05:00
destfile_pfx="$(cat /dev/urandom | tr -cd 'a-f0-9' | head -c 32)" || true
2021-01-30 17:30:41 -05:00
while [ -d "/tmp/doasedit/$destfile_pfx" ]; do
destfile_pfx="$(cat /dev/urandom | tr -cd 'a-f0-9' | head -c 32)"
done
2021-02-03 17:07:23 -05:00
tempdir="/tmp/doasedit/$destfile_pfx"
# we don't want any other users to be able to read what we're doing, so -m700
mkdir -m700 -p $tempdir
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)
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
if doas cmp -s "$tempdir/file" "$srcfile"; then
2021-01-30 17:30:41 -05:00
echo "Skipping write; no changes."
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
exit 0
2021-01-30 17:30:41 -05:00
fi