#!/usr/bin/ksh

################################################################################
function usage
{
        print -u2 "USAGE: ${PROG} -f <FAMILY> -a <RELPATH> -m <MAPFILE> -r <RELEASE>"
        print -u2 "WHERE: FAMILY      is the CMVC family to process"
        print -u2 "       RELPATH     is the absolute path to the file tree"
        print -u2 "       MAPFILE     is the pathname component mapfile"
        print -u2 "       RELEASE     is the is the active CMVC release"
        print -u2 "NOTE : script must be run by a SUPERUSER"
	print -u2 "       MAPFILE format pathname|compname"
	print -u2 "       Assuming empty RELEASE"
        exit 1
}
################################################################################
function initialize
{
	RC=0
	if [ -z "${FAMILY}" ]
	  then  print -u2 "<<ERROR>> FAMILY name required"
		RC=1
	  else  CMVC_FAMILY=${FAMILY}
	fi
	if [ ! -d "${RELPATH}" ]
	  then  print -u2 "<<ERROR>> RELPATH not a directory"
		RC=1
	fi
	if [ ! -f "${MAPFILE}" ]
	  then  print -u2 "<<ERROR>> MAPFILE not a file"
		RC=1
	fi
	WHOAMI=`id -u -n`
	SUPERUSER=`Report -view users -wh "login = '${WHOAMI}' AND superuser = 'yes'" -raw`
	if [ -z "${SUPERUSER}" ]
	  then  print -u2 "<<ERROR>> LOGIN invalid or not SUPERUSER"
		RC=1
	fi
	if [ -z "${RELEASE}" ]
	  then  print -u2 "<<ERROR>> RELEASE name required"
		RC=1
	  else  PROCESS=`Report -view releaseview -wh "dropdate is null AND name = '${RELEASE}'" -raw | cut -d\| -f3`
		if [ -z "${PROCESS}" ]
		  then  print -u2 "<<ERROR>>  RELEASE name INVALID or deleted"
			RC=1
		fi
	fi
	OUTFILE=/tmp/outfile.$$
	print "Processing release: ${RELEASE}" >${OUTFILE}
	BADFILE=/tmp/badfile.$$

}
################################################################################
function process
{
	print "OUTPUT FILE: ${OUTFILE}"
	print "FAILED CMDS: ${BADFILE}"
	find ${RELPATH} -type f -print |
	while read pathname 
  	  do
		pathname=`print ${pathname} | sed "s;${RELPATH}/;;"`
		compname=`cat ${MAPFILE} | awk 'BEGIN {FS="|"}
		  {
			if ($1 == PATHNAME)
			  {
				printf ("%s",$2)
				break
			  }
		  }' PATHNAME=${pathname}`
		cmd="File -create ${pathname} -release ${RELEASE}"
		cmd="${cmd} -component ${compname} -relative ${RELPATH}"
		print "${cmd}" >>${OUTFILE}
		eval ${cmd} 2>>${OUTFILE}
		if [ $? -ne 0 ]
		  then	print "${cmd}" >>${BADFILE}
		fi
  	  done
}
################################################################################
# main processing
PROG=${0##*/}
while getopts :f:a:m:r: argument
  do
	case "${argument}" in
	  f)	FAMILY=${OPTARG}
		;;
	  a)	RELPATH=${OPTARG}
		;;
	  m)	MAPFILE=${OPTARG}
		;;
	  r)	RELEASE=${OPTARG}
		;;
	  \?)	usage
		;;
	esac
  done
initialize
if [ "${RC}" -eq "0" ]
  then  Release -modify ${RELEASE} -process prototype
	process
	Release -modify ${RELEASE} -process ${PROCESS}
  else  usage
fi
