#!/bin/bash
SYS_PATH=/etc/aops
OUT_PATH=/opt/aops/uwsgi
UWSGI_LOG_DIR=/var/log/aops/uwsgi
OPERATION=$1
AOPS_CONSTANT="aops"

function check_uwsgi_path() {
  if [ ! -d "$1" ];then
    mkdir -p $1
  fi
}

function check_file() {
  if [ ! -e "$1" ]; then
    touch "$1"
  fi
}

function get_config() {
  INIFILE=$1
  SECTION=$2
  ITEM=$3
  awk -F '=' '/\['"$SECTION"'\]/{a=1}a==1&&$1~/'"$ITEM"'/{print $2; exit}' "$INIFILE"
}

function create_config_file() {
  check_uwsgi_path $OUT_PATH
  check_uwsgi_path $UWSGI_LOG_DIR

  echo "[INFO] start to create uwsgi file"
  config_file=$1
  service_name=$2

  ip=$(get_config "${config_file}" "${service_name}" "ip")
  port=$(get_config "${config_file}" "${service_name}" "port")
  wsgi_file_name=$(get_config "${config_file}" "uwsgi" "wsgi-file")

  wsgi_file=$(find /usr/lib/python*/site-packages -maxdepth 1 -name ${service_name} | head -n 1)
  daemonize=$(get_config "${config_file}" "uwsgi" "daemonize")
  http_timeout=$(get_config "${config_file}" "uwsgi" "http-timeout")
  harakiri=$(get_config "${config_file}" "uwsgi" "harakiri")
  processes=$(get_config "${config_file}" "uwsgi" "processes")
  threads=$(get_config "${config_file}" "uwsgi" "threads")
  gevent=$(get_config "${config_file}" "uwsgi" "gevent")

  check_file $daemonize
  echo "[INFO] run ${service_name} under path: ${wsgi_file}"

  if [[ -z "${wsgi_file_name}" ]] || [[ -z "${ip}" ]] || [[ -z "${port}" ]]; then
    echo "[ERROR] can not find  all config name in: ${config_file}, please check the file."
    echo "[ERROR] the following config name is needed: ip, port and wsgi_file."
    exit 1
  fi
  if [ -z "${wsgi_file}" ]; then
    echo "[ERROR] can not find the ${service_name} path under: /usr/lib/"
    exit 1
  fi

  echo "[uwsgi]
http=${ip}:${port}
chdir=${wsgi_file}
module=${service_name}.manage
uwsgi-file=${wsgi_file_name}
pidfile=${OUT_PATH}/${service_name}.pid
callable=app
http-timeout=${http_timeout}
harakiri=${harakiri}
processes=${processes}
daemonize=${daemonize}" >"${OUT_PATH}"/"${service_name}".ini
  if [ ${gevent} ]
  then
    echo "gevent=${gevent}
gevent-monkey-patch=true" >>"${OUT_PATH}"/"${service_name}".ini
  else
    echo "threads=${threads}" >>"${OUT_PATH}"/"${service_name}".ini
  fi
  chown root: ${OUT_PATH}/"${service_name}".ini
  chmod 750 ${OUT_PATH}/"${service_name}".ini
  echo "[INFO] create ${service_name} uwsgi file ok,path is ${OUT_PATH}/${service_name}.ini"
}

function check_num() {
  result=$(echo "$1" | grep '^[[:digit:]]*$')
  if [ -z "${result}" ]; then
    echo "[ERROR] $2 should be a number,please check this parameter "
    exit 1
  fi
}

function is_started() {
  aops_version=$(aops -v)
  if [[ -n ${aops_version} ]] && [[ ${aops_version} =~ "Version" ]]; then
    return 0
  else
    return 1
  fi
}

function start_service() {
  module_name=$1
  echo "[INFO] 1. Before starting the service, ensure that the data table is initialized"
  echo "[INFO] 2. Execute aops-basedatabase zeus or apollo to complete the data table initialization, For example '/opt/aops/scripts/deploy/aops-basedatabase.sh init zeus'"
  rm -rf ${OUT_PATH}/"${module_name}".pid
  uwsgi -d --ini ${OUT_PATH}/"${module_name}".ini --enable-threads
  pid=`ps auxww | grep $module_name.ini | grep -v grep | awk '{print $2}'`
  local_pid=`cat ${OUT_PATH}/"${module_name}".pid`
  if [ "${pid}" = "" ] && [ "${local_pid}" = "" ]; then
      echo "[ERROR] start uwsgi service: ${module_name} failed"
      exit 1
  fi
  echo "[INFO] start uwsgi service: ${module_name} success"
  exit 0
}

function stop_service() {
  module_name=$1
  echo "[INFO] stop uwsgi service: ${module_name}"
  uwsgi --stop ${OUT_PATH}/"${module_name}".pid
  rm -rf ${OUT_PATH}/"${module_name}".pid
  echo "[INFO] stop ${AOPS_CONSTANT} service success"
  exit 0
}

function start_or_stop_service() {
  if [ "${OPERATION}" = "start" ]; then
    start_service $1
  elif [ "${OPERATION}" = "stop" ]; then
    stop_service $1
  fi
}

function check_es_installed() {
  CONFIG_FILE=$1
  echo "[INFO] start to check elasticsearch"

  es_ip=$(get_config "${CONFIG_FILE}" "elasticsearch" "ip")
  es_port=$(get_config "${CONFIG_FILE}" "elasticsearch" "port")

  if [ -z "${es_ip}" ] || [ -z "${es_port}" ]; then
    echo "[ERROR] can not find config name 'ip' or 'port' of elasticsearch in: ${CONFIG_FILE}, please check the file"
    echo "If you have installed ES, Please set correct 'ip' value and 'port' of elasticsearch value and re-execute '${DATABASE_CONSTANT} start' "
    echo "If you have not installed ES, please execute the automatic installation script '/opt/aops/scripts/deploy/aops-basedatabase.sh elasticsearch' under the root user "
    exit 1
  fi
  check_num "${es_port}" "es_port"
  # check whether to install Elasticsearch and started
  visit_es_response=$(curl -s -XGET http://"${es_ip}:${es_port}")
  if [ -z "${visit_es_response}" ]; then
    echo "========================================================================="
    echo "[ERROR] elasticsearch connection FAILED,the following reason may cause failed:"
    echo "[INFO] 1. You have not installed Elasticsearch, if you need to install, please execute the automatic installation script '/opt/aops/scripts/deploy/aops-basedatabase.sh' under the root user"
    echo "[INFO] 2. Elasticsearch configuration is incorrect, please update value of 'ip' and 'port' of elasticsearch in $CONFIG_FILE"
    echo "[INFO] 3. Elasticsearch service not started, please start elasticsearch service."
    exit 1
  fi
  echo "[INFO] elasticsearch check ok"
}

function check_mysql_installed() {
  CONFIG_FILE=$1
  SQL=$2
  echo "[INFO] start to check mysql"

  mysql_ip=$(get_config "${CONFIG_FILE}" "mysql" "ip")
  port=$(get_config "${CONFIG_FILE}" "mysql" "port")

  if [ -z "${mysql_ip}" ] || [ -z "${port}" ]; then
    echo "[ERROR] can not find config name 'ip' or 'port' of mysql in: ${CONFIG_FILE}, please check the file"
    echo "If you have installed mysql, please set correct 'ip' value and 'port' value of mysql and re-execute '${DATABASE_CONSTANT} start' "
    echo "If you have not installed mysql, please execute the automatic installation script '/opt/aops/script/aops-basedatabase install mysql' under the root user "
    exit 1
  fi
  check_num "${port}" "port"
  aops_database=$(get_config "$CONFIG_FILE" "mysql" "database_name")
  connect_check_cmd="import pymysql
try:
    connect = pymysql.connect(host='$mysql_ip', port=$port, database='$aops_database')
    connect.close()
except pymysql.err.OperationalError:
    print(False)
"
  connect_check_result=$(python3 -c "$connect_check_cmd")
  if [ "${init_result}" = "False" ]; then
    echo "========================================================================="
    echo "[ERROR] mysql connection FAILED, the following reason may cause failed:"
    echo "[INFO] 1. You have not installed mysql,If you need to install, please execute the automatic installation script '/opt/aops/scripts/deploy/aops-basedatabase.sh' under the root user, For example '/opt/aops/scripts/deploy/aops-basedatabase.sh install mysql'"
    echo "[INFO] 2. mysql configuration is incorrect,please update value of 'ip' and 'port' of mysql in ${CONFIG_FILE}"
    echo "[INFO] 3. mysql service not started,please start mysql service."
    exit 1
  fi
  echo "[INFO] mysql check ok"
}



