#!/bin/sh
#*************************************************************************
# Copyright (c) 2002 The University of Chicago, as Operator of Argonne
#     National Laboratory.
# Copyright (c) 2002 The Regents of the University of California, as
#     Operator of Los Alamos National Laboratory.
# EPICS BASE Versions 3.13.7
# and higher are distributed subject to a Software License Agreement found
# in file LICENSE that is included with this distribution. 
#*************************************************************************
# InstallEpics
#
#     InstallEpics is used within makefiles to copy new versions of
#     files into a destination directory.
#
##########################################################
TOOL=`basename $0`
MODE=755
CREATE_DIR=0
USAGE="Usage:
	$TOOL [ -m mode ] file ... directory

     -m mode        Set the mode for the installed file (0755 by default)
     file           Name of file
     directory      Destination directory
"
# get command line options
while getopts m:g:o:csd OPT
do

	case $OPT in
	m)            MODE=$OPTARG;;
	g | o)        echo "$USAGE"; echo "$i $OPTARG not implemented";;
	c | s)        echo "$USAGE"; echo "$i not implemented";;
	d)            CREATE_DIR=1;;
	--)           break;;
	esac
done
shift `expr $OPTIND - 1`

# at least two args required
if [ $# -lt 2 ]
then
	echo "Nothing to install"
	exit
fi

INSTALL_DIR=
FILELIST=
for i 
do
	FILELIST="${FILELIST} ${INSTALL_DIR}"; INSTALL_DIR=$i; shift;
done

if [ ! -d "${INSTALL_DIR}" ] ;then
    if [ ${CREATE_DIR} != "0" ] ;then
        OLDIFS=${IFS}
        IFS=/
        DIRNAME=
        for DIR in ${INSTALL_DIR}
        do
	    if [ "${DIR}" = "." ] || [ "${DIR}" = ".." ] ;then
	        if  [ "${DIRNAME}" = "" ] ;then
 	    	    DIRNAME=${DIR}
		else
 	    	    DIRNAME=${DIRNAME}/${DIR}
		fi
	    else
 	    	DIRNAME=${DIRNAME}/${DIR}
		if [ ! -d "${DIRNAME}" ] ;then
		    mkdir "${DIRNAME}"
		fi
	    fi
        done
        IFS=${OLDIFS}
    else
        echo "$USAGE\n Can't find directory '${INSTALL_DIR}'"
        exit 1
    fi
fi

for FILE in ${FILELIST} 
do
	if [ ! -f ${FILE} ] ;then
    	echo "$USAGE\n Can't find file '${FILE}'"
    	exit 1
	fi

	TEST=
	FILEBASENAME=`basename ${FILE}`
	if [ -f ${INSTALL_DIR}/${FILEBASENAME} ] ;  then 
		#Is ${INSTALL_DIR}/${FILEBASENAME} link timestamp  newer than ${FILE}
		TEST=`find ${INSTALL_DIR} -name "${FILEBASENAME}" -newer ${FILE} -print`
	fi
	if [ "${TEST}x" = "x" ] ; then 
		#echo "Installing ${FILEBASENAME}"
		rm -f ${INSTALL_DIR}/${FILEBASENAME}
		cp -p ${FILE} ${INSTALL_DIR}/${FILEBASENAME}
		chmod ${MODE} ${INSTALL_DIR}/${FILEBASENAME}
	else 
		echo "${INSTALL_DIR}/${FILEBASENAME} is up to date"
	fi
done

exit 0
