#
#
# ident "@(#)bbupdnfunc.sh 1.1     00/07/28 SMI"
#
# Copyright (c) 2000 by Sun Microsystems, Inc.
# All rights reserved.
#                       
#
# cp files on behalf of read_file
# $1 - handle, this is the agent that does the actual 
#      retrival from the portal, if set 'none' no 
#      handle is used and the data is kept on BB
# $2 - direction
# $3 - destination 
# $4 - uuid
# $5+ - list of files to copy
copy_files() {

	handle=$1
	dir=$2
	dst=$3
	uuid=$4
	shift 4

	if [ $handle != "none" ]; then
		handle=`eval echo $handle`
	fi

	udir=`bbfind_uuid_dir $uuid`

	for f in $*; do
		case $dir in
		 "up")	
			if [ -f $BBHOME/$dst/$f ]; then
#			  chown root $BBHOME/$dst/$f
			  if [ ! -d $udir/$dst ]; then 
			    mkdir -p $udir/$dst
			  fi
			  cp $BBHOME/$dst/$f $udir/$dst
			  rm -f $BBHOME/$dst/$f
			else
			  if [ ! -d $udir/$dst ]; then 
                            mkdir -p $udir/$dst
                          fi
			  touch $udir/$dst/$f 
			fi
			if [ $handle != "none" -a -x $handle ]; then
                              $handle $dir $uuid $udir $dst $f
                        fi 
			;;
		 "down")
			if [ $handle != "none" -a -x $handle ]; then
                        	$handle $dir $uuid $udir $dst $f
			fi
			if [ -f $udir/$dst/$f ]; then
			  if [ ! -d $BBHOME/$dst ]; then 
                            mkdir -p $BBHOME/$dst
                          fi
			  cp $udir/$dst/$f $BBHOME/$dst
			  chmod 600 $BBHOME/$dst/$f
#			  chown $BBUSER $BBHOME/$dst/$f
			else
			  if [ ! -d $BBHOME/$dst ]; then 
                            mkdir -p $BBHOME/$dst
			  fi
			  touch $BBHOME/$dst/$f
			fi
			;;
		 *);;
		esac
	done
}

# reads file list form a config file
# and moves the configured files to their 
# destination 
# $1 - up or down , depending if it is up/download
# $2 - config file to read 
# $3 - UUID ( universal user id , currently the smartcard token ) 
read_file() {

	dir=$1
	retv=0
	(
	  while [ $retv != 1 ]; do 
	    read hndl dst files
	    retv=$?
	    if [ ${#hndl} != 0 ]; then
	      comment=`echo $hndl | cut -d'#' -f1`
              if [ ${#comment} != 0 ]; then
                copy_files $hndl $dir $dst $3 $files
	      fi
	    fi
	  done
	) < $2
}

