#!/bin/sh

source ../Config.sh

if [ -z "$@" ]; then
    # rtsys only supports install commands
    
    if [ "$PP_BUILD_TYPE" = "final" ]; then
        # final: unpack existing final binaries from rtsys/fw-binary.bin
        
        # get firmware image name
        fw_filename=`ls . | grep "fw.*\.bin"`
        if [ "$fw_filename" = "" ]; then
            echo "Could not find existing firmware binary for final build"
            exit 1
        fi
        
        # mount the root fs
        pushd ../mkfirmware
        ./replacepart.pl ../rtsys/$fw_filename
        ./img2data.sh replacepart_1_0 root.initrd.unpacked
        
        mkdir -p target_root
        sudo umount target_root &> /dev/null
        sudo mount -o loop -t ext2 root.initrd.unpacked ./target_root
	if [ "$?" != "0" ]; then
		echo "Could not mount initrd via loop device"
		exit 1;
	fi
        
        # copy root fs
        sudo install -d $DESTDIR
        sudo cp -a target_root/* $DESTDIR
        sudo rm -rf $DESTDIR/lost+found/

	# change owner of /install_root files to the user of this sdk
	USERID=`id -un`
	GOUPID=`id -gn`
	sudo chown -R $USERID:$GROUPID $DESTDIR/*

	# unpack static libraries from rtsys/install_root_devel.tar
	filelist=`tar -tf $FW_TOPDIR/rtsys/install_root_devel.tar`
	for i in $filelist; do
		filename=`echo $i | grep "/lib/[^/]*\.a$"`
		if [ -n "$filename" ]; then
			echo "Extracting static lib $i"
			rm -f "$DESTDIR/$i"
			tar -C $DESTDIR -xf $FW_TOPDIR/rtsys/install_root_devel.tar "$i"
		fi
	done
	for i in $filelist; do
		filename=`echo $i | grep "/lib/[^/]*\.so$"`
                if [ -n "$filename" ]; then
                        tar -C "$FW_TOPDIR/rtsys" -xf $FW_TOPDIR/rtsys/install_root_devel.tar "$i"
			filetype=`file -L "$FW_TOPDIR/rtsys/$i" | grep "relocatable"`
			if [ -n "$filetype" ]; then
				echo "Extracted relocatable lib $i"
				mv "$FW_TOPDIR/rtsys/$i" "$DESTDIR/$i"
			else
				rm -f "$i"
			fi
		fi					
	done

	# save version string for later usage when building the final fw
	hal_wrapper="/usr/local/bin/make_initrd_image"
	if [ ! -x "$hal_wrapper" ]; then
	    hal_wrapper=""
	fi   
	sudo $hal_wrapper ./patch_version.pl -W ./pp_fw_version.bin $DESTDIR/lib/libpp_firmware.so

        # unmount the root fs
        sudo umount ./target_root
        rm root.initrd.unpacked replacepart_?_?
        rmdir target_root
        popd
    else
        # devel or debug: unpack existing devel binaries from rtsys/install_root_devel.tar
        install -d $DESTDIR
        tar -C $DESTDIR -xvf install_root_devel.tar
        cp -f uImage /tftpboot/zImage.$PP_BOARD.$PP_SUBBOARD.$USER
    fi;

fi
