#
# set -x
# C. Ostheimer and <dynamic>: 10-2008
# 081013 - asterisk 1.6.0.1 script 1.241, chan-capi-HEAD
#put user defined post install commands into file cfg.customize 
#maximal size of tar archive with asterisk config files
#which is written to /var/flash/cfg.configs
addon=asterisk16
app_ver=1.6.0.1
script_ver=1.241
cfg_common_req=2.352
max_conf_size=100000
ast_console_args="vvv"
addon_bin=asterisk

#server=http://192.168.222.10 #or =ftp://user17:secret@1.2.3.4
server=http://www.spblinux.de/fbox.new/0.9.29
#server=http://c2a2b2.com/fbox/0.9.29
# cfg.common and cfg.customize are downloaded from $server and
# firmware version specific files are downloaded from $server$svr26 
# ( kernel 2.6/uClibc-0.9.28 and 0.9.29 beta );
# default sub directories are /26, /26-ar7, /26-ur8.
# svr26=/26

##############################################################################
# Copyright (C) cfg_asterisk16,  C. Ostheimer and <dynamic>, licensed under
# GNU General Public License version 2 (GPL v2.0)
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details; spblinux.de/fbox.new/gpl-2.0.txt

replace_word()
# replace_word file_with_path old_word new_word [description]
{
   f_tmp=/var/tmp/`basename "$1"`_$PPID
   cp $1 $f_tmp 
   if cat $f_tmp |sed "s/$2/$3/" >$1; then
    rm $f_tmp
   else
    echo "Error: failed to write $3 ($4) into $1\n"
   fi
   unset f_tmp
}

usage()
{
 echo -e "usage:\n" \
	"*******************************************************************************\n" \
	"[INST_DIR=install_dir] ${0##*/} [-v] [-s alt_sever ] install|usb_install\n" \
	" install:     installs to ramdisk or to INST_DIR/addons if INST_DIR is given\n" \
	" usb_install: installs to ./addons of autodetected usb device\n" \
	" -v:          enables verbose mode for debugging purposes\n" \
	" -s [ftp://[id:secret@]my_ftp_server.com|http://my_http_server.com]\n" \
	"\n" \
	"${0##*/} [-v] remove\n" \
	"\n" \
	"${0##*/} [-v] disable | enable\n" \
	" disable:     Application is put to maintenance mode to prevent installing\n" \
	"              and starting of $addon\n" \
	" enable:      Application is put to normal operations mode again\n" \
	"\n" \
	"${0##*/} [-v|h]  start|stop [asterisk|zebedee]\n" \
	"\n" \
	"For RAM-Installations only:\n" \
	"${0##*/} [-v] [-f] config2flash|flash2config|clearflash [minor]\n" \
	" config2flash: save modified configuration files to non volatile (flash) memory\n" \
	" flash2config: restore configuration files from non volatile (flash) memory\n" \
	" clearflash:   clear $addon configuration files from flash memory\n" \
	" -f:           forced mode - never prompt and always assume \"y\"\n" \
	"\n" \
	" not available: ${0##*/} [-v] bluetooth [start [12345 [0000]]|stop]\n" \
	"*******************************************************************************\n"
 exit
}

usage_stop()
{
 echo -e "usage: ${0##*/} start|stop [asterisk|zebedee]\n" \
	"Terminate asterisk and/or zebedee (default: terminate both)"
 exit
}

usage_start()
{
  echo -e "usage:\n" \
	"${0##*/} [-v] start\n" \
	" (or directly via console: [TERM=xterm] asterisk [-vvv|-rvvv])\n" \
	"   r=attach console to running daemon;\n" \
	"   TERM=xterm asterisk -cvvv enables colored console output)\n" \
	"\n" \
	"${0##*/} [-v] start msn\n" \
	"  set external ISDN number (msn, e.g. 1122334) in capi.conf\n" \
	"  and in extensions.conf (sets global variable CAPI_CALLERID)\n" \
	"  and start asterisk (ONLY possible with unmodified configuration)\n" \
	"  (recommended: edit capi.conf, extensions.conf instead of using ${0##*/}\n" \
	"   /usr/lib/common/bin/e3c /etc/asterisk/capi.conf\n" \
	"\n" \
	"  The applicaton configuration files are stored in /etc/asterisk\n" \
	"  For RAM installations, you can use \"config2flash\" Option to make\n" \
	"  your configuration settings permament and available after reboot\n" \
	"  (run ${0##*/} without arguments to see usage information).\n" \
	"\n" \
	"To get usage information about ip tunnel zebedee type ${0##*/} start -z\n" \
	"\n" \
	"WARNING: check the configuration files in /etc/asterisk (capi.conf, extensions.conf...)\n" \
	"Do NOT continue if you do not have a knowledge about asterisk pbx.\n" \
	"(to stop asterisk at the console (*CLI>) type stop now)\n"
  exit
}
usage_start_zebedee()
{
  echo -e "usage:\n" \
	"${0##*/} [-v] start [asterisk] zebedee\n" \
	"  start (asterisk and) encrypted ip tunnel zebedee\n" \
	"  for iax2 connection to a second asterisk with zebedee\n" \
	"  (www.winton.org.uk/zebedee/)\n" \
	"\n" \
	"${0##*/} [-v] start [msn] asterisk [ip_asterisk2 [pw_ast2\n" \
	"               [zebedee zbd_ip zbd_port] [remote_user_nr]]]\n" \
	"  configure (asterisk and) zebedee and start (asterisk and) zebedee\n" \
	"  (ONLY possible with unmodified configuration)\n" \
	"  (recommended: edit extensions.conf, iax.conf instead of using ${0##*/})\n" \
	"\n" \
	"${0##*/} [-v] newkey\n" \
	"  For tunneling with zebedee you should create your own key\n" \
	"  by running ${0##*/} newkey; then you have to add the content of\n" \
	"  /etc/zebedee/client_fbox.id to your zebedee server id file.\n" 
  exit
}

# command line option parsing
unset verbose forced disable downloaded_latest version_status
[ $# -eq 0 ] && usage
while [ x$1 != x ]; do case $1 in
 -v) verbose=1;;
 -f) forced=1;;
 -s) echo $2 | grep -q -E "(http|ftp)://.*\..+" || (echo -e "\nParameter error: Wrong \"-s ...\" Option usage!" && usage )
     server="$2";shift;;
 -h | -\? | --help) 
  if [ "$2" = "start" ];then
   if [ "$3" = "zebedee" ];then
    usage_start_zebedee
   else
    usage_start
   fi
  else 
   if [ "$2" = "stop" ];then
    usage_stop
   else
    usage
   fi
  fi;;   
 -*) echo "warning: unknown option $1";;
 *) break
esac; shift; done

# Check version of cfg.common required for installation and download latest version if required
f=cfg.common
cfg_common_script=${0%cfg_*}$f
while true;do
 if [ -x $cfg_common_script ];then
  version_status="`$cfg_common_script cmp_version $cfg_common_req`"
  if [ "$verbose" ];then
   echo "INFORMATION: $version_status"
   echo "INFORMATION: $addon Version: $app_ver"
   echo "INFORMATION: Install-Script Version: $script_ver"
  fi
  if echo $version_status | grep -q "\-> OK";then
   break;
  else
   if ! [ $downloaded_latest ];then
    echo -e "Fatal Error: Cannot locate version v$cfg_common_req of $f file"
    exit 1 
   fi 
  fi 
 fi 
 cfg_common_script=/var/$f
 if ! wget $server/$f -O $cfg_common_script;then
  echo -e "Fatal Error: Couldn't download $f from $server"
  exit 1 
 fi 
 chmod +x $cfg_common_script
 downloaded_latest=1
done 

# Source common functions for installation from cfg.common
. $cfg_common_script

_fct cfgctl@${0##*/}:check:app_status

[ "$app_status" = "disabled" -a "$1" != "" ] && case $1 in
 stop|help|enable|remove|usb_remove);;
 *)
  echo "***************************************************************************" 
  echo "${0##*/} is currently in maintenance mode and will not allow"
  echo "any activities unless it is enabled via command line." 
  echo "Run: \"${0##*/} enable\", to activate normal operation mode again."
  echo "***************************************************************************" 
  exit
esac

modext=`_fct modext`
svrsub=`_fct svrsub`
export PATH=$PATH:/sbin:/usr/sbin

[ "$modext" = "o" ] && errorexit "Error: In this version of cfg_$addon only kernel 2.6 is supported." 
case $1 in
usb_install | install)
 is_addon_installed && errorexit "Error: $device installation of $addon detected.\nInstallation aborted. Run ${0##*/} [remove|usb_remove] first"
 free
 ### Set DEBUG to blank if not defined by external parameter
 DEBUG=${DEBUG-""}
 if [ "$INST_DIR" ];then 
  if [ -d "$INST_DIR" ]; then
   [ $1 = install ] && echo -n "defaulting to "
   echo "usb_install on $INST_DIR(="`get_inst_realdir_ $INST_DIR`") (given by variable INST_DIR)"
   echo "(if this is not correct run: unset INST_DIR)"
   device="USB"
   INST_DIR=$INST_DIR/addons
   [ -d $INST_DIR ] || mkdir $INST_DIR
   # check for user installation directory given in $INST_DIR
   _fct instdir@`get_inst_realdir_ $INST_DIR`:$addon:inst_dir:inst_fs_type
  else
   echo "WARNING:     INST_DIR(=$INST_DIR) defined, but not a directory"
   echo "             using default install to ramdisk"
   device="SQF"
   INST_DIR="/var"
   sleep 10
  fi
 else
  if [ "$1" = "usb_install" ];then
   device="USB"
   _fct instdir@/var/media/ftp:addons/$addon:inst_dir:inst_fs_type
   INST_DIR="$inst_dir/addons"
   [ -d $INST_DIR ] || mkdir $INST_DIR
  else
   device="SQF"
   INST_DIR="/var"
  fi 
  echo "INFORMATION: Installing $addon ($server$svrsub) to $INST_DIR ..."
 fi
 _fct mkdr@/var:log:run:spool:log/asterisk:spool/asterisk
 source_dir=$INST_DIR/$addon
 ############ CHECK WHETHER SOURCE FILES ARE ALREADY AVAILABLE ############
 if [ -f $source_dir/bin/$addon_bin ];then
  ############ SOURCE FILES ARE ALREADY AVAILABLE ############
  ############ USB-INSTALL, NO NEED TO EXTRACT FILES. ALREADY ON INST_DIR #####
  [ "$device" = "USB" ] && echo "INFORMATION: $addon already on USB-Device ... skipping extract phase."
 else 
  ############ SOURCE FILES NOT YET AVAILABLE      ############
  ############ COPY SQF-FILE TO RAMDISK AND MOUNT TO /var/$addon ###########
  [ -d /var/$addon ] || mkdir /var/$addon
  # get common install scripts / tools / modules from $server$svrsub
  _fct wgetx@$server$svrsub:$INST_DIR:freeramdisk:rd.$modext
  _fct wgetx@$server:$INST_DIR:cfg.customize
  chmod +x $INST_DIR/freeramdisk $INST_DIR/cfg.customize
  _fct rdsk@start
  _fct rdsk@new:ramdev
  # WORKAROUND FOR HANDLING COMPATIBILITY ISSUES WITH uClibc > 0.9.28
  # a) cp does not do proper dereferencing of symlinks when copying 
  #    -> use cp from customized busybox coming in $addon 
  # b) recursive mutex not properly supported for > 0.9.28 therefore no thread safety
  #    -> enforce use of old uClibc 0.9.28 via LD_LIBRARY_PATH
  if [ -f /lib/libuClibc-0.9.29.so ];then
   CP="/var/$addon/bin/cp"
  else
   CP="cp"
  fi 
  SQF_FILE=${addon}.sqf
  echo "$SQF_FILE -> $ramdev: "
  if [ -f $INST_DIR/$SQF-FILE ]; then
   cat $SQF_FILE > $ramdev
  else
   _fct wgetx@$server$svrsub:$ramdev:$SQF_FILE
  fi 
  mount $ramdev /var/$addon || _fct fallback@$SQF_FILE
  mount |grep -q "on /var/$addon" || errorexit "Error: failed to download and mount $addon (on /var/$addon)"
  if [ "$device" = "USB" ]; then 
   ############ USB-INSTALL, EXTRACT TO INST_DIR/$addon IF NOT EXTRACTED YET #######
   case $inst_fs_type in
    msdos | vfat | ntfs)
     cp_opts=""
     ;;
    *)
     cp_opts="-pd"
   esac
   echo "INFORMATION: Installing $addon on usb device (${inst_dir##*/})"
   file_path=`_fct path_abs@$0`
   if [ $file_path != $INST_DIR ];then
    # not called from $INST_DIR: install to $INST_DIR
    eval ${CP} $cp_opts $file_path/cfg.common $INST_DIR
    eval ${CP} $cp_opts $file_path/`basename $0` $INST_DIR
   fi
   echo "Start extracting files ... please wait!"
   eval ${CP} -R $cp_opts /var/$addon/* $INST_DIR/$addon
   umount /var/$addon
   _fct rdsk@free:$ramdev:$inst_dir/addons
   rm -r /var/$addon
   _fct lnsf@/var/log/$addon_bin:$source_dir/log/$addon_bin
   _fct lnsf@/var/spool/$addon_bin:$source_dir/spool/$addon_bin
   echo "COMPLETED:   $addon has been successfully installed to usb device ${inst_dir##*/}"
  fi 
 fi 
 ########### COMMON ROOT INSTALL ( SQF and USB ) ###########
 ########### OVERLAYING ROOT DIRECTORIES ###########
 echo "#####################################################################"
 echo "Performing root install ... This may take a couple minutes."
 echo "Aborting during this period will render your system inoperable!!!"
 echo "#####################################################################"
 _fct cfgctl@`basename $0`:disable:SILENT
 [ "$verbose" ] || echo -n "Installation progress: "
 ################# HANDLING OF /bin DIRECTORY ####################### 
 _fct ovrly@RO,$device:$DEBUG/bin:$source_dir/bin
 ################# HANDLING OF /etc DIRECTORY #######################  
 _fct ovrly@RO,$device:$DEBUG/etc:$source_dir/etc
 ################# HANDLING OF /usr DIRECTORY #######################  
 _fct ovrly@RO,$device:$DEBUG/usr:$source_dir/usr
  # Newer FW with ctlmgr does not support symlinks to /usr/www 
  [ -L /usr/www ] && rm /usr/www && mkdir /usr/www && _fct mntif@-o:bind:/var/_RO_/usr/www:/usr/www
 # igdd has relative symlink references to /var and requires /var to be bound to /var/_RO_/var
 _fct mntif@-o:bind:/var:/var/_RO_/var
 echo ""
 _fct cfgctl@`basename $0`:enable:SILENT
 ########### OVERLAYING ROOT DIRECTORIES FINISH ###########
 
 ########### APPLICATION SPECIFIC ACTIVITIES    ###########
 [ -f /bin/busybox.1.1.3 ] && _fct lnsf@/bin/top:/bin/chroot:busybox.1.1.3
 ########### APPLICATION INSTALLATION FINISHED  ########### 
 free
 echo "to use $addon type ./cfg_$addon start"
 if ! [ "$device" = "USB" ]; then
  [ "$0" != "./cfg_$addon" ] && echo "(or $0 start)"
 else
  echo "(or $inst_dir/addons/${0##*/} start)"
  echo
  echo "After a reboot you may reinstall $addon from usb with"
  echo "$inst_dir/addons/${0##*/} usb_install"
 fi
 # check for existence of "cfg.customize" to perform user specific cfg_xyz customizations
 for d in /var $INST_DIR;do
  if [ -f $d/cfg.customize -a -x $d/cfg.customize ];then
   [ "$verbose" ] && echo "Found addons customization script cfg.customize in $d. Will check & run customizations for $addon now."
   $d/cfg.customize allow `basename $0`
   break
  fi
 done  
 ;;
usb_remove | remove)
 if is_addon_installed;then
  if [ "$forced" ];then
   echo "Forced uninstall requested ... trying!"
   for mount_point in /var/_RO_/var /bin /lib /etc /usr/www /usr /dev/pts;do
    mount |grep -q " on $mount_point" && umount $mount_point
   done
   if [ $device = "SQF" ];then
    _fct rdsk@get_device:ramdev:/var/$addon || unset ramdev
    umount /var/$addon
    [ "$ramdev" ] && _fct rdsk@free:$ramdev
    _fct rdsk@stop
   fi
   cd /
   umount /var/_RO_
   rm -rf /var/lib/asterisk /var/log/asterisk /var/spool/asterisk
   echo "Leaving contents of \"/var/_RW_\" as is. rm -rf as needed." 
  else 
   free
   $0 -q stop ask || exit
   echo "*************************************************************************"
   echo "Due to $addon installation being mapped to \"/\" ( root directories ) a removal"
   echo "requires a System Reboot for clean completion of the de-installation."
   _fct cfgctl@`basename $0`:disable
   echo "A potential automatic re-installation of $addon after reboot was disabled."
   echo "Reboot your system now via \"reboot\" to complete the de-installation of $addon"
   [ "$device" = "USB" ] && echo "Your $addon files that were stored on your usb will not be deleted."
   echo "*************************************************************************"
   free
   exit
  fi 
 else
  [ "$verbose" ] && echo "addon $addon is not installed (has already been removed?)"
  free
 fi
 ;;
start)
 is_addon_installed || errorexit "Error: executable /bin/$addon_bin not found. You need to run first\n \"${0##*/} usb_install | install\""
 for running in asterisk none; do
   ps |grep -v grep |grep -q " $running" && break 
 done
 unset ast_opt ast_run ast_msn ast2_ip ast2_pw ast2_nr zbd_run zbd_ip zbd_port
 for x in $@ none; do
  case $x in
   start | asterisk | zebedee) y=$x; continue;;
  esac
  case $y in
   start) 
    case $x in
     none)ast_run=1;;
     c|d|r)ast_run=1;;
     [0-9]*[0-9])ast_msn=$x;;
     *)echo "warning: unknown option: $x"
    esac
    case $x in
     c|r)ast_opt="-${x}${ast_console_args#-}";;
    esac
    ;;
   asterisk) 
    ast_run=1
    case $x in
     none|d);;
     c|r)ast_opt="-${x}${ast_console_args#-}";;
     *)
      if [ -z "$ast2_ip" ]; then ast2_ip=$x
      elif [ -z "$ast2_pw" ]; then ast2_pw=$x
      else ast2_nr=$x; fi
    esac
    ;;
   zebedee)
    zbd_run=1
    case $x in
     none);;
     *)
      if [ -z "$zbd_ip" ]; then zbd_ip=$x
      elif [ -z "$zbd_port" ]; then zbd_port=$x
      else ast2_nr=$x; fi
    esac
    ;;
  esac
 done
# echo "ast_opt=$ast_opt ast_run=$ast_run ast_msn=$ast_msn ast2_ip=$ast2_ip ast2_pw=$ast2_pw ast2_nr=$ast2_nr zbd_run=$zbd_run zbd_ip=$zbd_ip zbd_port=$zbd_port"
 if [ "$zbd_run" ]; then # do not start a second instance of zebedee
   if ps |grep -v grep |grep -q " zebedee"; then
    echo "Warning: zebedee is already running (no automatic restart)"
    unset zbd_run
    if [ "$zbd_ip" -o "$zbd_port" ]; then
     echo "cannot set zebedee ip address and port (ignoring; use ${0##*/} stop zebedee)"
     unset zbd_ip zbd_port
    fi
   fi
 fi
 if [ $running = asterisk -a "$ast_run" ]; then # connect to remote asterisk or warning
  case x$ast_opt in
    x)
     echo "asterisk is already running (to open a console use: ${0##*/} start r)"
     unset ast_run
     ;;
    -c*)
     echo "asterisk is already running, connecting to remote asterisk"
     ast_opts="-r${ast_console_args#-}"
  esac
 fi
 [ $running = asterisk ] && if [ "$ast_msn" -o "$ast2_ip" -o "$ast2_pw" -o "$ast2_nr" ]; then
  case x$ast_opt in
    x-r*|x)
     echo "Error: asterisk is running, cannot set configuration (use ${0##*/} stop)"
     echo "($@)"
     exit 1
  esac
 fi
   d=$app_path/etc
   if [ "$ast_msn" ]; then
    replace_word $d/asterisk/capi.conf \
          	"1234567" "$ast_msn" "msn on external isdn S0 bus"
    replace_word $d/asterisk/extensions.conf \
          	"CAPI_CALLERID=1234567" "CAPI_CALLERID=$ast_msn" "msn on external isdn S0 bus"
   fi
   [ "$ast2_ip" ] && replace_word $d/asterisk/extensions.conf \
          	"192.168.123.123" "$ast2_ip" "address ip_asterisk2"
   [ "$ast2_pw" ] && replace_word $d/asterisk/iax.conf \
          	"geheim" "$ast2_pw" "password of users asterisk2/asterisk2fbox"
    [ "$zbd_ip" ] && replace_word $d/zebedee/zbd.conf \
          	"11.22.33.44" "$zbd_ip" "address of remote zebedee server"
    [ "$zbd_port" ] && replace_word $d/zebedee/zbd.conf \
          	"14569" "$zbd_port" "port of remote zebedee server"
   if [ "$ast2_nr" ]; then
    replace_word $d/asterisk/iax.conf \
          	"asterisk2" "asterisk$ast2_nr" "nr of remote asterisk server+users"
    replace_word $d/asterisk/extensions.conf \
          	"asterisk2" "asterisk$ast2_nr" "nr of remote asterisk server+users"
   fi
 [ "$TERM" ] || export TERM=xterm
 [ "$ast_args" ] && ast_args="${ast_args}${ast_console_args}"

 if [ "$zbd_run" ]; then
   [ -x $app_path/bin/zebedee ] || errorexit "Error: zebedee not found."
   if ps |grep -v grep |grep -q " zebedee"; then
    echo "warning: zebedee is already running (no automatic restart)"
   else
    zebedee -f /etc/zebedee/zbd.conf
   fi
 fi
 if [ "$ast_run" ]; then # (check, that asterisk is not running, already done) 
  if [ $device = "USB" ] && ! [ -f /var/lib/asterisk/astdb ]; then
   # restore astdb from usb device UNUSED??
   f=$source_dir/var/lib/asterisk/astdb
   [ -f $f ] && cp $f /var/lib/asterisk
  fi
  asterisk $ast_opt
  case x$ast_opt in
    x|x-d*)
     echo "asterisk daemon has been started (to open a console use: ${0##*/} start r)"
  esac
 fi
 ;;
stop)
 is_addon_installed || errorexit "Error: executable /bin/asterisk not found. You need to run \"${0##*/} usb_install | install\" first"
 unset do_ask
 [ "x$2" = "xask" ] && do_ask=1 && shift
 f1=asterisk
 f2=zebedee
 f3=sdpd
 f4=hcid
 [ -z "$3" -a "$2" = "asterisk" ] && unset f2
 [ -z "$3" -a "$2" = "zebedee" ] && unset f1
  for x in TERM KILL result; do
   unset is_running
   for f in $f1 $f2 $f3 $f4; do
    [ "$f" ] || continue 
    if ps |grep -v grep |grep -v ${0##*/} |grep -q "$f[ :]"; then
     case $x in
      result)
       errorexit "Error: cannot terminate process $f"
       ;;
      *)
       is_running=1
       key=y
       if [ "$do_ask" ]; then
        echo "$addon is running; do you want to terminate process $f (Y/n)"
read key
[ "n" = "$key" ] && errorexit "script terminated by user"
echo "(to reset a terminal use command: stty sane)"
       fi
       if [ $x = TERM -a $f = asterisk ]; then
        asterisk -rx "stop now"
       else
        killall -$x $f
       fi
       sleep 2
     esac
    fi
   done
   [ "$is_running" ] || break
  done
  if [ $device = "USB" ]; then
   # save astdb on usb device
   d=$source_dir/var/lib/asterisk
   f=/var/lib/${addon}/astdb
   [ -d $d ] || mkdir $d
   [ -f $f ] && cp $f $d
   # save bluetooth pairing information on usb device
   d=$source_dir/var/lib/bluetooth
   f="/var/lib/bluetooth/*"
   [ -d $d ] || mkdir $d
   for ff in $f; do [ -d $ff -o -f $ff ] && cp -r $ff $d; done
  fi
  [ "$verbose" ] && echo "run ${0##*/} remove to free memory by removing addon $addon from the system"
 ;;
newkey)
 if [ -x /bin/zebedee ]; then
  zebedee -p >/var/tmp/zebedee/client_fbox.key
  zebedee -P -f /etc/zebedee/client_fbox.key \
     |sed "s/(none)/(fbox)/">/var/tmp/zebedee/client_fbox.id
  echo "add the new public key (/var/tmp/zebedee/client_fbox.id)"
  cat /var/tmp/zebedee/client_fbox.id
  echo "to your zebedee server id file and restart zebedee server"
 else
  echo "Error: executable /bin/zebedee not found (try to run ${0##*/} usb_install | install)"
 fi
 ;;

disable | enable )
 if [ "$1" = "disable" ];then
  _fct cfgctl@`basename $0`:disable
 else
  _fct cfgctl@`basename $0`:enable
 fi 
 ;;   

config2flash)
 conf_in_flash_ $1 ${2-"101"} /etc/asterisk /etc/zebedee /etc/bluetooth /usr/lib/bluetooth
 ;;
flash2config|clearflash) 
 conf_in_flash_ $1 ${2-"101"}
 ;;
 
bluetooth)
 errorexit "bluetooth not available in this version."
 [ "$modext" = "o" ] && errorexit "Error: bluetooth only available with kernel 2.6" 
 case $2 in
  start)
   #enable kernel messages for debugging (takeover_printk=0)
   if [ "" ]; then # disabled because reloading ubik2 breaks isdn
   echo -n "enabling kernel messages (dmesg)... "
   killall telefon
   rmmod isdn_fbox_fon4
   sleep 2
   rmmod ubik2
   modprobe ubik2 takeover_printk=0
   modprobe isdn_fbox
   sleep 2
   telefon a127.0.0.1
   echo "done."
   fi
   # end: enable kernel messages
   [ -d $addon/modules ] || errorexit "Error: $addon not installed; run ${0##*/} install"
   for m in bluetooth hci_usb l2cap rfcomm sco; do
    [ -f $addon/modules/$m.$modext ] || errorexit "Error: module $m.$modext not found"
    lsmod |grep -q "^$m " || insmod $addon/modules/$m.$modext
   done
   D=tmp/bluetooth
   [ -d $D ] || mkdir $D
   if [ "$3" ]; then
    echo "$3" |sed "s/[0-9]*/x/" |grep -qv "^x$" && errorexit "Error: invalid pin: $3; (only numbers allowed)" 
    [ -f $D/pin ] && cat $D/pin |grep -qv "$3" && echo "warning: overwriting existing asterisk pin"
    pin_own=$3
    if [ "$4" ]; then
     echo "$4" |sed "s/[0-9]*/x/" |grep -qv "^x$" && errorexit "Error: invalid pin: $4; (only numbers allowed)" 
     [ -f $D/givepin ] && cat $D/givepin |grep -qv "PIN:$4" && echo "warning: overwriting existing headset pin"
     pin_given=$4
    elif [ -f $D/givepin ] &&  cat $D/givepin |grep -qv "0000"; then
     pin_given=`cat $D/givepin |grep "PIN:" |sed "s/ *echo *PIN:\([^ ]*\) */\1/"`
    fi
   elif [ -f $D/pin ] &&  cat $D/pin |grep -qv "12345"; then
    pin_own=`cat $D/pin`
    if [ -f $D/givepin ] &&  cat $D/givepin |grep -qv "0000"; then
     pin_given=`cat $D/givepin |grep "PIN:" |sed "s/ *echo *PIN:\([^ ]*\) */\1/"`
    fi
   fi
   [ -z "$pin_own" ] && pin=12345 && echo -n "warning: using default asterik pin: 12345; "
   [ -z "$pin_given" ] && pin=0000 && echo -n "using default headset pin: 0000."
   echo
   echo $pin_own >$D/pin
   cat $addon/etc/bluetooth/givepin.default |sed "s/\( *echo *PIN:\).*/\1$pin_given/" >$D/givepin
   chmod +x $D/givepin
   for x in sdpd hcid; do
    ps |grep -v "grep" |grep -q " $x[ /:]" && killall $x
   done  
   ./$addon hcid >/dev/null 2>&1
   ./$addon sdpd
   echo "to pair your bluetooth devices with asterisk read and edit /etc/asterisk/cellphone.conf"
   echo "(e.g. use editor e3c: /bin/e3c /etc/asterisk/cellphone.conf)"
  ;;
  stop)
   for x in sdpd hcid; do
    ps |grep -v "grep" |grep -q " $x[ /:]" && killall $x
   done  
  ;;
  *)
  echo "usage: ${0##*/} bluetooth  [start [asterisk_pin [headset_pin]]|stop]"
 esac
 ;;
*)
 usage
esac
