#!/bin/sh
#
# This script cleans the "rfs" directory, then copies built programs and template
# files to the "rfs" directory in the format needed to add to a pristine OS
# install.  The format of the command is:
#
#	populate_smc {build-type}
#
# If build-type is left blank, it defaults to "ZoomRelease"; otherwise, it is the
# type of build to pull from the workspaces.  For example, to pull the Debug files
# for the target:
#
#	populate_smc ZoomDebug
#
# After populating the rfs directory with populate_smc, the user should invoke
# "maketar" to build an installable compressed tar ball.
#
BUILD="$1"

if [ -z "$BUILD" ]
then
	BUILD=ZoomRelease
fi

XETC=./rfs/etc
XHOME=./rfs/home
XUSR=./rfs/usr
XVAR=./rfs/var
SMCHOME=./rfs/home/smc
SMC0HOME=./rfs/home/smc0
WKSP=../Workspaces/Mixed
START=`pwd`
TEMPFILE=/tmp/temp`date +'%Y%m%d%H%M%S%N'`

# clean the rfs directory and re-create
sudo rm -rf rfs
mkdir rfs

# use cpio to copy the content of the template directory (less the .svn and
# .makepp directories) to rfs
cd template
find * -print | egrep -v '/.svn|/.makepp' | cpio -pv ../rfs

# create an archive of the CORBA libraries and extract under rfs
cd /home/SMCDev/omniORB/Zoom
find * -print | egrep -v '/[.]svn|/[.]makepp' > "$TEMPFILE"
tar -cvjf $START/omni.tar.bz2 -T "$TEMPFILE" --no-recursion
rm "$TEMPFILE"
mkdir -p $START/rfs/usr/local
cd $START/rfs/usr/local
tar xvjpf $START/omni.tar.bz2
cd $START

# determine which files (shared objects and executables) should be copied from the
# workspace build directories
candidate_files=`find $WKSP -type f -print | egrep "/$BUILD/" | egrep -v "/$BUILD/"'.+/'`
built_libs=`file $candidate_files | grep 'shared object' | sed 's/[:].*//g'`
built_execs=`file $candidate_files | grep 'executable' | sed 's/[:].*//g' | egrep -v EncryptedStartup`
built_execs0=`file $candidate_files | grep 'executable' | sed 's/[:].*//g' | egrep EncryptedStartup`

# indicating which files are being pulled
echo "LIBS: $built_libs"
echo "EXECS: $built_execs $built_execs0"

# copying the files to lib and bin subdirectories of smc home
sudo cp $built_libs $SMCHOME/lib
sudo cp $built_execs $SMCHOME/bin

# copying EncryptedStartup smc0
sudo cp $built_execs0 $SMC0HOME/bin

# in general, everything under rfs will be owned by root/root
find ./rfs -printf '"%p"\n' | sudo xargs chown root
find ./rfs -printf '"%p"\n' | sudo xargs chgrp root

# items under SMC home will be owned by smc/smc and bin directory
# files are executable (+x)
find $SMCHOME/bin -type f -printf '"%p"\n' | sudo xargs chmod +x
find $SMCHOME -printf '"%p"\n' | sudo xargs chown smc
find $SMCHOME -printf '"%p"\n' | sudo xargs chgrp smc

# items under SMC0 home will be owned by smc0/smc0 and bin directory
# files are executable (+x)
find $SMC0HOME/bin -type f -printf '"%p"\n' | sudo xargs chmod +x
find $SMC0HOME -printf '"%p"\n' | sudo xargs chown smc0
find $SMC0HOME -printf '"%p"\n' | sudo xargs chgrp smc0


# the sudoers file must be rr-
sudo chmod 440 ./rfs/etc/sudoers
