#! /bin/sh

. $TS_GLOBAL
INITLIST=/tmp/initlist
PKGDIR=/tmp/pkg

if [ -n "$DEBUG_NETWORK" ] ; then
	debug="-d"
fi

case $1 in
load)
    if ! pkg_is_loaded $2; then
	# This first checks for pkgs loaded on local storage
	# If it doesn't find them it tries to download from tftp
	if [ -e ${PKG_PATH}/$4/$2.$3 ]; then
	    echo_log "Loading package $2 (storage)..." -n $debug
	    ln -s ${PKG_PATH}/$4/$2.$3 /$2.$3
	else
	    echo_log "Loading package $2 (tftp)..." -n $debug
	    # Download PKGs from a subdir of /tftpboot if PKG_PREFIX
	    # is set in thinstation.conf.network
	    
	    # Check weither IP_SERVER variable is set or not. If not, dont try TFTP.
	    if [ -z "$SERVER_IP" ]; then
	    	 echo_log "No tftp server availibale." $debug
	    else
	         tftp -g -r ${BASEPATH}/$4/$2.$3 -l /$2.$3 $SERVER_IP
	    fi
	fi
	if [ -s /$2.$3 ]; then
	    zcat /$2.$3 | tar -C $PKGDIR -xf - etc/rc$CURRENTRC.d 2> /dev/null
	    # This gets pulls out the list of init processes which need to be done
	    # otherwise you don't know which have/haven't been processed later
	    if [ -e $PKGDIR/etc/rc$CURRENTRC.d ] ; then
		    ls $PKGDIR/etc/rc$CURRENTRC.d >> $INITLIST
	    fi
	    rm -Rf $PKGDIR/* 2>/dev/null
	    zcat /$2.$3 | tar -C / -xf -
	    rm /$2.$3 
	    echo_log "Ok" $debug
	else
	    if [ -e /$2.$3 ]; then
	        rm /$2.$3 
	    fi
	    echo_log "Not found" $debug
	fi
	if [ -e /lib/modules/$2.ko ] ; then
		cat /etc/$2.modules >> /etc/modules.mpkg
		rm /etc/$2.modules
        	touch /var/packages/$2
	fi
    fi
    ;;
# Forces a re-download of a package
forceload)
    rm /etc/init.d/$2 2> /dev/null
    shift 1
    exec $0 load $@
    ;;
# Forces a re-init of a package
forceinit)
    rm /var/packages/$2 2> /dev/null
    shift 1
    exec $0 init $@
    ;;
*)
    if [ -f /etc/init.d/$2 ]; then
	exec /etc/init.d/$2 $1 "$3" "$4" "$5"
    else
	echo "Package $2 is not loaded!!"
	sleep 5
    fi
    ;;
esac

exit 0
