#!/usr/bin/env bash

## Licensed to the Apache Software Foundation (ASF) under one
## or more contributor license agreements.  See the NOTICE file
## distributed with this work for additional information
## regarding copyright ownership.  The ASF licenses this file
## to you under the Apache License, Version 2.0 (the
## "License"); you may not use this file except in compliance
## with the License.  You may obtain a copy of the License at
##
##     http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.

export PKG=tdb.xloader
export TDB_NAME=TDB1
export TDB_CMD=tdb1.xloader

## In common with tdb1.xloader
## Minimal needed to setup script execution.

function resolveLink() {
  local NAME=$1

  if [ -L "$NAME" ]; then
    case "$OSTYPE" in
      darwin*|bsd*)
        # BSD style readlink behaves differently to GNU readlink
        # Have to manually follow links
        while [ -L "$NAME" ]; do
          NAME=$(readlink -- "$NAME")
        done
        ;;
      *)
        # Assuming standard GNU readlink with -f for
        # canonicalize
        NAME=$(readlink -f -- "$NAME")
        ;;
    esac
  fi

  echo "$NAME"
}

# If JENA_HOME is empty
if [ -z "$JENA_HOME" ]; then
  SCRIPT="$0"
  # Catch common issue: script has been symlinked
  if [ -L "$SCRIPT" ]; then
    SCRIPT=$(resolveLink "$0")
    # If link is relative
    case "$SCRIPT" in
      /*)
        # Already absolute
        ;;
      *)
        # Relative, make absolute
        SCRIPT=$( dirname "$0" )/$SCRIPT
        ;;
    esac
  fi

  # Work out root from script location
  JENA_HOME="$( cd "$( dirname "$SCRIPT" )/.." && pwd )"
  export JENA_HOME
fi

# If JENA_HOME is a symbolic link need to resolve
if [ -L "${JENA_HOME}" ]; then
  JENA_HOME=$(resolveLink "$JENA_HOME")
  # If link is relative
  case "$JENA_HOME" in
    /*)
      # Already absolute
      ;;
    *)
      # Relative, make absolute
      JENA_HOME=$(dirname "$JENA_HOME")
      ;;
  esac
  export JENA_HOME
  #echo "Resolved symbolic links for JENA_HOME to $JENA_HOME"
fi

export LOADER_SCRIPTS="${LOADER_SCRIPTS:-${JENA_HOME}/bin}"

if [ -e "${LOADER_SCRIPTS}/xload-common" ]; then
  # Can source common functions
  source "${LOADER_SCRIPTS}/xload-common"
else
    echo "${LOADER_SCRIPTS}/xload-common"
  echo "Unable to locate common functions script xload-common"
  exit 1
fi

exec "${LOADER_SCRIPTS}/xload-main" "$@"
