doasedit/doasedit

49 lines
1.0 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"
mkdir -p $tempdir
trap "rm -rf $tempdir" EXIT
srcfile="$(doas realpath $1)"
2021-01-30 17:30:41 -05:00
if doas [ -f "$srcfile" ]; then
2021-02-03 17:07:23 -05:00
doas cp $srcfile $tempdir/edit
doas chown -R $USER:$USER $tempdir/edit
doas cp $srcfile $tempdir/file
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-02-03 17:07:23 -05:00
if 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