#!/bin/bash
CWD=$(cd `dirname $0`;pwd)
cd "${CWD}"
source _env
export HOST_IP_MODE=1
export TELEMETRY_REPORTER="docker_${OB_CLUSTER_NAME}"

STAMP="$(date +%s)"
STEP=1
PHASE_START_TIME=0

function timediff() {
  start_time=$1
  end_time=$2

  start_s=${start_time%.*}
  start_nanos=${start_time#*.}
  end_s=${end_time%.*}
  end_nanos=${end_time#*.}

  if [ "$end_nanos" -lt "$start_nanos" ];then
      end_s=$(( 10#$end_s - 1 ))
      end_nanos=$(( 10#$end_nanos + 10**9 ))
  fi

  time=$(( 10#$end_s - 10#$start_s )).`printf "%03d\n" $(( (10#$end_nanos - 10#$start_nanos)/10**6 ))`
  echo $time
}

function print_start_phase() {
  echo "///////////////////////         STEP ${STEP}: $@         ///////////////////////"
  STEP=$[ ${STEP} + 1 ]
  PHASE_START_TIME=$(date +%s.%N)
}

function print_end_phase() {
  cur_time=$(date +%s.%N)
  echo "/////////////////////// phase end: $(timediff ${PHASE_START_TIME} ${cur_time}) s ///////////////////////"
}

function is_true() {
  value=$1
  # convert value to upper case string(can work in bash 4.x)
  value=${value^^}
  
  if [ "x${value}" == "xNO" ] || [ "x${value}" == "xFALSE" ] || [ "x${value}" == "x0" ]; then
    return 1
  fi
  return 0
}

function get_mode() {
  if test -z ${MODE}
  then
    MODE="MINI"
  fi
  MODE=${MODE^^}
}

function exit_while_error() {
  if test -z ${EXIT_WHILE_ERROR}
  then
    return 0 
  fi

  return `is_true ${EXIT_WHILE_ERROR}`
}

function fastboot() {
  if test -z ${FASTBOOT}
  then
    return 0
  fi

  return `is_true ${FASTBOOT}`
}

function remove_disk_check_logic_in_obd() {
  # make sure obd copy the plugin code
  obd cluster list
  start_check_files=('/root/.obd/plugins/oceanbase/3.1.0/start_check.py' '/root/.obd/plugins/oceanbase/4.0.0.0/start_check.py')
  for start_check_file in ${start_check_files[@]}
  do
    sed -i "s/critical('(%s) %s not enough disk space\. (Avail/alert('(%s) %s not enough disk space\. (Avail/g" $start_check_file
    sed -i "s/critical(EC_OBSERVER_NOT_ENOUGH_DISK_4_CLOG/alert(EC_OBSERVER_NOT_ENOUGH_DISK_4_CLOG/g" $start_check_file
  done
}

function run_custom_scripts {
  INIT_SCRIPTS_ROOT="${1}";

  # Check whether parameter has been passed on
  if [ -z "${INIT_SCRIPTS_ROOT}" ]; then
    echo "No INIT_SCRIPTS_ROOT passed on, no scripts will be run.";
    return;
  fi;

  # Execute custom provided files (only if directory exists and has files in it)
  if [ -d "${INIT_SCRIPTS_ROOT}" ] && [ -n "$(ls -A "${INIT_SCRIPTS_ROOT}")" ]; then
    echo -e "Executing user defined scripts..."
    run_custom_scripts_recursive ${INIT_SCRIPTS_ROOT}
    echo -e "DONE: Executing user defined scripts.\n"
  fi;
}

function run_custom_scripts_recursive {
  local f
  for f in "${1}"/*; do
    echo -e "running ${f} ...";
    obclient -h127.1 -uroot@${OB_TENANT_NAME} -A -P${OB_MYSQL_PORT} < ${f}
    echo "DONE: running ${f}";
  done
}

function deploy_failed {
  echo "deploy failed!"
  if exit_while_error
  then
    exit 1
  else
    echo "Please check the log file ${OB_HOME_PATH}/log/observer.log"
  fi
}

function cleanup() {
  obd cluster stop $OB_CLUSTER_NAME
  exit 0
}

trap 'cleanup' SIGTERM

# We should decide whether the observer's data exists and
# whether the obd has the information of the cluster

if [ -f "$HOME/.obd/cluster/${OB_CLUSTER_NAME}/config.yaml" ]; then
  echo "find obd deploy information, skip configuring..." 
  echo "start ob cluster ..."
  obd cluster start $OB_CLUSTER_NAME

else # nothing here, bootstrap
  print_start_phase "Config Generation"
  TMPFILE="boot.${STAMP}.yaml"

  get_mode
  if [ "x${MODE}" == "xNORMAL" ]; then
    echo "oceanbase-ce docker in normal mode"
    cp -f boot-tmp.yaml $TMPFILE
  elif [ "x${MODE}" == "xMINI" ]; then
    echo "oceanbase-ce docker in mini mode"
    cp -f boot-mini-tmp.yaml $TMPFILE
  elif [ "x${MODE}" == "xSLIM" ]; then
    echo "oceanbase-ce docker in slim mode"
    cp -f boot-mini-tmp.yaml $TMPFILE
  else
    cp -f boot-mini-tmp.yaml $TMPFILE
  fi

  if [ "x${MODE}" != "xSLIM" ]; then
    cat obagent.yaml >> $TMPFILE
  fi

  if [ "x${MODE}" == "xSLIM" ]; then
    cat ob-configserver.yaml >> $TMPFILE
  fi
  
  sed -i "s|@OB_SERVER_IP@|${OB_SERVER_IP}|g" $TMPFILE
  sed -i "s|@OB_HOME_PATH@|${OB_HOME_PATH}|g" $TMPFILE
  sed -i "s|@OB_MYSQL_PORT@|${OB_MYSQL_PORT}|g" $TMPFILE
  sed -i "s|@OB_RPC_PORT@|${OB_RPC_PORT}|g" $TMPFILE
  sed -i "s|@OB_CLUSTER_NAME@|${OB_CLUSTER_NAME}|g" $TMPFILE
  sed -i "s|@OB_MEMORY_LIMIT@|${OB_MEMORY_LIMIT}|g" $TMPFILE
  sed -i "s|@OB_SYSTEM_MEMORY@|${OB_SYSTEM_MEMORY}|g" $TMPFILE
  sed -i "s|@OB_DATAFILE_SIZE@|${OB_DATAFILE_SIZE}|g" $TMPFILE
  sed -i "s|@OB_LOG_DISK_SIZE@|${OB_LOG_DISK_SIZE}|g" $TMPFILE
  sed -i "s|@OB_ROOT_PASSWORD@|${OB_ROOT_PASSWORD}|g" $TMPFILE

  [ "${OB_DATA_DIR}" ] && echo "    data_dir: ${OB_DATA_DIR}" >> $TMPFILE
  [ "${OB_REDO_DIR}" ] && echo "    redo_dir: ${OB_REDO_DIR}" >> $TMPFILE
  print_end_phase

  print_start_phase "Ob-deploy mirror clone"
  mkdir -p $OB_HOME_PATH
  obd mirror clone /root/pkg/*.rpm \
  && obd mirror list local
  print_end_phase

  print_start_phase "Ob-deploy deploy"
  remove_disk_check_logic_in_obd

  if fastboot; then
    obd devmode enable && obd cluster deploy "${OB_CLUSTER_NAME}" -c $TMPFILE < /dev/null;
    if [ $? -ne 0 ]; then
      deploy_failed
    fi
    print_end_phase

    print_start_phase "Ob-deploy restore store dir"
    rm -rf ${OB_HOME_PATH}/store && tar -Sxzvf /root/boot/store.tar.gz -C ${OB_HOME_PATH}
    BLOCK_CNT=`cat /root/boot/block_cnt`
    for i in $(seq 0 $[ $BLOCK_CNT - 1 ])
    do
      fallocate -o 0 -l 67108864 ${OB_HOME_PATH}/store/clog/log_pool/$i
      echo "restore block id $i"
    done
    print_end_phase

    print_start_phase "Ob-deploy import etc"
    cp -r /root/boot/etc/* ${OB_HOME_PATH}/etc
    print_end_phase

    print_start_phase "Ob-deploy start"
    obd cluster start ${OB_CLUSTER_NAME}
    print_end_phase

    if [ "x${MODE}" == "xSLIM" ]; then
      run_custom_scripts /root/boot/init.d
    fi

  else
    print_start_phase "Ob-deploy autodeploy"
    obd devmode enable && obd cluster autodeploy "${OB_CLUSTER_NAME}" -c $TMPFILE < /dev/null;
    print_end_phase

    print_start_phase "Ob-deploy Create Tenant"
    create_tenant_cmd="obd cluster tenant create ${OB_CLUSTER_NAME} -n ${OB_TENANT_NAME}"
    if ! [ -z "${OB_TENANT_MINI_CPU}" ]; then
      create_tenant_cmd="${create_tenant_cmd} --min-cpu=${OB_TENANT_MINI_CPU}"
    fi;
    if ! [ -z "${OB_TENANT_MEMORY_SIZE}" ]; then
      create_tenant_cmd="${create_tenant_cmd} --memory-size=${OB_TENANT_MEMORY_SIZE}"
    fi;
    if ! [ -z "${OB_TENANT_LOG_DISK_SIZE}" ]; then
      create_tenant_cmd="${create_tenant_cmd} --log-disk-size=${OB_TENANT_LOG_DISK_SIZE}"
    fi;
    eval ${create_tenant_cmd} < /dev/null
    if [ $? -ne 0 ]; then
      deploy_failed
    fi

    if [ "x${MODE}" != "xSLIM" ]; then
      obclient -h127.1 -uroot@${OB_TENANT_NAME} -A -P${OB_MYSQL_PORT} < init_tenant_user.sql
    else
      run_custom_scripts /root/boot/init.d
    fi
    print_end_phase
  fi

  if [ $? -ne 0 ]; then
    deploy_failed
  fi
  mv -f $TMPFILE ${OB_HOME_PATH}/boot.yaml && echo "deploy success!"
fi

if [ $? -eq 0 ]; then
  echo "boot success!"
  # close the enable_rich_error_msg
  PASSWORD_ARG=""
  if [ "${OB_ROOT_PASSWORD}" != "" ]; then
    PASSWORD_ARG="-p${OB_ROOT_PASSWORD}"
  fi
  obclient -h127.1 -uroot@sys -A -P${OB_MYSQL_PORT} ${PASSWORD_ARG} -e "alter system set enable_rich_error_msg = false;"
else
  echo "boot failed!"
  if exit_while_error
  then
    exit 1
  else
    echo "Please check the log file ${OB_HOME_PATH}/log/observer.log"
  fi
fi
while :; do
    sleep 1
done

