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

ARGS=();
while [ $# -gt 0 ] ; do
  case "$1" in
  -q) shift;
      QUERY=$1;;
  -e) shift;
      QUERY=$1;;
  -f) shift;
      FILE=$1;;
   *) ARGS+=($1);;
  esac
  shift
done

bin=`dirname "${BASH_SOURCE-$0}"`
bin=`cd "$bin">/dev/null; pwd`

. "$bin"/drill-config.sh

# Override SQLLine's default initial transaction isolation level.  (SQLLine
# sets an initial level instead of leaving it at whatever the Driver's default
# is.) 
# Put our property specification before previous value of DRILL_SHELL_JAVA_OPTS
# so that it can still be overridden via DRILL_SHELL_JAVA_OPTS.
#
# This is not currently needed as the new SQLLine we are using doesn't isolate.
# DRILL_SHELL_JAVA_OPTS="-Dsqlline.isolation=TRANSACTION_NONE $DRILL_SHELL_JAVA_OPTS"

DRILL_SHELL_JAVA_OPTS="$DRILL_SHELL_JAVA_OPTS -Dlog.path=$DRILL_LOG_DIR/sqlline.log -Dlog.query.path=$DRILL_LOG_DIR/sqlline_queries.json"

if ! $is_cygwin; then
  DRILL_SHELL_OPTS="$DRILL_SHELL_OPTS --color=true"
fi

if [ -n "$QUERY" ] ; then
  echo $QUERY | exec "$JAVA" $DRILL_SHELL_JAVA_OPTS $DRILL_JAVA_OPTS -cp $CP sqlline.SqlLine -d org.apache.drill.jdbc.Driver  --maxWidth=10000 "${ARGS[@]}"
elif [ -n "$FILE" ] ; then
  exec "$JAVA" $DRILL_SHELL_JAVA_OPTS $DRILL_JAVA_OPTS -cp $CP sqlline.SqlLine -d org.apache.drill.jdbc.Driver  --maxWidth=10000 "${ARGS[@]}" --run=$FILE
else
  exec "$JAVA" $DRILL_SHELL_JAVA_OPTS $DRILL_JAVA_OPTS -cp $CP sqlline.SqlLine -d org.apache.drill.jdbc.Driver --maxWidth=10000 $DRILL_SHELL_OPTS "${ARGS[@]}"
fi
