#! /bin/bash

set -x

#
# Script to update version information in header file fcc/fvw/FVSourceRevision.h and optionally in macOS/iOS info.plist files
#
# Xcode projects depending on FVSourceRevision.h be must run this script before compile phase.
# Xcode projects updating .plist files of privileged helper tools must run this script before linker
#

# Root directory of working copy of source tree
WORK_ROOT=$1

#Name of Info.plist file to update (optional)
PLIST_FILE=$2

USAGE_INFO="update_version_info.sh <Source Root Directory> [<Plist Filename>]\n"


if [ -z "${WORK_ROOT}"  ] ; then
echo "source root directory undefined"
echo ""
echo $USAGE_INFO
exit -1;
fi

#
# If svn commands used by XCode are incompatible with SVN client used to checkout sources,
# set the variable SVN_PATH in optional script file svnpath.sh (don't forget trailing slash in path name)
# If SVN_PATH is not set, the svn commands installed with XCOde are used.
#
[ -e ${WORK_ROOT}/build/svnpath.sh ] && source ${WORK_ROOT}/build/svnpath.sh

[ ! -e "${WORK_ROOT}/svn_version.txt" ] && (`svnversion -n` > "${WORK_ROOT}/svn_version.txt")

SVN_REVISION_NUM=`cat ${WORK_ROOT}/svn_version.txt`

#
# Extract version info from FastLibVersion.h
#
VERSION_INFO=`awk -f ${WORK_ROOT}/build/get_version.awk -- ${WORK_ROOT}/fcc/fvw/FastLibVersion.h`


#
# Update FVSourceRevision.h
#
# First write to temp file than move to FVSourceRevision.h because this script might be used concurrently in parallel builds
#
TMP_FILE="${WORK_ROOT}/fcc/fvw/$RANDOM.$$.tmp"

cat << EOF > ${TMP_FILE}
//
// This file is automatically created or updated with each build. Do not edit!
//
#define FV_SOURCE_REVISION          ${SVN_REVISION_NUM}
#define FV_SOURCE_REVISION_STR      "${SVN_REVISION_NUM}"
#define FV_VERSION_INFO             ${VERSION_INFO}
#define FV_VERSION_INFO_STR         "${VERSION_INFO}"
#define FV_FULL_VERSION_INFO        ${VERSION_INFO}.${SVN_REVISION_NUM}
#define FV_FULL_VERSION_INFO_STR    "${VERSION_INFO}.${SVN_REVISION_NUM}"
EOF

mv ${TMP_FILE} ${WORK_ROOT}/fcc/fvw/FVSourceRevision.h

#
# Finally update plist file if regested 
#
if [ ! -z "${PLIST_FILE}" ] ; then

echo -n ${PLIST_FILE} \
| xargs -0 /usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${VERSION_INFO}"

echo -n ${PLIST_FILE} \
| xargs -0 /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${VERSION_INFO}"

echo -n  ${PLIST_FILE} \
| xargs -0 /usr/libexec/PlistBuddy -c "Set :com.fastviewer.source.revision ${SVN_REVISION_NUM}"

fi
