#!/usr/bin/env bash
#clear
#export PS4='\e[90m+${LINENO} in ${#BASH_SOURCE[@]}>${FUNCNAME[0]}:${BASH_SOURCE[@]##*/} \e[0m'
#set -x

#echo "starting: $0 <LOG_LEVEL=$1>"


replace.by()
{
  REPLACE_EXPRESSION="$1"
  shift
  if [[ $FILE == *.new ]]; then
    awk -v place="$SEARCH_EXPRESSION" -v replace="$REPLACE_EXPRESSION" '{sub(place,replace); print}' $FILE > $FILE.new
    replace commit "$FILE"
    replace cleanup "$FILE"
  else
    awk -v place="$SEARCH_EXPRESSION" -v replace="$REPLACE_EXPRESSION" '{sub(place,replace); print}' $FILE > $FILE.new
  fi
  RETURN=$1
}

# This function reads text from stdin, and substitutes a *BLOCK* with the contents from a FILE, and outputs to stdout
# The BLOCK is indicated with BLOCK_StartRegexp and BLOCK_EndRegexp
#
# Usage:
#    seq 100 110 | substitute_BLOCK_with_FILEcontents '^102' '^104' /tmp/FileWithContents > /tmp/result.txt
replace.by.file() 
{
  local BLOCK_StartRegexp="${1}"
  local BLOCK_EndRegexp="${2}"
  local FILE="${3}"
  sed -e "/${BLOCK_EndRegexp}/a ___tmpMark___" -e "/${BLOCK_StartRegexp}/,/${BLOCK_EndRegexp}/d" | sed -e "/___tmpMark___/r ${FILE}" -e '/___tmpMark___/d'
}


replace.within()
{
  FILE="$1"
  shift
  SEARCH_EXPRESSION=$1
  shift
  RETURN=$1

}
replace.diff()
{
 FILE="$1"
 diff "$FILE" "$FILE.new"
}

replace.commit()
{
  FILE="$1"
  check file "$FILE.bak" exists call rm "$FILE.bak"
  chmod -x "$FILE"
  mv "$FILE" "$FILE.bak"
  mv "$FILE.new" "$FILE"
  chmod +x "$FILE"
}

replace.rollback()
{
  FILE="$1"
  if [ -f "$FILE.new" ]; then
    rm "$FILE"
  else
    mv "$FILE" "$FILE.new"
    mv "$FILE.bak" "$FILE"
    chmod +x "$FILE"
  fi

}

replace.cleanup()
{
  if [ -n "$1" ]; then
    if check file $1.bak exists
    then
      rm $1.bak
    fi

    if check file $OOSH_DIR/$1.new exists
    then
      rm $1.new
    fi
  else
    rm $OOSH_DIR/*.bak
    rm $OOSH_DIR/*.new
  fi
}




replace.usage()
{
  local this=${0##*/}
  echo "You started 
$0

  Usage:
  $this: in filename expressin by relpaceExpression

      usage             prints this dialog while it will print the status when there are no parameters          
      v                 print version information
      commit            filename
      rollback          filename
      diff              filename

      by        <replace expression> 
      by.file
      within        <filename> <search expression>

      cleanup

  
  Examples
    $this init

    replace within some.File.txt \"hello\" by \"servus\"
    replace diff some.File.txt
    replace commit some.File.txt

  "
}

replace.start()
{
  #echo "sourcing init"
  source this

  # if [ -z "$1" ]; then
  #   status.discover "$@"
  #   return 0
  # fi

  this.start "$@"
}

replace.start "$@"

