Skip to content

Instantly share code, notes, and snippets.

@Ikke
Last active September 23, 2017 18:07
Show Gist options
  • Save Ikke/d9f084ec1212623d10db to your computer and use it in GitHub Desktop.
Save Ikke/d9f084ec1212623d10db to your computer and use it in GitHub Desktop.
#!/bin/bash
file=$1
# Ignore the command this script was run with to prevent infiniute recursion
editor=$(which -a $EDITOR | grep -v $0 | head -n1)
if test -z "$CURRENT_UID"; then
export CURRENT_UID=$UID
fi
sha1() {
printf $(sudo sha1sum "$1" | awk '{print $1}')
}
update_if_changed() {
new_hash=$(sha1 "$tmpfile")
if test "$file_hash" != "$new_hash"
then
cat "$tmpfile" >"$file"
file_hash=$new_hash
fi
}
file_exists() {
test -f $1
}
file_writable() {
test -w "$1"
}
dir_writable() {
tmpfile=$(dirname $1)/.is_writable
touch "$tmpfile" 2>/dev/null && rm "$tmpfile"
}
cleanup() {
sudo rm -f "$tmpfile"
! test -z $job && kill $job 2>/dev/null;
exit
}
if test -z "$file"; then
echo "Usage; $0 <filename>" && exit
fi
# If we have write access, no need to use sudo
if test $EUID -ne 0 && \
(file_writable "$file" || \
! file_exists "$file" && dir_writable "$file");
then
exec $editor "$file"
fi
# Gain root
if test $EUID -ne 0
then
exec sudo -E $0 "$@"
fi
trap "cleanup" SIGINT
dir=$(dirname $file)
filename=$(basename $file)
tmpfile=$(mktemp --tmpdir=$dir -t .${filename}.XXX)
touch "$tmpfile" # Make sure temp file exists
chown $CURRENT_UID "$tmpfile"
chmod 600 "$tmpfile"
file_hash=da39a3ee5e6b4b0d3255bfef95601890afd80709 #empty file
if test -f "$file"
then
file_hash=$(sha1 "$file")
cat "$file" >"$tmpfile"
fi
# Background listener to update the actual file while the editor is still running
(
while true
do
test ! -f "$tmpfile" && exit
inotifywait -e modify "$tmpfile" -qq 2>/dev/null \
&& update_if_changed
done
)&
job=$!
disown # No job control messages in this shell
# Time for real action. Run the editor as the user
sudo -E -u \#$CURRENT_UID $editor "$tmpfile"
cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment