#!/usr/bin/env bash

# Some global variables
PGREP_COMMAND=$(which pgrep)
PHP_COMMAND=$(which php)
EHCMCLI_COMMAND=$(which ehcmcli)
ASMCLI_COMMAND=$(which asmcli)
BASE_DIR='/root'
REFRESH_SCRIPT=$(find ${BASE_DIR} -type f -name <%= @db_refresh_file %>)
LOGFILE_NAME='/var/log/iscsi_remount.log'
REFRESH_LOG='/var/log/refresh.log'
SECONDS_TO_WAIT=300
SECONDS=0

function logmessage {
  printf '%s\n' " $(date +%c): ${1}" >> "${LOGFILE_NAME}"
  printf '%s\n' >> "${LOGFILE_NAME}"
}

# Check if refresh process is running
while [ ${SECONDS} -lt ${SECONDS_TO_WAIT} ]; do 
  if ${PGREP_COMMAND} php > /dev/null; then
    logmessage "PHP process is running. Sleeping for 10 seconds."
    sleep 10
  else
    logmessage "No PHP process found, so a refresh is not currently running."
    break 2
  fi
done

# Check if data directory is found
if [ -d "<%= node['mysql']['directory'] %>" ]; then
  logmessage 'MySQL directory found. Exiting...'
  exit 0
else
  logmessage 'MySQL directory not found. Proceeding with iscsi remount.'
fi

<% if node['platform_version'].to_s.start_with?('7') %>
if [ -x "${ASMCLI_COMMAND}" ]; then
  logmessage "CentOS 7 does not populate equallogic volume lockfile used by refresh script, so add it with the following command..."
  # Filter for lines of the format <VOLUME> --> <SMART_COPY_ID>
  ${ASMCLI_COMMAND} list smart-copy --comment $(cat /var/lib/equallogic/serverid) | grep -- '-->' | tail -n 1 | awk '{print $3}' > /var/lib/equallogic/volume
else
  logmessage 'asmcli not found. Please install asmcli.'
  exit 1
fi
<% end -%>

# Find logged in targets, then log them out
if [ -x "${EHCMCLI_COMMAND}" ]; then
  for target in $(${EHCMCLI_COMMAND} status | grep "Target name" | awk '{print $3}'); do
    logmessage "logging out ${target}"
    ${EHCMCLI_COMMAND} logout --target ${target}
  done
else
  logmessage 'ehcmcli not found. Please install ehcmcli.'
  exit 1
fi

# Now run db refresh script with remount parameter
# The remount parameter handles logging in to targets and existing snapshots
if [ -x "${PHP_COMMAND}" ] && [ -f "${REFRESH_SCRIPT}" ]; then
  logmessage "Refresh script and php binary found. Running ${REFRESH_SCRIPT}..."
  ${PHP_COMMAND} ${REFRESH_SCRIPT} --remount >> ${REFRESH_LOG} 2>&1
  logmessage "Refresh script exited without error"
else
  logmessage "Refresh script or php binary not found. Is system-utils git repo present in ${BASE_DIR}?"
  exit 1
fi
