#!/bin/ksh
#
# ident "@(#)bbcpfiles.sh	1.6 01/06/12 SMI"
#
# Copyright 2000-2001 Sun Microsystems, Inc.
# All rights reserved.
#

. /etc/opt/SUNWbb/blackbox.rc

CONF_FILE=""
SRCPATH=""
TARGET=""
IGNORE=""
CUR_OS=`uname -r`
TARGET_ERR=""
ME=`basename $0`

umask 022

copy_file() {

	file=$1
	shift
	argc=$#

	if [[ "$file" = "!search" ]]; then 
		SRCPATH="$*"
		return 0
	fi
	if [[ "$file" = "!target" ]]; then
		TARGET=$BBROOTPATH/$1
		if [[ ! -d $TARGET ]]; then 
			mkdir -m 755 -p $TARGET
			if [[ $? != 0 && ! -d $TARGET ]]; then 
				print -u2 "${ME}: cannot create: $TARGET"
				TARGET_ERR="target $TARGET is missing"
				TARGET=""
				return 1
			else
				TARGET_ERR="no target error"
			fi
		fi
		return 0
	fi
	if [[ "$file" = "!ignore" ]]; then
		if [[ $argc -gt 0 ]]; then 
			IGNORE="$*"
		else 
			IGNORE=""
		fi
		return 0  
	fi
	if [[ "$TARGET" = "" ]]; then
		print -u2 "${ME}: $TARGET_ERR, skip $file" 
		return 1
	fi
	if [[ "$SRCPATH" = "" ]]; then
                print -u2 "${ME}: no search path set in $CONF_FILE, skip $file"
		return 1
        fi  
	
	# search for file
	for dir in $SRCPATH; do
		
		if [[ -f $dir/$file ]]; then 
			reldir=`dirname $file`
			relfile=`basename $file`
			if [[ "$reldir" != '.' ]]; then
				mkdir -m 755 -p $TARGET/$reldir
				if [[ $? != 0 && ! -d $TARGET/$reldir ]]; then 
					print -u2 "${ME}: failed to create $TARGET/$reldir"
					return 2
				fi
			fi 
			rm -f $TARGET/$file
			cp -p $dir/$file  $TARGET/$file
			(
				cd $TARGET/$reldir
				typeset -i cnt=0
				while [[ $cnt != $argc ]]; do
					(( idx=cnt+1 ))
					eval link=\$$idx
					if [[ -h $link ]]; then
						rm -f $link
					fi
					ln -s $relfile $link
					(( cnt+=1 ))
				done
			)
			return 0
		fi
	done
	for os in "$IGNORE"; do
		if [[ "$CUR_OS" = "$os" ]]; then 
			return 0
		fi
	done
	print -u2 "${ME}: Warning: $file not found"
	return 1
}

if [[ $# != 1 ]]; then
	print -u2 "usage: $0 <file>"
	print -u2 "<file> list of files to copy to the chroot environment"
	print -u2 "comments start with #"
	exit 1
fi

CONF_FILE=$1 
TARGET_ERR="no target set in $CONF_FILE" 

retv=0
egrep -v '^#|^$$' $CONF_FILE | (

	while [[ $retv != 1 ]]; do
        	read line
        	retv=$? 
		if [[ retv != 1 && ! -z $line ]]; then 
			copy_file $line
		fi
	done
)

exit 0
