#! /bin/sh
#
# bitscope-dso -- a startup script to get the mess clean.
#
# (C) 2006, jw@suse.de, 
# This script is under GPL V2
#
# This software expects the settings file in the same directory as the binary is.
# And it needs it writable. What a hack!
#
# We make a per-user copy in his home, and patch the open syscall, 
# so that BitScope.prb is always taken from his home.
#
# 
defsettings_dir=/usr/share/bitscope-dso
settings=BitScope.prb
dso_dir=$HOME/.bitscope
test -d $dso_dir || mkdir $dso_dir
test -f "$dso_dir/$settings" || cp "$defsettings_dir/$settings" "$dso_dir"
probe_dev=$1
test -z "$probe_dev" && probe_dev=$(grep '^USB:' "$dso_dir/$settings"  |tr -d \\r | head -1)
case "$probe_dev" in
   *USB*)
    a=$(dmesg | grep 'FTDI FT232BM Compatible converter now' | tail -1 | sed -e 's@.*: @@')
    echo $a
    case "$a" in
      *disconnected*)
      echo " USB link failure. Try to reconnect USB cable."
      echo " (If this fails, try: rmmod ftdi_sio usbserial; then reconnect ...)"
      exit
      ;;
    esac
    ;;
esac
probe_dev=$1
sett_probe_dev=$(grep '^USB:' "$dso_dir/$settings"  |tr -d \\r | head -1 | sed -e 's@^USB:@@')
case "$sett_probe_dev" in COM*) sett_probe_dev= ;; esac
test -z "$probe_dev" && probe_dev=$sett_probe_dev	# first fallback
test -z "$probe_dev" && probe_dev=/dev/ttyUSB0		# second fallback
if [ -e "$probe_dev" ]; then
  if [ -r "$probe_dev" ]; then
    echo "seen $probe_dev"
  else
    echo "$probe_dev seen, but is not readable. Try with sudo"
  fi

  if [ "x$sett_probe_dev" != "x$probe_dev" ]; then
    # comment out everything else and append what was probed.
    sed -i 's@^\([^#]\)@# \1@' $dso_dir/$settings
    echo >> $dso_dir/$settings "USB:$probe_dev"
  fi
else
  echo "Error: $probe_dev does not exist."
  echo "Attach device, change $dso_dir/$settings, or give devicename as parameter."
  echo "E.g.   $0 /dev/ttyUSB0"
  exit
fi
# preload does not work with group-sbit.
# env LD_PRELOAD=/usr/lib/bitscope-dso/dso_home_wrapper.so /usr/lib/bitscope-dso/Dso 
# found a different way to cheat:
perl -e "exec {'/usr/lib/bitscope-dso/Dso'} '$dso_dir/Dso'"
