#!/bin/bash

# import global variables
source /home/pi/monitoring/common/scripts/common_var

function timestamp() {
  echo $(date +"%F %T")
}

function check_log_dir() {
  # first argument - node/server/common string

  case $1 in
    "node")   CHECK_LOG_DIR=$DIR_NODE_LOGS; ;;
    "server") CHECK_LOG_DIR=$DIR_SERVER_LOGS; ;;
    "common") CHECK_LOG_DIR=$DIR_COMMON_LOGS; ;;
    *)        echo "ERROR: invalid argument ${1} for function check_log_dir!" ;;
  esac
      
  if [ ! -d "${CHECK_LOG_DIR}" ];
  then
    echo "Log directory '${CHECK_LOG_DIR}' does not exist yet! Creating it..."
    mkdir ${CHECK_LOG_DIR}
    chown pi:pi ${CHECK_LOG_DIR}
  fi
}

function log_server_import() {
  # first  argument - success/fail
  # second argument - bt/wlan
  # third  argument - source hostname (database name)
  # fourth argument - log source

  # local variables
  LOG_DELIM=$'\t'

  check_log_dir "server"

  echo "$(timestamp)${LOG_DELIM}${1}${LOG_DELIM}${2}${LOG_DELIM}${3}${LOG_DELIM}${4}" \
  >> "${DIR_SERVER_LOGS}/${LOG_SERVER_IMPORT}.log"
}

function mysql_passwd_check() {
  # first  argument - MySQL username

  while :
  do
    read -s -p "Enter MySQL password for user ${1}: " MYSQL_SECRET
    echo ""
    # password empty?
    if [[ "$MYSQL_SECRET" == "" ]]
    then
      echo "Incorrect password - try again!"
      continue;
    fi
    # try logging in to MySQL
    echo "exit" | mysql -u ${1} -p${MYSQL_SECRET} &>/dev/null
    if [[ "$?" == "0" ]]
    then
      echo "Password OK!"
      break;
    else
      echo "Incorrect password - try again!"
    fi
  done
}
