#!/bin/bash
# login with root
# maily for private
# 0 4 * * * schemaBackup.sh
#docker, of1 hana: ./schemaBackup.sh -SCHEMA_PASSWD EPM_user_2017 -CONN_ADDR of1:30115 -DOCKER_DEPLOY -DATA_DIR /var/hanadata -SCHEMA_NAME LEONTESTCONS
#ecs: hanaDev ./schemaBackup.sh -SCHEMA_PASSWD EPM_user_2017 -CONN_ADDR 192.168.124.204:30115 -DATA_DIR /data_disk1/HANA -SCHEMA_NAME LEONEMPTY
# eg,ashang
# 0 1 * * * /EPM2/HANA/schemaBackupPrivate.sh -SCHEMA_PASSWD aShang_2022 -DATA_DIR /EPM2/HANA -SCHEMA_NAME ASHANG -HDBSQL_BIN /usr/sap/EPM/HDB01/exe/hdbsql
echo 'begin schema backup for hana'
schemaName='EPM'
hdbsqlBin='/usr/sap/hdbclient/hdbsql'
connAddr='127.0.0.1:30115'
schemaPass='EPM_user_2022'
while [ $# -gt 0 ]; do
  COMMAND=$1
  case $COMMAND in   
    -SCHEMA_PASSWD)
      schemaPass=$2
      shift 2
      ;;
    -CONN_ADDR)
      connAddr=$2
      shift 2
      ;;
    -HDBSQL_BIN)
      hdbsqlBin=$2
      shift 2
      ;;
    -DOCKER_DEPLOY)
      dockerDeploy=true
      shift 1
      ;; 
    -DATA_DIR) #in docker , corresponding to /hana/mounts
      dataDir=$2
      shift 2
      ;;
    -SCHEMA_NAME)
      schemaName=$2
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

OUTPUT="$dataDir/SCHEMA_BACKUP"
dateStr=`date '+%F_%H'`
echo "Date: $dateStr"

echo "exporting $schemaName"
if test -e $OUTPUT
then
    echo 'schema dir exist'
else
    echo 'schema dir does not exist, create it'
    mkdir -p $OUTPUT
fi
chmod a+w $OUTPUT

if [ $dockerDeploy ]
then
  echo 'docker'
  $hdbsqlBin -n $connAddr -u $schemaName -p $schemaPass "EXPORT $schemaName.\"*\" AS BINARY INTO '/hana/mounts/SCHEMA_BACKUP/$dateStr' WITH REPLACE"
else
  echo 'ecs'
  $hdbsqlBin -n $connAddr -u $schemaName -p $schemaPass "EXPORT $schemaName.\"*\" AS BINARY INTO '${OUTPUT}/$dateStr' WITH REPLACE"
fi
if [ $? != "0" ]; then
  echo "exporting fails"
else
  echo "exporting success"
fi
echo "export end"