# New Yaim Configuration and setup for D-Cache 1.6.6-X
# Maintained by Owen Synge on behalf of GridPP

# This file is a library for processing key value configuration files.


yaim_config_file_backup()
{
  RET="$1".`date +%y%m%d_%H%M%S`.old
  test -f "$1" && cp -p "$1" $RET
}

# takes file name as a parameter
# returns a temp file for manipulation
# see yaim_config_pool_manager_add_lines for example
yaim_config_file_update_prepare()
{
yaimlog DEBUG "function yaim_config_file_update_prepare start"
local managed_file
local md5sum_orig
local file2update

managed_file=$1
if [ -z ${managed_file} ] ; then
echo yaim_config_file_update_prepare called with no file
exit 1
fi
if [ ! -f ${managed_file} ] ; then
    touch ${managed_file}
fi
file2update=${managed_file}.${md5sum_orig}
md5sum_orig=$(md5sum ${managed_file} | cut -d" " -f1)
RET=${managed_file}.${md5sum_orig}
#echo cp ${managed_file} ${RET}
cp ${managed_file} ${RET}
yaimlog DEBUG "function yaim_config_file_update_prepare stop"
}


# takes file name as a parameter
# Gets the temp file, checks the checksum against the
# old file, if different update and atomicly update
# using mv functionality which on POSIX systems is atomic.
# returns 0 on no update
# returns 1 on update
# see yaim_config_pool_manager_add_lines for example
yaim_config_file_update_done()
{
yaimlog DEBUG "function yaim_config_file_update_done start"
local managed_file
local md5sum_orig
local file2update
local md5sum_new


managed_file=$1
if [ -z ${managed_file} ] ; then
echo yaim_config_file_update_done called with no file name
exit 1
fi

if [ ! -f ${managed_file} ] ; then
echo yaim_config_file_update_done called with no file that exists
echo filename=${managed_file}
exit 1
fi
md5sum_orig=$(md5sum ${managed_file} | cut -d" " -f1)
file2update=${managed_file}.${md5sum_orig}
md5sum_new=$(md5sum ${file2update} | cut -d" " -f1)
if [ "${md5sum_orig}" != "${md5sum_new}" ] ; then
    yaim_config_file_backup ${managed_file}
    mv ${file2update} ${managed_file}
else
    rm ${file2update}
fi
yaimlog DEBUG "function yaim_config_file_update_done stop"
if [ "${md5sum_orig}" == "${md5sum_new}" ] ; then
    return 0
else
    return 1
fi
}


yaim_config_file_get_value()
{
# Returns 0 on success
# Returns 2 if key not found
local FILE
local Key
local cursor
local CursorLine
local MatchLine
local AllCursors
local foundPotentialCursors
local lineNumBefore
local PreviousLine
local MatchLine
local RawCursorLine
FILE=$1
Key=$2
if [ ! -f ${FILE} ] ; then
    echo yaim_config_file_get_value called with no file, file=$FILE
    exit 1
fi
AllCursors=`grep -n "^[	 ]*${Key}[	 ]*=" $FILE | cut -d: -f1 `
if [ "${AllCursors}X" == "X" ] ; then
  RET=""
  return 2
fi
# Now iterate through all our matches 
# check the line before is not terminated with \
foundPotentialCursors=""
for acursor in $AllCursors
do
  let lineNumBefore="${acursor}-1"
  if [ "${lineNumBefore}" == "0" ] ; then
    foundPotentialCursors="${acursor} ${foundPotentialCursors}"
  else
    # Following bash convention ignore all content after "#"
    # including lines terminating in "\"
    PreviousLine=`sed "${lineNumBefore}q;d" $FILE | sed 's/#.*$//'`
    MatchLine="${PreviousLine%%"\\"}"
    if [ "${PreviousLine}" == "${MatchLine}" ] ; then
      foundPotentialCursors="${acursor} ${foundPotentialCursors}"
    fi
  fi
done
if [ "${foundPotentialCursors}X" == "X" ] ; then
  RET=""
  return 2
fi
# Since we reversed the order of the cursors while validating them
# We can process only first valid cursor
cursor=`echo ${foundPotentialCursors} | sed 's/ .*//'`

RawCursorLine=`sed "${cursor}q;d" $FILE | cut -s -d= -f2- `
CursorLine=`echo "${RawCursorLine}" | sed 's/#.*//'`
if [ "${RawCursorLine}" == "${CursorLine}" ] ; then
  # No comments on this line so check for terminating '\'
  MatchLine="${CursorLine%%"\\"}\\"
  RET="${CursorLine%%"\\"}"
  while [ "${CursorLine}" == "${MatchLine}" ] 
  do
    # While last line character is "\"
    let cursor+=1
    RawCursorLine=`sed "${cursor}q;d" $FILE`
    CursorLine=`echo "${RawCursorLine}" | sed 's/#.*//'`
    if [ "${RawCursorLine}" != "${CursorLine}" ] ; then
      # No comments on this line
      RET="${RET} ${CursorLine}"
      break
    fi
    MatchLine="${CursorLine%%"\\"}\\"
    RET="$RET ${CursorLine%%"\\"}"
  done
else
  # Comments on this line so no need to process "\"
  RET=${CursorLine}
fi
# Now after all the processing remove starting and termianting white space
RET=`echo $RET | sed 's/^[ 	]*\"\([^"]*\)\"[ 	]*$/\1/'`
}



yaim_config_file_set_value()
{
  local FILE
  local Key
  local Value
  local tmpfile 
  local AddedValue
  local line
  local CursorLine
  local linesWithKeys
  local cursor
  local MatchCursorLine
  local lastline
  # File to edit
  FILE="$1"
  # Key to set 
  Key="$2"
  # Value to Set
  Value="$3"
  # Use as Flag for adding value
  # 0 Not yet added
  # 1 Should add as soon as posible
  # 2 Already Added

  yaim_config_file_get_value "${FILE}" "${Key}"
  if [ "${RET}" == "${Value}" ] ; then
    return 0
  fi
  yaimlog DEBUG "function yaim_config_file_set_value start"
  AddedValue=0
  tmpfile=$FILE.backup.$$
  rm -f $tmpfile
  AllCursors=`grep -n  "^[	 ]*${Key}[	 ]*=" $FILE | cut -d: -f1 `
  if [ "${AllCursors}X" == "X" ] ; then
    RET=""
  fi
  # Now iterate through all our matches 
  # check the line before is not terminated with \
  foundPotentialCursors=""
  for acursor in $AllCursors
  do
    let lineNumBefore="${acursor}-1"
    if [ "${lineNumBefore}" == "0" ] ; then
      foundPotentialCursors="${acursor} ${foundPotentialCursors}"
    else
      # Following bash convention ignore all content after "#"
      # including lines terminating in "\"
      PreviousLine=`sed "${lineNumBefore}q;d" $FILE | sed 's/#.*$//'`
      MatchLine="${PreviousLine%%"\\"}"
      if [ "${PreviousLine}" == "${MatchLine}" ] ; then
        foundPotentialCursors="${acursor} ${foundPotentialCursors}"
      fi
    fi
  done
  if [ "${foundPotentialCursors}X" == "X" ] ; then
    # No Value already exists.
    lastLineCommented=`grep -n "^[\t# 	]*$Key=" $FILE | cut -d: -f1 `
    if [ "" == "$lastLineCommented" ] ; then
      # No commented out line exists
      cp $FILE $tmpfile
      echo "$Key=$Value" >> $tmpfile
      AddedValue=1
    else
      # Commented out line = $lastLineCommented        
      let cursor=$lastLineCommented
      CursorLine=$(sed "${cursor}q;d" $FILE)
      MatchCursorLine="${CursorLine%%"\\"}\\"
      while [ "${CursorLine}" == "${MatchCursorLine}" ]
      do
        let cursor+=1
        CursorLine=$(sed "${cursor}q;d" $FILE)
        MatchCursorLine="${CursorLine%%"\\"}\\"
      done
      sed "${cursor}q" $FILE >> $tmpfile
      echo "$Key=$Value" >> $tmpfile
      AddedValue=1
      line=`cat  $FILE | wc -l |  sed -e "s/ *//g"`
      let cursor+=1
      sed -n "${cursor},${line}p" $FILE >> $tmpfile
    fi
  else
    #linesCommented=`grep -n "^[\t# ]*$Key=" $FILE | cut -d: -f1`
    linesContinued=`grep -n "^[#	 ]*${Key}[	 ]*=" $FILE | cut -d: -f1 `
    #echo linesWithKeys=$linesWithKeys
    #echo linesContinued=$linesContinued
    #echo linesContinued=${linesContinued}
    let before_cursor='1'
    let Cursor='-1'
    linesProcessed="${linesContinued}"
    while [ -n "${linesProcessed}" ] ; do
      let Head=`echo "${linesProcessed}" | sed q`
      linesProcessed=`echo "${linesProcessed}" | sed '1,1d'`
      if [ ${Head} -ge ${Cursor} ] ; then
        let Cursor=${Head}
        let lineNumBeforeHead="${Cursor}-1"
        # check this line is not a continuation of the last line
        if [ ${lineNumBeforeHead} -ge 1 ] ; then
          RawBeforeCursorLine=`sed "${lineNumBeforeHead}q;d" $FILE | sed 's/#.*//'`
          MatchLine="${RawBeforeCursorLine%%"\\"}\\"
          if [ "${MatchLine}" == "${RawBeforeCursorLine}" ] ; then
            continue
          fi
        fi
        let gap=${lineNumBeforeHead}-$before_cursor
        # assuming that this line is valid.
        # add preseading contnet 
        # echo gap=$gap
        if [ ${gap} -gt -1 ] ; then
          sed -n "${before_cursor},${lineNumBeforeHead}p" $FILE >> $tmpfile
        fi
        let before_cursor=${Cursor}
        # find the end of this block
        CursorLine=$(sed "${Cursor}q;d" $FILE)
        MatchLine="${CursorLine%%"\\"}\\"
        while [ "${CursorLine}" == "${MatchLine}" ] 
        do
          # While last line character is "\"
          let Cursor+=1
          RawCursorLine=`sed "${Cursor}q;d" $FILE`
          CursorLine=`echo "${RawCursorLine}" | sed 's/#.*//'`
          if [ "${RawCursorLine}" != "${CursorLine}" ] ; then
            # No comments on this line
            RET="${RET} ${CursorLine}"
            break
          fi
          MatchLine="${CursorLine%%"\\"}\\"
          RET="$RET ${CursorLine%%"\\"}"
        done
        # add commented block
        let gap=${Cursor}-${before_cursor}
        #echo CommentGap=$gap
        if [ ${gap} -gt -1 ] ; then
          sed -n "${before_cursor},${Cursor}p" $FILE | sed -e 's/^# *//' | sed -e 's/^/# /' >> $tmpfile
        fi
        let Cursor=${Cursor}+1
	      let before_cursor=${Cursor}  
      fi
      if [ -z "${linesProcessed}" ] ; then
        echo "$Key=${Value}" >> $tmpfile
        AddedValue=1
      fi
    done
    let lastline=$(cat $FILE | wc -l |  sed -e "s/ *//g")
    let gap=${lastline}-${Cursor}
    #echo finalGap=$gap
    if [ ${gap} -ge 0 ] ; then
      sed -n "${before_cursor},${lastline}p" $FILE >> $tmpfile
    fi
    if [ "$AddedValue" == "0" ] ; then
      echo "$Key=${Value}" >> $tmpfile
    fi    
fi
mv $tmpfile $FILE
yaimlog DEBUG "function yaim_config_file_set_value stop"
}


# Comments out the key and value if already set
yaim_config_file_remove_value()
{
    yaimlog DEBUG "function yaim_config_file_remove_value start"
    local FILE
    local Key
    local SED
    FILE=$1
    Key=$2
    tmpfile=$FILE.bak
    if [ ! -f ${FILE} ] ; then
        echo yaim_config_file_remove_value called with no file
        exit 1
    fi

    sed -e  "s/^${Key}=/#${Key}=/"  $FILE > $tmpfile
    mv $tmpfile $FILE
    yaimlog DEBUG "function yaim_config_file_remove_value stop"
}
