#! /bin/bash

# Update a /cell/cui_properties.txt file for cyflex_java use.
#
# Input arguments
#    File to update
# 
# Actions
#    When updating, the original file is saved.

SAVE_EXTENSION=cyflex_java_rpm.save

# One command line argument is required.
if (( $# != 1  )); then
   echo One command line argument is required.
   exit 1
fi

# Command line argument must be an existing file
if [ ! -e $1 ]; then
   echo Command line argument must be an existing file.
   exit 1
fi

# Original file owner and group
OWNER=$(ls -ldH $1 | tr -s ' ' | cut -f 3 -d\ )
GROUP=$(ls -ldH $1 | tr -s ' ' | cut -f 4 -d\ )

# Save original file.
cp $1 ${1}.$SAVE_EXTENSION
chown ${OWNER}:${GROUP} ${1}.$SAVE_EXTENSION

# Temporary work file
TEMP=TEMP_PROP_FILE
rm -f $TEMP

# Remove all properties which need to be updated.
ex $1 <<eod
1,$ g/com.cybermetrix.cyflex.specfiles.Units.fileName/ d
1,$ g/com.cybermetrix.cyflex.specfiles.PAMChannels.fileName/ d
1,$ g/com.cybermetrix.cyflex.specfiles.Variables.fileName/ d
1,$ g/com.cybermetrix.cyflex.specfiles.xmlBase/ d
1,$ g/com.cybermetrix.cyflex.specfiles.hardwarefile/ d
1,$ g/com.cybermetrix.cyflex.specfiles.cal_tables/ d
1,$ g/com.cybermetrix.cyflex.specfiles.local_specs/ d
1,$ g/cyflex.home / d
1,$ g/cyflex_java.home / d
1,$ g/cyflex.local_cell.cell / d
w $TEMP
eod

# Reinsert needed properties with updated pointers.
# Property values are inherited from the invoking script, configure_java
cat - $TEMP <<eod >$1
com.cybermetrix.cyflex.specfiles.Units.fileName       $CYFLEX/units.dat
com.cybermetrix.cyflex.specfiles.PAMChannels.fileName $CYFLEX/channel.dat
com.cybermetrix.cyflex.specfiles.Variables.fileName   $SPECS/dump_labels.dat
com.cybermetrix.cyflex.specfiles.xmlBase              $CYFLEX_JAVA_HOME/specfilegui/xmlfiles/
com.cybermetrix.cyflex.specfiles.hardwarefiles        $SPECS/
com.cybermetrix.cyflex.specfiles.cal_tables           $CELL/tables/
com.cybermetrix.cyflex.specfiles.local_specs          $SPECS/
cyflex.home               $CYFLEX/
cyflex_java.home          $CYFLEX_JAVA_HOME/
cyflex.local_cell.cell    $CELL/
eod

# Restore ownership of original file
chown ${OWNER}:${GROUP} $1

# Clean up.
rm -f $TEMP
