Skip to content

Instantly share code, notes, and snippets.

@Zenexer
Created February 7, 2018 22:24
Show Gist options
  • Save Zenexer/0125fa80113f0cf4cd3ae2078789e236 to your computer and use it in GitHub Desktop.
Save Zenexer/0125fa80113f0cf4cd3ae2078789e236 to your computer and use it in GitHub Desktop.
#!/bin/sh
set -e
backup() {
if exists "$1"; then
cp -dp "$1" "$2" || return $?
fi
return 0
}
exists() {
[ -e "$1" ] || return 1
}
force_symlink() {
if [ -e "$3" ] && ! unlink "$3"; then
echo "cannot create symlink $2 -> $1 (unlink)" >&2
exit 1
fi
if ! symlink "$1" "$3"; then
echo "cannot create symlink $2 -> $1 (symlink)" >&2
exit 1
fi
if ! rename "$3" "$2"; then
echo "cannot create symlink $2 -> $1 (rename)" >&2
exit 1
fi
return 0
}
symlink() {
ln -s "$1" "$2" || return $?
}
rename() {
mv -fT "$1" "$2" || return $?
}
reset_diversion() {
dpkg-divert --package bash --remove "$2" || return $?
dpkg-divert --package "$1" --divert "$3" --add "$2" || return $?
}
has_binsh_line() {
while read -r item; do
if [ "$item" = '/bin/sh' ]; then
return 0
fi
done
return 1
}
binsh_in_filelist() {
dpkg-query -L "$1" 2> /dev/null | has_binsh_line || return $?
}
undiverted() {
in="`dpkg-divert --listpackage "$1"`" || return $?
[ -z "$in" -o "$in" = 'bash' ] || return 1
}
access() {
# This isn't perfectly accurate, but it's sufficient for our purposes. The syscall is a little different.
[ -e "$1" ] || return 1
}
main() {
if access /bin/sh; then
backup /bin/sh /bin/sh.distrib || return $?
backup /usr/share/man/man1/sh.1.gz /usr/share/man/man1/sh.distrib.1.gz || return $?
force_symlink bash /bin/sh /bin/sh.temp || return $?
force_symlink bash.1.gz /usr/share/man/man1/sh.1.gz /usr/share/man/man1/sh.1.gz.temp || return $?
if ! binsh_in_filelist bash; then
return 0
fi
fi
if undiverted /bin/sh; then
reset_diversion dash /bin/sh /bin/sh.distrib || return $?
fi
if undiverted /usr/share/man/man1/sh.1.gz; then
reset_diversion dash /usr/share/man/man1/sh.1.gz || return $?
fi
return 0
}
main || exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment