#!/bin/sh

# TODO: (m.toumanov@antitricks.ru)
#     1) Проверка, куда ставится oracle: oracle/oracle или /oracle/lib/oracle
#     2) Что-то решить с фалйами include, которые не ставятся, а они нужны для сборки cx-Oracle для Django
#     3) Переместить окружжение в /etc/profile

if [ `whoami` != 'root' ]; then
    echo "Run under 'root' user only"
    exit
fi

ORACLE_INSTANTCLIENT_MAJOR='12.1'
ORACLE_INSTANTCLIENT_VERSION='12.1.0.2.0'
ORACLE='/usr/local/oracle'
ORACLE_HOME=$ORACLE/oracle/$ORACLE_INSTANTCLIENT_MAJOR/client64
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib
C_INCLUDE_PATH=$C_INCLUDE_PATH:$ORACLE/include/oracle/$ORACLE_INSTANTCLIENT_MAJOR/client64
LC_ALL='C.UTF-8'

BASIC_RPM='oracle-instantclient'$ORACLE_INSTANTCLIENT_MAJOR'-basic-'$ORACLE_INSTANTCLIENT_VERSION'-1.x86_64.rpm'
DEVEL_RPM='oracle-instantclient'$ORACLE_INSTANTCLIENT_MAJOR'-devel-'$ORACLE_INSTANTCLIENT_VERSION'-1.x86_64.rpm'

TMP_DIR='/usr/local/src'

echo "\nStep 1: Prepare apt"
apt-get update && apt-get install -y curl rpm2cpio cpio libaio1 libaio-dev

for DIR in $ORACLE $TMP_DIR; do
    if [ ! -d $TMP_PATH ]; then
        mkdir $TMP_DIR
    fi
done

echo "\nStep 2: Download Oracle RPMs and unpack"
cd $TMP_DIR

for RPM in $BASIC_RPM $DEVEL_RPM; do
    curl -L https://github.com/sergeymakinen/docker-oracle-instant-client/raw/assets/$RPM -o ./$RPM
    rpm2cpio ./$BASIC_RPM | cpio -i -d -v
done

echo "\nStep 3: Copy data to workplace"
cp -vr $TMP_DIR/usr/* $ORACLE

echo "\nStep 4: make .so symlinks"
cd $ORACLE_HOME
for SO in libocci libclntsh libclntshcore; do
  ln -vfs $SO.so.$ORACLE_INSTANTCLIENT_MAJOR $SO.so
done

echo "\nStep 5: Update ld configs"
if [ `cat /etc/ld.so.conf.d/oracle.conf | grep '/usr/local/oracle/oracle/12.1/client64/lib' | wc -l` -eq 0 ]; then
   echo "$ORACLE_HOME/lib" >> /etc/ld.so.conf.d/oracle.conf && chmod o+r /etc/ld.so.conf.d/oracle.conf && ldconfig
fi
echo "Content of /etc/ld.so.conf.d/oracle.conf:"
cat /etc/ld.so.conf.d/oracle.conf

echo "\nStep 6: Environment"
echo "\nSet this OS environment virables before run your project"
echo "= 8< ===\n"
echo "export ORACLE='$ORACLE'"
echo "export ORACLE_HOME='$ORACLE_HOME'"
echo "export DYLD_LIBRARY_PATH='$ORACLE_HOME'"
echo "export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:$ORACLE_HOME/lib'"
echo "export C_INCLUDE_PATH='$C_INCLUDE_PATH:$ORACLE_HOME'"
echo "\n=== >8 ="
