#!/bin/bash
#
# Helper for the 'su -c' command
# (understands spaces in command parameters).

Usage() {
    cat <<EOF
Usage: $progname [-p] command-with-parameters
-p    Meant to be used by the Welcome app only.
EOF
    #echo "Usage: $progname [-p] command-with-parameters" >&2
}

DIE() {
    echo "$progname: Error: $1" >&2
    Usage
    exit 1
}

Main() {
    local progname="su-c_wrapper"
    local command=()
    local xx result=0
    local subresultfile="$(mktemp -u $HOME/$progname.$(date +%s%N).XXXXX)"
    local owner="$LOGNAME:users"
    local subresult=0
    local prompt="Root "

    while true ; do
        case "$1" in
            -p) prompt+="Password: " ; shift ;;
            "") DIE "command missing" ;;
            *) break ;;
        esac
    done

    # test -z "$1" && DIE "command missing"

    # command and parameters containing spaces: surround each with single quotes
    for xx in "$@" ; do
        command+=("'$xx'")
    done

    # run max 3 times
    for xx in {2..0} ; do
        printf "$prompt"
        LANG=C /usr/bin/su -c "${command[*]} ; echo $? > '$subresultfile' ; chown $owner '$subresultfile'"

        result=$?
        if [ -r "$subresultfile" ] ; then
            subresult="$(< "$subresultfile")"
            rm -f "$subresultfile"
        fi

        case "$result" in
            0)                       # OK
                break ;;
            127|126)                 # command is erroneous or can't be executed
                break ;;
            1)                       # wrong password or subcommand failure
                case $subresult in
                    0) ;;            # wrong password
                    *) break ;;      # subcommand failure
                esac
                ;;
            *) ;;                    # signal killed command
        esac
        if [ $xx -ne 0 ] ; then
            echo "Sorry, try again ($xx)." >&2
        else
            echo "Fail." >&2
        fi
    done
}

Main "$@"
