#!/bin/bash
set -e

umask 0002

output_with_date() {
  echo "[$(date +"%d-%b-%Y %H:%M:%S")] $1";
}

# Run userini parser before starting FPM
RUN_USERINI_PARSER_WRAPPER="/platform/bin/run-userini-parser-wrapper.sh"
if [[ -x ${RUN_USERINI_PARSER_WRAPPER} ]]; then
  output_with_date "Running userini parser..."
  ${RUN_USERINI_PARSER_WRAPPER}
fi

if [[ "$1" == "php-fpm" ]]; then
  # Override this var with fpm replacements
  export PHP_INI_SCAN_DIR="${PHP_INI_SCAN_DIR//cli/fpm}"
fi
CURRENT_UID=$(id -u)

FPM_RESTART_THRESHOLD=2
FPM_RESTART_DELAY_MIN=10
FPM_RESTART_DELAY_MAX=60

# Make sure we only run this logic when running php-fpm
if [[ "$1" == "php-fpm" ]] && [[ -z "${PAGELY_FPM_SKIP_THROTTLE}" ]]; then
  # See if we have a variables file that we can use
  if [[ -e /pagely-fpm-restart-vars.env ]]; then
    output_with_date "Loading FPM restart vars from vars file.";
    # Just as a security precaution only load this if it's owned by root
    VARS_FILE_OWNERSHIP="$(stat -c '%u:%g' /pagely-fpm-restart-vars.env)"
    if [[ "$VARS_FILE_OWNERSHIP" == "0:0" ]]; then
      source /pagely-fpm-restart-vars.env;
    fi;
  fi;
  # Setup defaults
  PAGELY_FPM_CONSECUTIVE_FAST_RESTARTS="${PAGELY_FPM_CONSECUTIVE_FAST_RESTARTS:-0}"
  PAGELY_FPM_LAST_RESTART="${PAGELY_FPM_LAST_RESTART:-0}"
  LAST_RESTART_SECS=-1
  # See if this was a fast restart
  if [[ $PAGELY_FPM_LAST_RESTART -gt 0 ]]; then
    # Last restart > 0 means that we actually have a last restart time
    LAST_RESTART_SECS=$(($(date +%s) - ${PAGELY_FPM_LAST_RESTART}))
  fi;
  # If LAST_RESTART_SECS != -1 then this is a real restart time
  if [[ $LAST_RESTART_SECS -ne -1 ]]; then
    output_with_date "Last restart was ${LAST_RESTART_SECS} seconds ago.";
    # If LAST_RESTART_SECS is < 10, increase the recorded number of fast restarts
    if [[ $LAST_RESTART_SECS -le 10 ]]; then
      PAGELY_FPM_CONSECUTIVE_FAST_RESTARTS=$(($PAGELY_FPM_CONSECUTIVE_FAST_RESTARTS + 1))
    else
      # Reset everything if our last restart was outside the time period
      PAGELY_FPM_CONSECUTIVE_FAST_RESTARTS=0
    fi;
    output_with_date "Detected ${PAGELY_FPM_CONSECUTIVE_FAST_RESTARTS} consecutive fast restarts so far.";
    # If we had >= 2 consecutive fast restarts, throttle
    if [[ $PAGELY_FPM_CONSECUTIVE_FAST_RESTARTS -ge $FPM_RESTART_THRESHOLD ]]; then
      SLEEP_TIME="$(shuf -i ${FPM_RESTART_DELAY_MIN}-${FPM_RESTART_DELAY_MAX} -n1)"
      output_with_date "Throttling for ${SLEEP_TIME} seconds.";
      sleep $SLEEP_TIME;
    fi;
  fi;
  # Set last restart to now
  PAGELY_FPM_LAST_RESTART=$(date +%s)
  if [[ $CURRENT_UID -eq 0 ]]; then
    # Dump out vars to our storage file
    set | grep PAGELY_FPM > /pagely-fpm-restart-vars.env;
  fi;
fi;

exec "$@"
