#!/bin/sh
#set -x
# -------------------------------------------------------------- 
# (C) Copyright 2001,2007                                       
# International Business Machines Corporation,                                                           
#                                                                
# All Rights Reserved.                                           
# --------------------------------------------------------------                                               

#------------------------------------------------------------------------
#  cellsdk-sync_simulator
#
#  This script synchronizes the Simulator sysroot with the SDK 
#------------------------------------------------------------------------

#  Set our name
SELF=`basename $0`

# Determine which machine we are installing on
MACHINE=`uname -m`
case $MACHINE in
    i686) 
        ;;
    x86_64) 
	;;
    ppc64)
        ;;
    *)
         echo "CELL SDK not supported on this machine type $MACHINE"
         exit 1; 
         ;;
esac

# Set local variables
cellTop=/opt/cell
sdkDir=${cellTop}/sdk
prototypeDir=${cellTop}/sdk/prototype
rpmDir=/tmp/cellsdk/rpms

SYSROOT_DISK=sysroot_disk
mntPoint=/mnt/cell-sdk-sysroot
simulator=/opt/ibm/systemsim-cell
imagesDir=${simulator}/images/cell

if [ "$MACHINE" = "ppc64" ] ; then  
   sysrootTop=
else
   sysrootTop=${cellTop}/sysroot
fi



#--------------------------------------------------------------------------
# Displays the usage statement
# args:
#			none
# return
#			0 = 
function usage()
{
  echo ""
  echo "Usage: $SELF [install]"
  echo "where install optionally installs RPMs in "
  echo "    ${rpmDir} into the sysroot image"
  echo ""
}


# mount sysroot
function mountSysroot()
{
   # check to see if the mount point has been created
   if [ ! -e ${mntPoint} ] ; then
         mkdir -p ${mntPoint}
         if [ $? != 0 ] ; then
            echo "ERROR: Failed to create sysroot mount dir in /mnt."
            echo "Check that you have write permission and/or turn off autofs."
            exit 1
       	 fi
   fi

   # check if not mounted, if so mount and set flag so as to unmount
   if [ "`cat /etc/mtab | grep ${mntPoint}`" == "" ] ; then
	 echo "Mounting system root on ${mntPoint}"
	 echo "mount -o loop ${imagesDir}/${SYSROOT_DISK} ${mntPoint}"
	 mount -o loop ${imagesDir}/${SYSROOT_DISK} ${mntPoint}
	 if [ $? != 0 ] ; then
	    echo "ERROR:  Failed to mount sysroot image.  Is sysroot_image installed?"
            exit 1
         fi
         mounted=1
   fi

}

# unmount sysroot
function unmountSysroot()
{
    if [ $mounted == 1 ] ; then
        echo "Unmounting system root from ${mntPoint}"
        umount ${mntPoint}
        mounted=0
    fi
}


# build and install libsim simulation library
function installLibsim()
{
    cd ${simulator}/sample/cell/libsim
    make CELL_TOP=${sdkDir}
    cp spu/libsim.h ${sysrootTop}/usr/spu/include
    cp spu/libsim.a ${sysrootTop}/usr/spu/lib
}


# rsync a directory into the sysroot
function rsyncDir()
{
    local dirName=$1
    dir=`dirname $dirName`
    mkdir -p ${mntPoint}${dirName}
    if [ -e ${sysrootTop}${dirName} ]; then
        rsync -az --delete ${sysrootTop}${dirName} ${mntPoint}${dir} #>/dev/null 2>&1
        if [ $? != 0 ] ; then
            echo "ERROR:  Problem with rsync of files from ${sysrootTop}${dirName}"
            echo "        to ${mntPoint}${dir}"
            return 1
        fi
    fi
    return 0
}


#--------------------------------------------------------------------------
# Updates the simulator sysroot image
# args:
#			<none>
# return
#			0 = 
function update_sysroot()
{
    mounted=0
    mountSysroot

    # build and install simulation library
    echo "Building and installing sample simulation library"
    installLibsim

    # synchronize files from sysroot directories into the SYSROOT image 
    echo "Starting synchronization of directories with Simulator sysroot image."

    mkdir -p ${mntPoint}${sdkDir}/usr 
    rsyncDir "${sdkDir}/usr"

    mkdir -p ${mntPoint}/etc/pki/cell-spu-isolation
    rsyncDir "/etc/pki/cell-spu-isolation"

    mkdir -p ${mntPoint}/etc/pki/rpm-gpg
    cp /etc/pki/rpm-gpg/*cellsdk* ${mntPoint}/etc/pki/rpm-gpg 2>/dev/null

    mkdir -p ${mntPoint}${prototypeDir}/usr
    rsyncDir "${prototypeDir}/usr"

    mkdir -p ${mntPoint}/usr/lib/spe
    rsyncDir "/usr/lib/spe"
   
    echo "Synchronization of directories with Simulator sysroot image is complete."

    # rpms (for installation into the sysroot)
    if (( INSTALL_RPMS )) ; then
        rpmCount=`ls -1 ${rpmDir}/*.{ppc,ppc64}.rpm 2>/dev/null | wc -l`
        if [ $rpmCount -eq 0 ]; then
            echo ""
            echo "${rpmDir} does not contain RPMs for the Simulator sysroot image."
        else
            echo ""
            echo "Starting installation RPMs into Simulator sysroot image."
            echo ""
            echo "The simulator will now start with an automated script. Depending on your"
            echo "machine speed, it may take some time for the simulator to start and"
            echo "execute the provided TCL script. The simulator exits when it is complete."
            echo ""
            echo "Installing RPMS into Simulator sysroot image"
            mkdir -p ${mntPoint}/${rpmDir}

            # create a bash script to run in the simulator
            cat << EOF > ${rpmDir}/install_rpms.sh
#!/bin/sh
# install the cellsdk gpg keys
key=\`rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n' | grep -i cellsdk\`
[ "\$key" == "" ] && [ -e "/etc/pki/rpm-gpg/RPM-GPG-KEY-cellsdk" ] && rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-cellsdk
key=\`rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n' | grep -i cell_support\`
[ "\$key" == "" ] && [ -e "/etc/pki/rpm-gpg/RPM-GPG-KEY-cellsdk" ] && rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-cellsdk-open

cd ${rpmDir}
rm -f ${rpmDir}/install_rpms.out
for r in *.{ppc,ppc64}.rpm; do
  echo "installing \$r" >> ${rpmDir}/install_rpms.out
  rpm -U --nodeps --force \$r 2>>${rpmDir}/install_rpms.out
  if [ \$? -ne 0 ]; then
    echo "ERROR \$r" >> ${rpmDir}/install_rpms.out
  else 
    rm -f \$r
  fi
done
cat ${rpmDir}/install_rpms.out
cp ${rpmDir}/install_rpms.out /tmp
sync; sync
EOF
            chmod 777 ${rpmDir}/install_rpms.sh
            rm -f ${rpmDir}/install_rpms.out

            # copy the files into the simulator
            mkdir -p ${mntPoint}${rpmDir}
            cp ${rpmDir}/install_rpms.sh ${mntPoint}${rpmDir} #>/dev/null 2>&1
            cp ${rpmDir}/*.{ppc,ppc64}.rpm ${mntPoint}${rpmDir} #>/dev/null 2>&1
         
            # unmount the Simulator sysroot image. 
            unmountSysroot

            # in order to start the simular in rw mode, we must modify the default
            # tcl script before we start the simulator
            sed 's/mysim bogus disk init 0 $sysrootfile newcow sysroot_disk.cow 1024/mysim bogus disk init 0 \$sysrootfile rw/' < ${simulator}/lib/cell/systemsim.tcl > ${simulator}/lib/cell/installrpms.tcl

            # start the simulator with the TCL script to install RPMs
            echo ""
            echo ""
            PATH=${simulator}/bin:$PATH systemsim -cell -n -q -f ${cellTop}/install_rpms.tcl #>/dev/null 2>&1
            rm ${simulator}/lib/cell/installrpms.tcl
        fi   

        if [ -e ${rpmDir}/install_rpms.out ] && [ `grep -ic error ${rpmDir}/install_rpms.out` -gt 0 ]; then
	     echo "ERROR installing rpms into sysroot"
             cat ${rpmDir}/install_rpms.out
        else
             mkdir -p ${rpmDir}/installed
             mv ${rpmDir}/*.{ppc,ppc64}.rpm ${rpmDir}/installed #>/dev/null 2>&1
             echo "Installation of RPMs into Simulator sysroot image is complete."
        fi
   fi

   unmountSysroot
}


# Pop the first argument as the task
if [ $# -eq 1 ] ; then

   TASK=$1
   shift

   case $TASK in 
	install)
		let "INSTALL_RPMS += 1"
		;;
                
	*)
		usage
		exit 1
           	;;
   esac
fi

# Make sure there is only one parameter  
if [ $# -gt 1 ] ; then
   usage
   exit 1
fi   


# Checks if the user is either root, or has the required sudo abilities
if [ $UID != 0 ] ; then
	echo "ERROR:  $SELF must be run as root"
	exit
fi

# do the work
update_sysroot

# end of script


