#!/bin/sh
PROCESSOR_COUNT=$(node -e 'console.log(require("os").cpus().length)')
if [ -z "${PROCESSOR_COUNT}" ] ; then
  PROCESSOR_COUNT=2
fi
DEFAULT_LOAD_MULTIPLE=2
DEFAULT_MAX_LOAD=$(expr ${PROCESSOR_COUNT} '*' ${DEFAULT_LOAD_MULTIPLE})
if [ -z "${DEFAULT_MAX_LOAD}" ] ; then
  DEFAULT_MAX_LOAD=10
fi

# 2.5 minutes max wait between retries
MAX_SLEEP_TIME=150

YB_MAX_LOAD=${YB_WORK_MAX_LOAD}
if [ -z "${YB_MAX_LOAD}" ] ; then
  YB_MAX_LOAD=${DEFAULT_MAX_LOAD}
fi
YB_LOAD_LOG="${YB_WORK_DIR:-/tmp}/yuebing_load.log"

SCRIPT="${0}"

log () {
  echo "${SCRIPT} [$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "${YB_LOAD_LOG}"
}

loadAverage () {
  # Use the 5-minute load average; the 2nd-to-last word in `uptime` output
  # Return only the integer part of the load, drop any decimal
  uptime | awk '{print $(NF-1)}' | cut -d. -f1
}

# This block of load-related code is to keep the system from grinding
# to a halt.

# Sometimes queue management is hard and we spin up too many ffmpeg jobs
# Before the system dies, let's stall jobs here, wait for the system
# load to go below a threshold

MAX_WAIT=$(expr 60 '*' 30)  # max wait 30 minutes
START=$(date +%s)
LOAD="$(loadAverage)"
ATTEMPT=0
if [ -z "${LOAD}" ] ; then
  log "Unable to determine load, running: ffmpeg $*"
elif [ ${LOAD} -gt ${YB_MAX_LOAD} ] ; then
  while [ ${LOAD} -gt ${YB_MAX_LOAD} ] ; do
    NOW=$(date +%s)
    if [ $(expr ${NOW} - ${START}) -gt ${MAX_WAIT} ] ; then
      log "Exceeded max wait (${MAX_WAIT} seconds), quitting and not running ffmpeg $*"
      exit 2
    fi
    ATTEMPT=$(expr ${ATTEMPT} + 1)
    SLEEP_TIME=$(expr 10 '*' ${ATTEMPT})
    if [ ${SLEEP_TIME} -gt ${MAX_SLEEP_TIME} ] ; then
      SLEEP_TIME=${MAX_SLEEP_TIME}
    fi
    log "Load is too high (${LOAD} > ${YB_MAX_LOAD}), waiting ${SLEEP_TIME} seconds before trying again: ffmpeg $*"
    sleep ${SLEEP_TIME}
    LOAD="$(loadAverage)"
    if [ -z "${LOAD}" ] ; then
      log "Unable to determine load, quitting and not running ffmpeg $*"
      exit 3
    fi
  done
else
  log "Load is OK (${LOAD} <= ${YB_MAX_LOAD}) we can run ffmpeg $*"
fi

log "RUNNING: ffmpeg $*"

exec ffmpeg "$@"
