#!/system/xbin/bash
read -a cmd -s -r #read will notice the \r at eol and count it if testing with
		  #telnet(1), so please use nc(1).
function driver_die() {
    local x=$?
    echo "$@"
    if test -z "$x" -o "$x" = 0; then
	x=-1
    fi
    echo ret: $x
    exit "$x"
}

function die() {
    local x=$?
    echo "$@"
    if test -z "$x" -o "$x" = 0; then
	x=-1
    fi
    exit "$x"
}

function random() {
    awk '
BEGIN {
    srand();
    for (i = 0; i < '"${2-1}"'; i++) {
        printf("%d\n", int(rand() * '"${1-10}"'));
    }
}'

}

export -f random

function getprop() {
    test $# = 0 && die "Error: Usage: $(basename $0) PROP..."

    for x in "$@"; do
	command getprop "$x" | sed -e 's/.*: \[\(.*\)\]/\1/'
    done
}

export -f getprop

export -f die #for use in sub scripts
export PATH=$PATH:/data/vendor/bin


if test ${#cmd[@]} = 0; then
    driver_die 'You have not specified the command to execute!'
fi

if test -e /system/etc/tcmd/tcmd-init; then
    . /system/etc/tcmd/tcmd-init;
fi

cd /system/etc/tcmd || driver_die "system not correctly setup, can not cd to /system/etc/tcmd"

test -e ./"${cmd[0]}" || driver_die "command ./${cmd[0]} not found"
#       ^^note this, so that the client can not use an absolute path to create a
#       security hole.
debug=
if test -e /data/script-debugging; then
    debug=-x
fi

cmdname=${cmd[0]}
if [[ $cmdname =~ \.\. ]]; then
    driver_die "Security Error: can not exec $cmdname because it contains .."
fi

if test "$cmdname" = ${cmdname%-with-data}; then # no -with-data at the end
    bash $debug ./"${cmd[@]}" < /dev/null        # no need for more data
else
    bash $debug ./"${cmd[@]}"
fi
ret=$?
log -t tcmd "'${cmd[@]}'" return value is $ret
sync
echo ret: $ret
exit $ret
