#!/bin/sh

module_id() {
    awk 'BEGIN { FS=": " } /Hardware/ { print $2 } ' </proc/cpuinfo
}

# Read the h2200 bluetooth radio version out of the asset data in flash.
h2200_radio_version() {
	dd if=/dev/mtdblock1 bs=1 skip=126968 count=5 | tr -d \\0
}

if [ -f /etc/sysconfig/bluetooth ]; then

  . /etc/sysconfig/bluetooth

  if [ $BLUETOOTH = "yes" ]; then
    # Turn echo off; if the bluetooth chip emits characters on power up,
    # they would be echoed back to the chip, confusing it. This should only
    # be necessary to do once, as hciattach turns echo off too (but too
    # late the first time, since the bluetooth chip is powered up when the
    # port is opened, before hciattach gets a chance to turn echo off).
    echo "Turning echo off on ${BLUETOOTH_PORT}"
    stty -echo < $BLUETOOTH_PORT
  fi

else
  echo -n "Checking for built-in Bluetooth: "
  case `module_id` in
    "HP iPAQ H2200")
	BLUETOOTH=yes
	PORT=/dev/tts/3
	SPEED=921600
	PROBE=no
	RADIO_VER=`h2200_radio_version`
	case $RADIO_VER in
	  "141")  # Zeevo
	  	echo "found Zeevo bluetooth chip"
	  	PROTO=any
		;;
	  "525")  # CSR
	  	echo "found CSR bluetooth chip"
	  	PROTO=bcsp
		;;
	  *)
	  	echo "Unknown radio version '${RADIO_VER}'"
		;;
	esac
	;;
    "HP iPAQ H5400")
	BLUETOOTH=yes
	PORT=/dev/tts/1
	SPEED=921600
        PROTO=any
	PROBE=yes
	;;
    "HP iPAQ H3900")
	BLUETOOTH=yes
	PORT=/dev/tts/1
	SPEED=921600
        PROTO=bcsp
	PROBE=yes
	;;
    "HP iPAQ H3800")
	BLUETOOTH=yes
	PORT=/dev/ttySB0
	SPEED=230400
        PROTO=bcsp
	PROBE=yes
	;;
    "HP iPAQ HX4700")
	BLUETOOTH=yes
	PORT=/dev/ttyS1
	SPEED=115200
	PROTO=texas
	PROBE=no
	;;
    "HP iPAQ H6300")
	BLUETOOTH=yes
	PORT=/dev/ttyS0
	SPEED=115200
	PROTO=texas
	PROBE=no
	;;
    *)
	BLUETOOTH=no
        ;;
  esac

  if [ $BLUETOOTH = "yes" ]; then
    stty -echo < $PORT
    if [ $PROBE = "yes" ]; then
      if ! blueprobe $PORT $SPEED; then
        BLUETOOTH=no
      fi
    fi
  fi

  echo $BLUETOOTH
  echo "BLUETOOTH=$BLUETOOTH" >/etc/sysconfig/bluetooth
  if [ $BLUETOOTH = "yes" ]; then
    echo "BLUETOOTH_PORT=$PORT" >>/etc/sysconfig/bluetooth
    echo "BLUETOOTH_SPEED=$SPEED" >>/etc/sysconfig/bluetooth
    echo "BLUETOOTH_PROTOCOL=$PROTO" >>/etc/sysconfig/bluetooth
  fi
fi
