#!/bin/bash
#
# pre-commit hook script that activates the Sesame serializer to serialize any OWL files in a standard format just before
# they are committed to the (local) Github repository.
#
# Called by "git commit" with no arguments. This hook can stop the commit when it encounters an error.
#
# To enable this hook, rename this file to "pre-commit" and save it in the directory <your git clone root>/.git/hooksj
#

# Customized by the git user
export JAVA_HOME="/c/Program Files (x86)/Java/jre1.8.0_101"

#
# Redirect all output generated by this script to stderr.
#
exec 1>&2

log_prefix="rdf-toolkit: sesame-serializer: "

function log() {
  echo "${log_prefix}$@"
}

function log_error() {
  log "ERROR: $@"
}

log "This is the pre-commit hook"

java_exe=""
base_dir=""

function findJava() {

  whichJava=""

  java_home=""

  if [ "${RDF_TOOLKIT_JAVA_HOME}" != "" ] ; then
    java_home="${RDF_TOOLKIT_JAVA_HOME}"
  fi
  if [ "${JAVA_HOME}" != "" ] ; then
    java_home="${JAVA_HOME}"
  fi
  if [ "${java_home}" == "" ] ; then
      log_error A-$JAVA_HOME
    log_error "Please set RDF_TOOLKIT_JAVA_HOME or JAVA_HOME to point to a Java 7 or later installation."
    return 1
  fi
  java_home=${java_home/C:\\/\/c\/}
  java_home=${java_home//\\/\/}
  log "java_home =" ${java_home}

  if [ -x "${java_home}/bin/java" ] ; then
    whichJava="${java_home}/bin/java"
  else
    log_error "Could not find java in your RDF_TOOLKIT_JAVA_HOME or JAVA_HOME: ${java_home}"
    log_error "Please set RDF_TOOLKIT_JAVA_HOME or JAVA_HOME to point to a Java 7 or later installation."
    return 1
  fi
  log "whichJava =" $whichJava

  local versionJava=$( "$whichJava" -version 2>&1 | head -n 1 | cut -d \"  -f 2 )
  log "versionJava = " $versionJava

  set -- ${versionJava//./ }

  local java_major=$1
  local java_minor=$2

  if [ $java_major -eq 1 -a $java_minor -gt 7 ] ; then
  	:
  else
    log_error "You are using Java $java_major.$java_minor whereas the Sesame serializer requires Java 1.7 or higher"
    return 2
  fi

  java_exe="${whichJava}"

  return 0
}

function findSerializerJar() {

  if [ "${RDF_TOOLKIT_JAR}" == "" ] ; then
    RDF_TOOLKIT_JAR="$PWD/.git/hooks/rdf-toolkit.jar"
  fi

  if [ -f "${RDF_TOOLKIT_JAR}" ] ; then
  	log "Found rdf-toolkit: ${RDF_TOOLKIT_JAR}"
  	return 0
  fi

  log_error "Could not find the rdf-toolkit JAR, please reinstall. Set RDF_TOOLKIT_JAR or put rdf-toolkit.jar in the .git/hook directory."

  return 1
}

# function findBaseDir() {

#   #
#   # For now, we just take the top level directory of the current git repository as the base dir
#   #
#   base_dir=$(git rev-parse --show-toplevel)

#   if [ "${base_dir}" == "" ] ; then
#     log_error "Could not find base directory"
#     return 1
#   fi
#   if [ ! -d "${base_dir}" ] ; then
#     log_error "Could not find base directory"
#     return 1
#   fi

#   return 0
# }

function showFilesThatAreInCommit() {

  git diff --cached --name-only
}

function serialize() {

  local file="$1"
  if [ -f "$file" ] ; then
    local extension="${file##*.}"
    local target_format="rdf-xml"
    if [ -d "$TEMP" ] ; then
      local logcfg="$TEMP/sesame-serializer-log"
    else
      if [ -d "/tmp/" ] ; then
        local logcfg="/tmp/sesame-serializer-log"
      fi
    fi
    
    case ${extension} in
    	rdf)
    	    target_format="rdf-xml"
     	  ;;
	ttl)
    	    target_format="turtle"
	  ;;
      *)
        log "Skipping unsupported file $file"
        return 0
    esac

    if [[ $file =~ .*About.* ]] ;  then 
        log "Skipping unsupported file $file"
        return 0
    fi

    if [[ $file =~ .*OWL.* ]] ;  then 
        log "Skipping unsupported file $file"
        return 0
    fi


    if [ -x "$logcfg" ] ; then
      cat > ${logcfg} << __log_config__
[logger_root]
level: error
handlers: h1

[handler_h1]
level: error
class: ConsoleHandler
formatter: f1

[formatter_f1]
class: DefaultFormatter
format: (%l) %t
__log_config__
    fi

    log "Launching the sesame-serializer with --source ${file}"

    set -x
    "${java_exe}" -Xmx1g "-Dorg.clapper.avsl.config=${logcfg}" -cp "${RDF_TOOLKIT_JAR}" org.edmcouncil.rdf_toolkit.RdfFormatter \
      --source "${file}" \
      --target "${file}" \
      --target-format ${target_format} \
      --use-dtd-subset -ibn -ibu \
      -sdt implicit 
    rc=$?
    set +x

    if [ -x "$logcfg" ] ; then
      rm -f "${logcfg}" >/dev/null 2>&1
    fi

    sed '/rdfs:label/!b;:a;/datatype="&xsd;string"/bb;$!{N;ba};:b;s/rdfs:label.*datatype=".....string"/rdfs:label/' "${file}" > temp
    rm "${file}"
    mv temp "${file}"

    if [ ${rc} -eq 0 ] ; then
      log "Re-adding potentially re-serialized file to git staging area: ${file}"
      git add --update "${file}"
    else
      log_error "sesame-serializer ended with error code ${rc}"
    fi
    return ${rc}
  else
    return 0
  fi

}

function serialize_all() {

  #echo "Checking the following files:"
  #showFilesThatAreInCommit

  for fileToBeCommitted in $(git diff --cached --name-only) ; do
    if ! serialize "$fileToBeCommitted" ; then
      return 1
    fi
  done

  return 0
}

function main() {

	findJava || return 1
	findSerializerJar || return 2
#	findBaseDir || return 3
  serialize_all
}

main $*
rc=$?
if [ $rc -gt 0 ] ; then
  log_error "Could not commit your files"
fi
exit $rc
