dotfiles

configuration files for shell, text editor, graphical environment, etc.
git clone git://src.adamsgaard.dk/dotfiles
Log | Files | Refs | README | LICENSE Back to index

commit 827e155d8ee2b4b93690f11ce255841562b23d18
parent caf3d4fea7353926bca61bbbacbc4b3d7f89186b
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date:   Tue, 18 Feb 2020 19:54:53 +0100

Add asuser command

Diffstat:
A.local/bin/asuser | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 108 insertions(+), 0 deletions(-)

diff --git a/.local/bin/asuser b/.local/bin/asuser @@ -0,0 +1,108 @@ +#!/bin/sh +set -e + +version=0.1.0 + +die() { + printf '%s\n' "$1" + exit 1 +} + +help() { + echo "usage: ${0##*/} [OPTIONS] USER CMD" + echo "run CMD as USER." + echo + echo "OPTIONS are one or more of the following:" + echo " -h show this message" + echo " -v show version and license information" + echo " -V show verbose information during execution" + echo " -t transfer any output files from CMD to current directory" + echo " -X run graphical command (limited performance, limited X access)" + echo " -Y run graphical command (native performance, full X access)" + echo " -- do not consider any following args as options" +} + +show_version() { + echo "${0##*/} version $version" + echo "Licensed under the ISC License" + echo "written by Anders Damsgaard, anders@adamsgaard.dk" + echo "https://src.adamsgaard.dk/dotfiles" +} + +if [ $# -lt 1 ]; then + die 'error: no USER specified' + exit 1 +fi + +verbose=0 +transfer=0 +ssh="" +while :; do + case "$1" in + -h) + help + exit 0 + ;; + -v) + show_version + exit 0 + ;; + -V) + verbose=1 + ;; + -t) + transfer=1 + ;; + -X) + ssh="-X" + ;; + -Y) + ssh="-Y" + ;; + --) + shift + break + ;; + -?*) + die 'error: unknown option specified' + ;; + *) + break; + esac + shift +done + +run_as_user() { + u="$1" + shift + orig="$PWD" + if [ "$transfer" = 1 ]; then + d="$(mktemp -d)" + mkdir -p "$d" + chmod 777 "$d" + cd "$d" + else + d="$orig" + fi + if [ "$verbose" = 1 ]; then + printf 'executing "%s" as %s in %s\n' "$*" "$u" "$d" + fi + if [ -n "$ssh" ]; then + ssh "$ssh" $u@localhost "$*" + else + doas -u "$u" sh -c "cd '$d' && \ + PATH=/home/'$u'/.local/bin:/home/'$u'/bin:\$PATH && \ + $*" + fi + if [ "$transfer" = 1 ]; then + if ls -lqA "$d" | grep -q .; then + if cp -prf "$d"/* "$orig"; then + rm -rf "$d" + else + die "could not transfer files from '$d' to '$orig'" + fi + fi + fi +} + +run_as_user "$@"