#!/bin/bash -x

UPTIME_LIMIT=300
TRY_LIMIT=9
#UPTIME_LIMIT=900000000   # 900k seconds ~ 28.5 years
#TRY_LIMIT=3
LOGFILE=$(awk '/^logfile/{print $3}' /defaults/selfdns/default.conf)
[ -w "${LOGFILE}" ] || LOGFILE='/dev/stderr'


_my_log() {
  local my_date=$(date "+%FT%T.%3N%z")
  [[ $1 ]] && local severity="${1:-DEBUG}" && shift
  echo -e "${my_date}\t${severity}\t${0}\t${@}"
}

# for qloud/deploy pods
_container_seconds() {
  # skip if we have NO pid=1
  kill -0 1 || return 1
  if echo ${PORTO_NAME} | grep -q '^ISS-AGENT'; then
    # return etime of pid=1
    ps --no-headers -o etimes -p1 | head -1 | grep -oP '[0-9]+' 
  else
    return 2
  fi
}

chmod +x /etc/yandex/selfdns-client/plugins/*

UPTIME=$(_container_seconds) || UPTIME=$UPTIME_LIMIT

if [ -n "$SELFDNS_TOKEN" ] ; then
  envsubst < /defaults/selfdns/default.conf > /etc/yandex/selfdns-client/default.conf
  export $JVB_WS_DOMAIN   # from ENV
  selfdns-client

  if [ ${UPTIME} -lt ${UPTIME_LIMIT} ]; then
    for n in `seq 1 ${TRY_LIMIT}`; do
      selfdns-client --force --terminal | tee -a "${LOGFILE}" | grep 'Processing finished in .* OK'
      [ $? -eq 0 ] && break
      if [ $n -eq $TRY_LIMIT ]; then
        tail -100 "${LOGFILE}" | egrep 'ERROR|FATAL'
        _my_log ERROR "selfdns-client: Retry limit reached (made $TRY_LIMIT requests), give up. Exit 2" | tee -a "${LOGFILE}"
        exit 2
      fi
      sleep 1
    done
  else
    _my_log INFO "UPTIME_LIMIT=${UPTIME_LIMIT} reached, do nothing. (UPTIME=${UPTIME})"
    exit 0
  fi
else
  _my_log INFO "SELFDNS_TOKEN not found, do nothing"
fi
