#!/bin/bash -e
#
# Setup ODBC driver for unixODBC
#
set -o pipefail

cat << EOS
Prerequisites:
- install unixODBC 
    - RedHat:  sudo yum install unixODBC
        - this package contains isql which can connect to Snowflake DB.
- adjust parameters in this file if needed
- make sure you are running this file from its local directory
- run this script as '$0'

EOS

# replace odbc patch in odbc configurations files

CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

echo "unset ODBCINI and ODBCINSTINI"
unset ODBCINI
unset ODBCINSTINI

SIMBAINI=$CURRENT_DIR/conf/unixodbc.snowflake.ini
perl -i -pe 's|(ErrorMessagesPath=).*(/ErrorMessages/)|$1'$CURRENT_DIR'$2|;' $SIMBAINI
perl -i -pe 's|(LogPath=).*|$1'$CURRENT_DIR/log'|;' $SIMBAINI

# copy simba ini file to driver directory
cp "$SIMBAINI" "$CURRENT_DIR"/lib/simba.snowflake.ini
cat <<CACERT >> "$CURRENT_DIR"/lib/simba.snowflake.ini
CABundleFile=$CURRENT_DIR/lib/cacert.pem
CACERT

ODBC_INI_ROOT_DIR=${ODBC_INI_ROOT_DIR:-/etc}
if ! grep -P "^\[SnowflakeDSIIDriver" $ODBC_INI_ROOT_DIR/odbcinst.ini > /dev/null; then
  echo "Adding driver info to $ODBC_INI_ROOT_DIR/odbcinst.ini..."
  cat >> $ODBC_INI_ROOT_DIR/odbcinst.ini << ODBCINST_INI

[SnowflakeDSIIDriver]
APILevel=1
ConnectFunctions=YYY
Description=Snowflake DSII
Driver=$CURRENT_DIR/lib/libSnowflake.so
DriverODBCVer=03.52
SQLLevel=1
ODBCINST_INI
else
    echo "SnowflakeDSIIDriver is already in $ODBC_INI_ROOT_DIR/odbcinst.ini."
fi

if ! grep -P "^\[snowflake" $ODBC_INI_ROOT_DIR/odbc.ini > /dev/null; then
    echo "Adding connect info to $ODBC_INI_ROOT_DIR/odbc.ini..."
    cat >> $ODBC_INI_ROOT_DIR/odbc.ini <<ODBC_INI

[snowflake]
Description=SnowflakeDB
Driver=SnowflakeDSIIDriver
Locale=en-US
SERVER=SF_ACCOUNT.snowflakecomputing.com
PORT=443
SSL=on
ACCOUNT=SF_ACCOUNT
ODBC_INI
else
    echo "DSN snowflake is already in $ODBC_INI_ROOT_DIR/odbc.ini"
fi

mkdir -p $CURRENT_DIR/log

cat << end
- Setup sucessfully!
- Steps to do after running this script
  1. Replace SF_ACCOUNT with the account name in /etc/odbc.ini
  2. (optional) Specify username and password in /etc/odbc.ini
  3. Make sure current users have write permission to the log 
     directory.
end
