#!/system/xbin/bash

export on_android=false #not on android means we are on pc.
if which getprop >/dev/null 2>&1; then
    on_android=true
fi

function output() {
    echo "$@"
}

function green_output() {
    printf "%s" $'\033[32;1m'
    echo "$@"
    printf "%s" $'\033[0m'
}

function red_output() {
    printf "%s" $'\033[31;1m'
    echo "$@"
    printf "%s" $'\033[0m'
    sleep 1
}

function adb() {
    if test $on_android = true; then
	shift #get rid of the "shell" in adb shell xxx
	"$@" | tr -d '\r'
    else
	command adb "$@" | tr -d '\r'
    fi
}

function log() {
    true
}

function yes-or-no-p() {
    default=no
    prompt=(yes/No)
    if test "$1" = -y; then
	default=yes;
	prompt=(Yes/no)
	shift
    fi

    user_prompt=$(echo -n "$@")
    if test "${user_prompt:0-1}" != '?'; then
	user_prompt=${user_prompt}\?
    fi

    if ! tty >/dev/null 2>&1; then
	test $default = yes && return 0
	return 1
    fi

    log "$user_prompt $prompt: "
    read -p "$user_prompt $prompt: "

    if test -z "$REPLY" -a $default = yes; then
	return 0
    fi

    if echo $REPLY|grep '^yes$' -iq; then
	return 0
    fi
    return 1
}

pass_cases=()
fail_cases=()

for x in $(adb shell bash -c 'echo ls-cases  |busybox nc 127.0.0.1 54321 ' | grep autotest | sort | egrep -e "${1:-.}"); do
    output 
    output "****************************************************************"
    output
    output "Will start case $x"
    result=$(adb shell bash -c "echo $x start | busybox nc 127.0.0.1 54321")
    output "$result"
    output

    if echo "$result" | grep -q -e "^ret: 0$"; then
	green_output -n "OK. "
	output $x started successfully.
    else
	red_output -n "NO! "
	output $x start failed.
	adb shell bash -c "echo $x stop | busybox nc 127.0.0.1 54321" >/dev/null 2>&1
	output case $x stoped...
	output
	fail_cases=("${fail_cases[@]}" $x)
	continue
    fi
    ask_result=$(adb shell bash -c "echo ask-result $x | busybox nc 127.0.0.1 54321" | grep -v -e "^ret: ")
    if test -z "$ask_result"; then
	ask_result="Do you think $x is OK?"
    fi

    if yes-or-no-p -y "$ask_result"; then
	green_output -n "OK. " 
	output "Tester think case is successful."
	pass_cases=("${pass_cases[@]}" $x)
    else
	red_output -n "NO! "
	output "Tester think case is failed."
	fail_cases=("${fail_cases[@]}" $x)
    fi

    adb shell bash -c "echo $x stop | busybox nc 127.0.0.1 54321" >/dev/null 2>&1
    output case $x stoped...
    output
done

output "****************************************************************"
output
output Summary:
output
for x in "${pass_cases[@]}"; do 
    output -n "$x "
    green_output "passed"
done

for x in "${fail_cases[@]}"; do
    output -n "$x "
    red_output "failed"
done
