#!/usr/bin/ksh
#

#
# Copyright (c) 2012, Igor Kozhukhov <ikozhukhov@gmail.com>. All rights reserved.
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Main
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Strip a full x86/amd64 root archive into the machine-specific portion.
# 
# Args:
#   MASTER_DIR: Area already populated with complete root contents
#
#   BA_BUILD: Area where machine-specific archive is put together.
#
#   KERNEL_ARCH: Architecture for which this image should be configured
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Verify argument count
if [ $# != 3 ] ; then
	print -u2 "$0: Requires 3 args: master root image, boot archive build area, kernel architecture"
	exit 1
fi

MASTER_DIR=$1
BA_BUILD=$2
KERNEL_ARCH=$3

# Define a few commands.
CD=cd		# Built into the shell
CPIO=/usr/bin/cpio
FIND=/usr/bin/gfind
GREP=/usr/bin/ggrep
MKDIR=/usr/bin/mkdir
RM=/usr/bin/rm
XARGS=/usr/bin/xargs

if [ ! -d ${BA_BUILD} ] ; then
	${MKDIR} -p ${BA_BUILD}
fi


# Start by duplicating entire master tree into build tree
print "Duplicating ${MASTER_DIR} to ${BA_BUILD}"
${CD} ${MASTER_DIR}
${FIND} . | ${CPIO} -pmud ${BA_BUILD}

${CD} ${BA_BUILD}

# Basic idea here is that an x86 arch means we remove anything that's amd64
# from /kernel, /platform, and /lib.  Conversely, on amd64, we remove anything
# from /kernel and /platform that's not a .conf file or in an amd64 directory

if [ ${KERNEL_ARCH} == "x86" ]; then
	print "Stripping amd64 components"
	${FIND} kernel platform lib usr -name amd64 | ${XARGS} ${RM} -rf 
#	${FIND} kernel platform lib usr -t l -name 64 | ${XARGS} ${RM} -rf 
elif [ ${KERNEL_ARCH} == "amd64" ]; then
	print "Stripping i386 components"
	${FIND} kernel platform -type f -print | ${GREP} -v conf$ | 
	    ${GREP} -v /amd64/ | ${XARGS} ${RM} -f
else
	print -u2 "$0: ${KERNEL_ARCH} is not a supported architecture"
	exit 1
fi

exit 0
