#!/usr/bin/env bash

if ! read -t 0.001; then
	cat <<-EOF
WARNING! This test script will turn the bluetooth power and discoverability on
and off several times. While it will try to restore the original state at the
end of the test, it is recommended to have wired keyboard and pointing device at
hand. You can skip the confirmation by piping yes to the script.
	EOF
	read -p "Please type y or Y followed by [ENTER] to proceed: "
fi
[[ $REPLY =~ ^[Yy]$ ]] || exit 1

blueutil=./blueutil
errors=

status=$($blueutil)
trap "{
  $blueutil -p$($blueutil -p) -d$($blueutil -d)
  echo
  if [[ -n \$errors ]]; then
    echo -n \"\$errors\"
    exit 1
  fi
}" EXIT

ANSI_BOLD=$(tput bold 2> /dev/null)
ANSI_RED=$(tput setaf 1 2> /dev/null)
ANSI_GREEN=$(tput setaf 2 2> /dev/null)
ANSI_RESET=$(tput sgr0 2> /dev/null)

success() {
  printf "$ANSI_GREEN"."$ANSI_RESET"
}

failure() {
  printf "$ANSI_RED"F"$ANSI_RESET"
  errors+="$@"$'\n'
}

assert_eq() {
  [[ $1 == $2 ]] && success || failure "$ANSI_BOLD""$BASH_LINENO""$ANSI_RESET: Expected \"$1\" to eq \"$2\""
}

assert_match() {
  [[ $1 =~ $2 ]] && success || failure "$ANSI_BOLD""$BASH_LINENO""$ANSI_RESET: Expected \"$1\" to match \"$2\""
}

# Power
$blueutil -p1
assert_eq "$($blueutil)" *'Power: 1'*

$blueutil -p 0
assert_eq "$($blueutil)" *'Power: 0'*

$blueutil --power=1
assert_eq "$($blueutil)" *'Power: 1'*
assert_eq "$($blueutil -p)" '1'
assert_eq "$($blueutil --pow)" '1'
assert_eq "$($blueutil --power)" '1'

$blueutil --pow 0
assert_eq "$($blueutil)" *'Power: 0'*
assert_eq "$($blueutil -p)" '0'
assert_eq "$($blueutil --pow)" '0'
assert_eq "$($blueutil --power)" '0'

# Discoverable
$blueutil -d1
assert_eq "$($blueutil)" *'Discoverable: 1'*

$blueutil -d 0
assert_eq "$($blueutil)" *'Discoverable: 0'*

$blueutil --discoverable=1
assert_eq "$($blueutil)" *'Discoverable: 1'*
assert_eq "$($blueutil -d)" '1'
assert_eq "$($blueutil --discov)" '1'
assert_eq "$($blueutil --discoverable)" '1'

$blueutil --discov 0
assert_eq "$($blueutil)" *'Discoverable: 0'*
assert_eq "$($blueutil -d)" '0'
assert_eq "$($blueutil --discov)" '0'
assert_eq "$($blueutil --discoverable)" '0'

# Combined
$blueutil -p1 -d1
assert_eq "$($blueutil)" $'Power: 1\nDiscoverable: 1'

$blueutil -p0 -d1
assert_eq "$($blueutil)" $'Power: 0\nDiscoverable: 1'

$blueutil -pon -dOff
assert_eq "$($blueutil)" $'Power: 1\nDiscoverable: 0'

$blueutil -pOFF -doFF
assert_eq "$($blueutil)" $'Power: 0\nDiscoverable: 0'

# Help
assert_eq "$($blueutil --help)" *'this help'*
assert_eq "$($blueutil -h)"     *'this help'*

# Version
assert_match "$($blueutil --version)" '^[0-9]+\.[0-9]+\.[0-9]+$'
assert_match "$($blueutil -v)"        '^[0-9]+\.[0-9]+\.[0-9]+$'
