#!/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

  # Use perl instead of awk — BSD awk cannot handle newlines in -v strings
  # Export vars so perl can access them via %ENV
  export SEARCH_EXPRESSION
  export REPLACE_EXPRESSION

  if [[ $FILE == *.new ]]; then
    perl -pe 's/\Q$ENV{SEARCH_EXPRESSION}\E/$ENV{REPLACE_EXPRESSION}/' "$FILE" > "$FILE.new"
    replace commit "$FILE"
    replace cleanup "$FILE"
  else
    perl -pe 's/\Q$ENV{SEARCH_EXPRESSION}\E/$ENV{REPLACE_EXPRESSION}/' "$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"
  # Use standard bash test - works on case-insensitive APFS
  [ -f "$FILE.bak" ] && 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
    # Use standard bash test - works on case-insensitive APFS
    [ -f "$1.bak" ] && rm "$1.bak"
    [ -f "$1.new" ] && rm "$1.new"
  else
    rm -f $OOSH_DIR/*.bak 2>/dev/null
    rm -f $OOSH_DIR/*.new 2>/dev/null
  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 "$@"

