#!/usr/bin/env bash

DIR='/root/system-utils'
GIT_COMMAND=$(which git)
LOGFILE='/var/log/refresh.log'
SEED_SCRIPT="${DIR}/scripts/eql_tools/seed_mysql_database.sh"

if [ -d "${DIR}" ]; then
  cd "${DIR}"
  if ${GIT_COMMAND} pull origin master; then
    echo $(date) >> ${LOGFILE}
    echo "Git repo pulled and up-to-date." >> ${LOGFILE}
    echo "Running refresh_database" >> ${LOGFILE}
    systemctl stop datadog-agent
    /usr/bin/php ${DIR}/scripts/eql_tools/refresh_database.php --sqlfile="${DIR}/scripts/eql_tools/sql/dev_base.sql" --automatic >> ${LOGFILE}
    chmod +x ${SEED_SCRIPT} && ${SEED_SCRIPT} -d art_relations 2>/dev/null >> ${LOGFILE}
    systemctl start datadog-agent
  else
    echo "Git pull had an unexpected error. You should manually run a git pull to test for issues.  This script will now exit." >> ${LOGFILE} && exit 1
  fi  
else
    echo "Repository directory not found. This script should only continue after pulling upstream changes." >> ${LOGFILE} && exit 1
fi