#!/bin/bash

# default values
BTMAC="30:21:5C:30:F1:C4"
CDELAY=15
STIME=60

usage() {
  echo "Usage: $(basename $0) [ -m MAC ADDRESS ] [ -d CONNECT_DELAY ] [-t SCAN_TIME]" 1>&2
}

exit_abnormal() {
  usage
  exit 1
}

# test number is a positive integer, syntax: test_number value var_name
test_number() {
  re='^[0-9]+$'
  if ! [[ $1 =~ $re ]]
  then
    echo "Error: $2 is not an integer" >&2;
    exit_abnormal
  fi
  if [[ $1 == "0" ]]
  then
    echo "Error: $2 must be greater than 0" >&2;
    exit_abnormal
  fi
}

cline=$1

if [ "$cline" != "" ] && [ "${cline:0:1}" != "-" ]
then
  echo "Error: $1 is an invalid option"
  exit_abnormal
fi

while getopts ":m:d:t:h" options
do

  case "${options}" in

    m)
      BTMAC=${OPTARG}
      ;;

    d)
      CDELAY=${OPTARG}
      ;;

    t)
      STIME=${OPTARG}
      ;;

    h)
      usage
      exit 0
      ;;

    :)
      echo "Error: -${OPTARG} requires an argument."
      exit_abnormal
      ;;

    ?)
      echo "Error: -${OPTARG} is an unknown flag."
      exit_abnormal
      ;;

    *)
      exit_abnormal
      ;;
  esac
done

# test validity of parameters
test_number $CDELAY "CONNECT_DELAY"
test_number $STIME "SCAN_TIME"
if ! [[ $BTMAC =~ ^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$ ]]
then
  echo "Error: \"$BTMAC\" is not a valid MAC address."
  exit_abnormal
fi

# echo "OK:"
# echo " BTMAC:  $BTMAC"
# echo " CDELAY: $CDELAY"
# echo " STIME:  $STIME"

# check if the devide is paired
bluetoothctl info $BTMAC  >/dev/null
if [ $? -ne 0 ]
then
   # dev not paired, enable scanning for 60 seconds to pair 
   # but waiting only 15 seconds before trying to connect
   nohup bluetoothctl --timeout $STIME scan on>/dev/null &>/dev/null &
   sleep $CDELAY
fi
bluetoothctl connect $BTMAC >/dev/null
exit $?

nestor@domus:~ $ 
