#!/bin/sh
# devplace sudo superclone: sudo-compatible CLI, no privilege change.
# It never swaps user; it executes the command as the current user (pravda),
# so nothing a container does can ever create a root-owned file on the host.

_dp_usage() {
    cat <<'EOF'
usage: sudo -h | -K | -k | -V
usage: sudo -v [-ABkNnS] [-g group] [-h host] [-p prompt] [-u user]
usage: sudo -l [-ABkNnS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]
usage: sudo [-ABbEHnPS] [-C num] [-g group] [-h host] [-p prompt] [-R dir] [-T timeout] [-u user] [VAR=value] [-i | -s] [command [arg ...]]
EOF
}

_dp_login=0
_dp_shell=0

while [ $# -gt 0 ]; do
    case "$1" in
        --) shift; break ;;
        -V|--version) echo "Sudo version 1.9.15p5"; echo "Sudoers policy plugin version 1.9.15p5"; exit 0 ;;
        --help) _dp_usage; exit 0 ;;
        -K|-k|--remove-timestamp|--reset-timestamp) exit 0 ;;
        -v|--validate) exit 0 ;;
        -l|-ll|--list) echo "User $(id -un 2>/dev/null) may run any command"; exit 0 ;;
        -i|--login) _dp_login=1; shift ;;
        -s|--shell) _dp_shell=1; shift ;;
        --user=*|--group=*|--prompt=*|--chdir=*|--chroot=*|--host=*|--role=*|--type=*|--other-user=*|--command-timeout=*|--close-from=*|--preserve-env=*) shift ;;
        -A|--askpass|-b|--background|-B|--bell|-E|--preserve-env|-H|--set-home|-n|--non-interactive|-N|--no-update|-P|--preserve-groups|-S|--stdin) shift ;;
        -u|--user|-g|--group|-p|--prompt|-C|--close-from|-D|--chdir|-R|--chroot|-T|--command-timeout|-U|--other-user|-r|--role|-t|--type|-c|--class|-h|--host)
            if [ $# -ge 2 ]; then shift 2; else shift; fi ;;
        -*) shift ;;
        *) break ;;
    esac
done

_dp_env=""
while [ $# -gt 0 ]; do
    case "$1" in
        [A-Za-z_]*=*) _dp_env="$_dp_env $1"; shift ;;
        *) break ;;
    esac
done

SUDO_USER="$(id -un 2>/dev/null)"; export SUDO_USER
SUDO_UID="$(id -u 2>/dev/null)"; export SUDO_UID
SUDO_GID="$(id -g 2>/dev/null)"; export SUDO_GID
SUDO_COMMAND="$*"; export SUDO_COMMAND

if [ "$_dp_login" -eq 1 ] || [ "$_dp_shell" -eq 1 ]; then
    _dp_sh="${SHELL:-/bin/sh}"
    if [ $# -gt 0 ]; then
        [ -n "$_dp_env" ] && exec env $_dp_env "$_dp_sh" -c "$*"
        exec "$_dp_sh" -c "$*"
    fi
    [ -n "$_dp_env" ] && exec env $_dp_env "$_dp_sh"
    exec "$_dp_sh"
fi

if [ $# -eq 0 ]; then
    _dp_usage >&2
    exit 1
fi

[ -n "$_dp_env" ] && exec env $_dp_env "$@"
exec "$@"
