#!/bin/sh
#set -x
# C. Ostheimer 05-2006, 10-2006, 12-2006; usb_install framework by dynamic
# template cfg script
addon=nfsclient
addon_bin=mount
[ "$addon_bin" ] || addon_bin=$addon
#put used defined post install commands into file cfg.customize

#server=http://192.168.222.10
server=http://www.spblinux.de/fbox
# cfg.common and cfg.customize are downloaded from $server and
# firmware version specific files are downloaded from $server$svr24 (or $svr26)
# (kernel 2.4/uClibc-0.9.26 or kernel 2.6/uClibc-0.9.28);
# default sub directories are /24[.zlib|.zlib16] and /26.
# svr24=/24
# svr26=/26

# command line option parsing
unset verbose quiet show_usage
[ $# -eq 0 ] && show_usage=1
while [ x$1 != x ]; do case $1 in
 -z) [ "$svr24" ] || svr24=24.zlib;;
 -Z) [ "$svr24" ] || svr24=24.zlib16;;
 -v) verbose=1;;
 -q) quiet=1;;
 -h | -\? | --help) show_usage=1;;
 -*) echo "warning: unknown option $1";;
 *) break
esac; shift; done

# Source common functions for installation, (download if missing)
f=cfg.common
if [ -f ${0%cfg_*}$f ]; then 
 . ${0%cfg_*}$f
else
 wget $server/$f -O /var/$f || errorexit " Couldn't download $f from $server"
 . /var/$f
fi
modext=`_fct modext`
svrsub=`_fct svrsub`
export PATH=$PATH:/sbin:/usr/sbin:/var/$addon/bin


usage()
{
 echo -e "usage:\n" \
	 " [INST_DIR=installation_directory] ${0##*/} [-v] install\n" \
         "   (installs to ramdisk or to INST_DIR/addons if INST_DIR is given)\n" \
	 " ${0##*/} [-v]  usb_install | remove\n" \
         "   (usb_install: installs to /addons of autodetected usb device or to INST_DIR)\n" \
	 " ${0##*/} [-v] start nfs_share [mountpoint] | [-v] stop  [mountpoint]\n" \
	 " (default mountpoint is /var/mnt)"
 exit
}
usage_start()
{
 errorexit "usage: ${0##*/} start nfs_share [mountpoint]\n" \
           "(default mountpoint /var/mnt; e.g. ${0##*/} start 192.168.222.10:/mnt/fbox /var/mnt2)"
}

is_addon_installed()
{
 unset msg
 if mount |grep -q "on /var/$addon"; then
  msg="$addon is still mounted to /var/$addon"
 elif [ -L /var/$addon/bin/$addon_bin -a -x /var/$addon/bin/$addon_bin ]; then
  msg="(usb_install: `ls -l /var/${addon}_usb |sed 's/^[^\/]*//'`)"
 fi
 if [ x$1 != x-q -a "$msg" ]; then
  echo "$addon is still installed. Installation aborted. Run ${0##*/} [remove|usb_remove] first"
  errorexit "$msg" 
 fi
 #create return value
 [ "$msg" ]
}

#echo TEST
#echo "modext $modext, svrsub $svrsub."
#get_inst_realdir_ $INST_DIR
#get_inst_realdir_
#get_missing_file_ chroot
#_fct rdsk@new:ramdev && echo "--$ramdev--"
#echo END_TEST

[ "$show_usage" ] && usage
cd /var
case $1 in
usb_install | install)
 is_addon_installed
 unset is_usb
 [ $1 = usb_install ] && is_usb=1
 free
 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)"
   is_usb=1
  else
   echo "warning: INST_DIR(=$INST_DIR) defined, but not a directory"
   echo "         using default install to ramdisk (press ctrl+c to stop)"
   sleep 10
  fi
 else
  echo "installing $addon ($server$svrsub) ..."
 fi
 [ -d $addon ] || mkdir $addon
 if [ "$is_usb" ]; then 
 ############ USB-INSTALL ####################################
  # check for user defined installation directory given in $INST_DIR
  if [ "$INST_DIR" ]; then
   _fct instdir@`get_inst_realdir_ $INST_DIR`:addons/$addon:inst_dir:inst_fs_type
  else
   _fct instdir@/var/media/ftp:addons/$addon:inst_dir:inst_fs_type
  fi
  case $inst_fs_type in
   msdos | vfat | ntfs)
    cp_opts=""
    ;;
   *)
    cp_opts="-pd"
  esac
  ############ USB-INSTALL, EXTRACT TO USB IF NOT EXTRACTED YET #######
  if ! [ -f $inst_dir/addons/$addon/bin/$addon ]; then
   echo "installing $addon on usb device (${inst_dir##*/})"
   # get $addon specific squashfs-archives from $server$svrsub
   _fct wgetx@$server$svrsub:$inst_dir/addons/$addon:$addon.sqf
   # get common install scripts / tools / modules from $server$svrsub
   file_path=`_fct path_abs@$0`
   if [ $file_path != $inst_dir/addons ];then
    # not called from $inst_dir/addons: install on $inst_dir/addons
    cp $cp_opts $file_path/cfg.common $inst_dir/addons
    cp $cp_opts $file_path/${0##*/} $inst_dir/addons
   fi
   _fct wgetx@$server$svrsub:$inst_dir/addons:freeramdisk:rd.$modext
   _fct wgetx@$server:$inst_dir/addons:cfg.customize
   chmod +x $inst_dir/addons/${0##*/} $inst_dir/addons/cfg.customize $inst_dir/addons/freeramdisk
   [ -d $addon.tmp ] || mkdir $addon.tmp
   mount |grep -q "on /var/$addon.tmp" && umount $addon.tmp
   if mount |grep -q "on /var/$addon.tmp"; then
    errorexit "error: /var/$addon.tmp already mounted; failed to unmount /var/$addon.tmp"
   else
    _fct rdsk@start:$inst_dir/addons
    # get free ramdisk and store device_name_and_path in variable ramdev
    _fct rdsk@new:ramdev:$inst_dir/addons
    echo -n "$addon.sqf -> $ramdev: "
    cat $inst_dir/addons/$addon/${addon}.sqf >$ramdev
    [ $? -eq 0 ] && mount $ramdev $addon.tmp || _fct fallback@$inst_dir/addons/$addon/$addon.sqf
   fi
   if mount |grep -q "on /var/$addon.tmp"; then
    echo "Start extracting files ... please wait!"
    fr=/var/$addon.tmp
    to=$inst_dir/addons/$addon
    _fct cprs@$cp_opts:$fr:$to:bin:lib:usr:dev:sys:proc
    _fct mkdr@$to:bin:lib:usr/bin
    _fct cpnL@$cp_opts:$fr/bin:$to/bin
    _fct cpnL@$cp_opts:$fr/lib:$to/lib
    _fct cprs@$cp_opts:$fr/usr:$to/usr:bin
    _fct cpnL@-R${cp_opts#-}:$fr/usr/bin:$to/usr/bin
    umount /var/$addon.tmp
    _fct rdsk@free:$ramdev:$inst_dir/addons
    rm -r $addon.tmp
    echo "$addon has been successfully installed to usb device ${inst_dir##*/}"
   else
    errorexit "error: failed to download and mount $addon (on /var/$addon.tmp)"
   fi
  else  
   ############ USB-INSTALL, NO NEED TO EXTRACT FILES. ALREADY ON USB #####
   echo "$addon already on USB-Device ... skipping extract phase."
  fi 
  ########### CONTINUE USB-INSTALL AFTER REQUIRED FILES CONFIRMED ON USB-PATH ###########
  file_path=`_fct path_abs@$0`
  if [ $file_path = $inst_dir/addons ]; then
   # called from $inst_dir/addons: create copy in /var
   cp $cp_opts $inst_dir/addons/cfg.common /var
   cp $cp_opts $inst_dir/addons/${0##*/} /var
  fi
  [ -L ${addon}_usb ] || _fct lnsf@${addon}_usb:$inst_dir/addons/$addon
  # create links in /var/$addon pointing to usb device
  _fct lndfe@/var/$addon:/var/${addon}_usb:bin:lib:usr:proc:sys:dev
  _fct mkdr@/var/$addon:bin:lib:usr/bin:proc:sys:dev
  _fct lndfe@/var/$addon/lib:/var/${addon}_usb/lib
  _fct lndfe@/var/$addon/bin:/var/${addon}_usb/bin
  _fct lndfe@/var/$addon/usr:/var/${addon}_usb/usr:bin
  _fct lndfe@/var/$addon/usr/bin:/var/${addon}_usb/usr/bin
  # additional symlinks inside /var/$addon
  d=/var/$addon/bin
  _fct lnsf2@$d:statd:portmap
  if [ $modext = ko ]; then
   _fct lnsf2@$d:chroot:umount:df:mount
   d=/var/$addon/usr/bin
   _fct lnsf2@$d:chroot:umount:df:mount
  else
   _fct lnsf2@$d:chroot:umount:mount
   d=/var/$addon/usr/bin
   _fct lnsf2@$d:chroot:umount:mount
   d=/var/$addon/lib
   _fct lnsf2@$d:libc.so:libc.so.0:libuClibc-0.9.26.so
  fi
  cd /var
 else 
  ########### RAM-INSTALL #############################################
  _fct wgetx@$server$svrsub:/var:freeramdisk:rd.$modext
  _fct wgetx@$server:/var:cfg.customize
  chmod +x freeramdisk cfg.customize
  _fct rdsk@start
  _fct rdsk@new:ramdev
  echo -n "$addon.sqf -> $ramdev: "
  if [ -f $addon.sqf ]; then
   cat $addon.sqf > $ramdev
  else
   _fct wgetx@$server$svrsub:$ramdev:$addon.sqf
  fi 
  mount $ramdev $addon || _fct fallback@$addon.sqf
  # Remove symlinks which might be left over from last usb_install
  for f in /var/${addon}_usb ; do
   [ -L $f ] && rm $f
  done
 fi
 ########### COMMON-INSTALL (RAM and USB) #############################
 _fct mkdr@/var:mnt:lib/nfs/sm
 free
 echo "to use $addon type ./cfg_$addon start"
 if ! [ "$is_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/addons;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 ${0##*/}
   break
  fi
 done  
 ;;
usb_remove | remove)
 unset is_usb
 [ $1 = usb_remove ] && is_usb=1
 inst_dir=`get_inst_realdir_`
 [ "$inst_dir" ] && is_usb=1 && echo -e "default set to usb_remove\n(if this is not correct run: rm /var/${addon}_usb )\n"
 if ! is_addon_installed -q; then
  [ "$quiet" ] || echo "addon $addon is not installed (has already been removed?)"
 else
  free
  echo "removing $addon ..."
  $0 -q stop ask || exit
  sleep 1
  if ! [ "$is_usb" ]; then
   _fct rdsk@get_device:ramdev:/var/$addon || unset ramdev
   umount /var/$addon
   [ "$ramdev" ] && _fct rdsk@free:$ramdev
   _fct rdsk@stop
  fi
  if ! mount |grep -q "on /var/$addon"; then
   f=$addon.sqf
   [ -f $f ] && rm $f
   if [ "$is_usb" ]; then
     [ -d $addon ] && rm -r $addon
     [ -L  ${addon_usb} ] && rm ${addon}_usb
   else
#   [ -d $addon ] && rmdir $addon # labor firmware 4883 busybox comes without rmdir
    if [ -d $addon ]; then for x in $addon/*; do [ -r $x ]; break; rm -r $addon; done; fi
   fi
   [ -d lib/nfs ] && rm -r lib/nfs
   echo -n "done - (addon $addon has been removed"
   if [ "$is_usb" ]; then echo " from ram, not from usb)"; else echo ")"; fi
  fi
  free
 fi
 ;;
start)
 if ! [ -x $addon/bin/$addon_bin ]; then
  errorexit "error: executable /var/$addon/bin/$addon_bin not found (try to run ${0##*/} install)"
 fi
 export PATH=$PATH:/sbin:/usr/sbin:/var/$addon/bin
 export LD_LIBRARY_PATH=/var/$addon/lib
 [ "$2" ] || usage_start
 ping -c 1 ${2%%:*} || errorexit "error: no connection to nfs share $2"
 mntdir=/var/mnt
 [ "$3" ] && mntdir=$3
 if ! [ -d $mntdir ]; then mkdir $mntdir || errorexit "error:cannot create mountpoint $mntdir"; fi
 for m in sunrpc lockd nfs; do
  lsmod |grep -q "^$m " || insmod /var/$addon/modules/$m.$modext
 done
 for f in portmap statd; do
  ps |grep -v grep |grep -q "[ /]$f.bin *$" || /var/$addon/bin/$f.bin
 done
 if mount |grep -q "$2 on "; then
  echo "information: $2 is already mounted on "`mount |grep "$2 on " |sed "s@^.* on \([^ ]*\).*@\1@"`
  echo "(to umount nfs mounts use: ${0##*/} stop mountpoint)"
 else
  if ! /var/$addon/usr/bin/mount $2 $mntdir; then
   echo "error: failed to connect: mount $2 $mntdir" 
   echo
   echo "Did you start nfs-server with the given share ($2=?"
   echo "(e.g. mount 192.168.222.10:/mnt/fbox /var/mnt)"
  fi
 fi
 df
 ;;
stop)
 unset do_ask
 [ "x$2" = "xask" -o "x$3" = "xask" ] && do_ask=1
 export PATH=$PATH:/sbin:/usr/sbin:/var/$addon/bin
 export LD_LIBRARY_PATH=/var/$addon/lib
 mntdir=/var/mnt
 if [ "$2" ] && [ "ask" != "$2" ]; then
  echo "$2" |grep -q "\.\." && errorexit "error: path with '..' not allowed ($2)"
  # make absolute path
  if [ "${2#/}" = "$2" ]; then mntdir=$PWD/${2#./}; else mntdir=$2; fi
 fi
 unset is_mounted
 mount |grep -q " type nfs " && is_mounted=1
 if [ "$is_mounted" ]; then
  if ! mount |grep -q "on $mntdir type nfs"; then
   echo
   mount |grep " type nfs "   
   errorexit "\n\nerror: $mntdir is not mounted or not mounted with type nfs\n" \
"(correct mountpoint has to be given as shown above:${0##*/} stop $mntdir)\n" \
"                                                                       ^^^^^^^^"
  fi
 fi
  for x in TERM KILL result; do
   unset is_running
   for f in portmap.bin statd.bin; do
    if ps |grep -v grep |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" = "portmap.bin" ]; then
        if [ "$is_mounted" ]; then
	 /var/$addon/usr/bin/umount $mntdir || errorexit "error: failed to umount $mntdir (running program inside $mntdir?)"
        fi
       fi
       killall -$x $f
       sleep 2
     esac
    fi
   done
   [ "$is_running" ] || break
  done
  for m in nfs lockd sunrpc; do
   lsmod |grep -q "^$m " && rmmod $m
  done
  [ "$quiet" ] || echo "run ${0##*/} remove to free memory by removing addon $addon from the system"
 df
 ;;
*)
 usage
esac

