#!/bin/sh

echo "Welcome to Reflex set_memory utility"
echo " This utility allows you to set the Java memory used by Reflex"
echo " Hints: If the machine has 2Gb, settting default to 1024 will allow "
echo "        reflex to run stable even for complex workflows."
echo "        Do not set max to more than 1536 on 32 bit machine."
echo "        If user has limited memory:  setting max value to 256 is enough"
echo "        for simple workflows (UVES), and will leave enough memory for"
echo "        esorex to run."

ESOREFLEX_BASE=$(dirname $0)/../..
if command -v perl > /dev/null ; then
    ESOREFLEX_BASE=$(perl -MCwd=realpath -e "print realpath '$ESOREFLEX_BASE'")
else
    ESOREFLEX_BASE=$(cd "$ESOREFLEX_BASE" ; pwd)
fi

memory_file=$ESOREFLEX_BASE/build-area/settings/memory.xml

min_line=`grep min "$memory_file"`
isnumber=0
while [ $isnumber -eq 0 ]
do
  printf "Minimum amount of memory (in Megabytes) for Reflex: [unchanged] " 
  read -r memory_min
  case $memory_min in
    '') printf "Minimum memory setting not changed\n"; isnumber=999 ;;
    *[!0-9]*) printf "Cannot understand number\n"; isnumber=0 ;;
    *)  isnumber=1 ; min_line=`echo \<entry key=\"min\"\>${memory_min}m\</entry\>`;;
  esac
done

max_line=`grep max "$memory_file"`
isnumber=0
while [ $isnumber -eq 0 ]
do
  printf "Maximum amount of memory (in Megabytes) for Reflex: [unchanged] " 
  read -r memory_max
  case $memory_max in
    '') printf "Maximum memory setting not changed\n"; isnumber=999 ;;
    *[!0-9]*) printf "Cannot understand number\n"; isnumber=0 ;;
    *)  isnumber=1 ; max_line=`echo \<entry key=\"max\"\>${memory_max}m\</entry\>`;;
  esac
done

write_config () {
  cat <<EOF2
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Default Memory Properties</comment>
$max_line
$min_line
</properties>
EOF2
}

# Test if we have write access to the file. If not then use sudo.
echo "" 2> /dev/null >> "$memory_file"
if test "$?" -eq 0 ; then
  write_config > "$memory_file" || exit 1
else
  # Copy via a temp file to avoid problems with redirections and sudo.
  temp_file=`mktemp /tmp/tmp_XXXXXXXX` || exit 1
  write_config > "$temp_file" || exit 1
  sudo cp "$temp_file" "$memory_file" || exit 1
  rm -f "$temp_file"
fi

echo " Memory config set to:"
echo $max_line
echo $min_line
