#!/bin/bash

PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin"
export PATH

TITLE="BLUETOOTH PIN"

umask 077

TMP="/tmp/btpin.$$"

PIN=""

X="$(/bin/ps --format args --no-headers -C X -C XFree86 -C Xorg 2>/dev/null)"

XAUTHORITY=""
DISPLAY=""

if [ -n "$X" ]; then
  DISPLAY=":0"
  authfile=""
  for i in $X; do
    [ -n "$authfile" ] && export XAUTHORITY="$i"
    case "$i" in :*) export DISPLAY="$i" ;; -auth) authfile="true"; continue ;; esac
    authfile=""
  done
fi

if [ -n "$DISPLAY" ]; then
DIALOG=Xdialog
else
DIALOG=dialog
exec >/dev/console </dev/console 2>&1
fi

rm -f "$TMP"

$DIALOG --title "$TITLE" --insecure --passwordbox "$TITLE" 8 35 2>"$TMP"

PIN="$(cat $TMP)"
rm -f "$TMP"

[ -n "$PIN" ] && echo "PIN:$PIN" || echo "ERR"
