misc-scripts/doasedit

38 lines
1.0 KiB
Bash
Executable File

#!/bin/sh
set -f
ercho() { echo "$*" >&2 ; }
error() { ercho "$*" && exit 1 ; }
TMPDIR="${TMPDIR:-/tmp}"
ed="${VISUAL:-vi}"
clean() {
[ -f "$tmpfile" ] && rm -f "$tmpfile"
}
[ "$(whoami)" = "root" ] && error "Cannot be run as root!"
[ -z "$1" ] && error "No files provided!"
trap 'clean' 1 INT HUP KILL EXIT
for f; do
[ ! -f "$f" ] && ercho "File $f is not a regular file, is not accessible by the user, or does not exist. Skipping..." && continue
tmpfile="$(mktemp -t doasedit_XXXXXXXX)" || error "Cannot make temp file for $f! Exiting..."
cp -fp "$f" "$tmpfile" || error "Cannot copy file $f! Exiting..."
ercho "$ed '$f'"
$ed "$tmpfile" || error "Exit code != 0 by editor. Exiting..."
cmp "$f" "$tmpfile" >/dev/null 2>&1
ec=$?
if [ $ec -eq 1 ]; then
if [ ! -w "$f" ]; then doas mv -f "$tmpfile" "$f"; else mv -f "$tmpfile" "$f" && echo "$f didn't need root perms!"; fi
elif [ $ec -eq 0 ]; then
ercho "File not changed, skipping..."
else
ercho "Problem running diff on $f! Skipping..."
fi
rm -f "$tmpfile"
done