#!/bin/sh
#
# A tool to simplify Makefiles that need to put something
# into the ROMFS
#
# Copyright (C) David McCullough, 2002,2003
#
#############################################################################

# Provide a default PATH setting to avoid potential problems...
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:$PATH"

usage()
{
cat << !EOF >&2
$0: [options] [src] dst
    -v          : output actions performed.
    -e env-var  : only take action if env-var is set to "y".
    -E env-var  : only take action if env-var is not set to "y".
    -o option   : only take action if option is set to "y".
    -O option   : only take action if option is not set to "y".
    -p perms    : chmod style permissions for dst.
    -d          : make dst directory if it doesn't exist
    -S          : don't strip after installing
    -a text     : append text to dst.
    -A pattern  : only append text if pattern doesn't exist in file
    -l link     : dst is a hard link to 'link'.
    -s sym-link : dst is a sym-link to 'sym-link'.
    -M          : install kernel module into dst subdir of module dir

    if "src" is not provided,  basename is run on dst to determine the
    source in the current directory.

    multiple -e and -o options are ANDed together.  To achieve an OR affect
    use a single -e/-o with 1 or more y/n/"" chars in the condition.

    if src is a directory,  everything in it is copied recursively to dst
    with special files removed (currently CVS and Subversion dirs).
!EOF
	exit 1
}

#############################################################################

setperm()
{
	rc=0
	# Always start with write access for the user so that files can be
	# updated/overwritten during make romfs
	chmod u+w ${DIR_ROMFS}${dst}
	if [ "$perm" ]
	then
		[ "$v" ] && echo "chmod ${perm} ${DIR_ROMFS}${dst}"
		chmod ${perm} ${DIR_ROMFS}${dst}
		rc=$?
	fi
	return $rc
}

#############################################################################

file_copy()
{
	rc=0
	if [ -d "${src}" ]
	then
		[ "$v" ] && echo "CopyDir ${src} ${DIR_ROMFS}${dst}"
		(
			cd ${src} || return 1
			V=
			[ "$v" ] && V=v
			find . -print | grep -E -v '/CVS|/\.svn' | cpio -p${V}dumL ${DIR_ROMFS}${dst}
			rc=$?
			# And make sure these files are still writable
			find . -print | grep -E -v '/CVS|/\.svn' | ( cd ${DIR_ROMFS}${dst}; xargs chmod u+w )
			setperm ${DIR_ROMFS}${dst}
		)
	else
		if [ -d ${DIR_ROMFS}${dst} ]; then
			dstfile=${DIR_ROMFS}${dst}/`basename ${src}`
		else
			dstfile=${DIR_ROMFS}${dst}
		fi
		rm -f ${dstfile}
		[ "$v" ] && echo "cp ${src} ${dstfile}"
		if [ ! -d "$DIR_IMAGE" ]
		then
			mkdir -p $DIR_IMAGE
		fi
		case "$src" in
			/*) echo "${src} ${dstfile}" ;;
			*)  echo "`pwd`/${src} ${dstfile}" ;;
		esac >> $DIR_IMAGE/romfs-inst.log
		cp ${src} ${dstfile} && setperm ${dstfile}
		rc=$?
		if [ $rc -eq 0 -a -n "$strip" ]; then
			${STRIPTOOL} ${dstfile} 2>/dev/null
			${STRIPTOOL} -R .comment -R .note ${dstfile} 2>/dev/null
		fi
	fi
	return $rc
}

#############################################################################

file_append()
{
	touch ${DIR_ROMFS}${dst} || return 1
	if [ -z "${pattern}" ] && grep -F "${src}" ${DIR_ROMFS}${dst} > /dev/null
	then
		[ "$v" ] && echo "File entry already installed."
	elif [ "${pattern}" ] && egrep "${pattern}" ${DIR_ROMFS}${dst} > /dev/null
	then
		[ "$v" ] && echo "File pattern already installed."
	else
		[ "$v" ] && echo "Installing entry into ${DIR_ROMFS}${dst}."
		echo "${src}" >> ${DIR_ROMFS}${dst} || return 1
	fi
	setperm ${DIR_ROMFS}${dst}
	return $?
}

#############################################################################

hard_link()
{
	rm -f ${DIR_ROMFS}${dst}
	[ "$v" ] && echo "ln ${src} ${DIR_ROMFS}${dst}"
	ln ${DIR_ROMFS}${src} ${DIR_ROMFS}${dst}
	return $?
}

#############################################################################

sym_link()
{
	rm -f ${DIR_ROMFS}${dst}
	[ "$v" ] && echo "ln -s ${src} ${DIR_ROMFS}${dst}"
	ln -sf ${src} ${DIR_ROMFS}${dst}
	return $?
}

#############################################################################
#
# main program entry point
#

if [ -z "$DIR_ROMFS" ]
then
	echo "DIR_ROMFS is not set" >&2
	usage
	exit 1
fi

v=1
option=y
noption=
pattern=
perm=
func=file_copy
mdir=
src=
dst=
strip=1
kernmod=

while getopts 'dSMve:E:o:O:A:p:a:l:s:' opt "$@"
do
	case "$opt" in
	v) v="1";                           ;;
	d) mdir="1";                        ;;
	S) strip=;							;;
	M) kernmod="1";                     ;;
	o) option="$OPTARG";                ;;
	O) noption="$OPTARG";               ;;
	e) eval option=\"\$$OPTARG\";       ;;
	E) eval noption=\"\$$OPTARG\";      ;;
	p) perm="$OPTARG";                  ;;
	a) src="$OPTARG"; func=file_append; ;;
	A) pattern="$OPTARG";               ;;
	l) src="$OPTARG"; func=hard_link;   ;;
	s) src="$OPTARG"; func=sym_link;    ;;

	*)  break ;;
	esac
#
#	process option here to get an ANDing effect
#
	case "$option" in
	*[mMyY]*) # this gives OR effect, ie., nYn
		;;
	*)
		[ "$v" ] && echo "Condition not satisfied."
		exit 0
		;;
	esac

#
#	process negative options here to get an ANDing effect
#
	case "${noption:-n}" in
	*[nN]*) # this gives OR effect, ie., yNy
		;;
	*)
		[ "$v" ] && echo "Condition not satisfied."
		exit 0
		;;
	esac
done

shift `expr $OPTIND - 1`

case $# in
1)
	dst="$1"
	if [ -z "$src" ]
	then
		src="`basename $dst`"
	fi
	;;
2)
	if [ ! -z "$src" ]
	then
		echo "Source file already provided" >&2
		exit 1
	fi
	src="$1"
	dst="$2"
	;;
*)
	usage
	;;
esac

if [ -n "$kernmod" ]; then
	strip=
	kerndir=${DIR_ROOT}/${DIR_LINUX}
	# could prob take from UTS headers as well ...
	kernver=$(cat ${kerndir}/include/config/kernel.release)
	dst="/lib/modules/${kernver}/${dst}"
fi

if [ "$mdir" -a ! -d "`dirname ${DIR_ROMFS}${dst}`/." ]
then
	mkdir -p "`dirname ${DIR_ROMFS}${dst}`/." || exit 1
fi

$func || exit 1

exit 0

#############################################################################
