#!/bin/sh

set -u

: "${DUMP_HOST:?}" "${DUMP_DB:?}" "${DUMP_PASSWORD_FILE:?}"
OPTS=${DUMP_OPTS:---single-transaction}
MINUTE=${DUMP_MINUTE:-50}
OUT=/dumps/$DUMP_DB.sql
RETRY=300

log() { echo "db-dump: $(date '+%F %T') $*"; }

dump() {
  tmp="$OUT.tmp"
  start=$(date +%s)
  if MYSQL_PWD="$(cat "$DUMP_PASSWORD_FILE")" mysqldump -h "$DUMP_HOST" -u root $OPTS \
       --hex-blob --order-by-primary --no-tablespaces \
       --databases "$DUMP_DB" > "$tmp" \
     && tail -n 1 "$tmp" | grep -q '^-- Dump completed' \
     && mv -f "$tmp" "$OUT"; then
    log "dumped $DUMP_DB: $(wc -c < "$OUT") bytes in $(( $(date +%s) - start ))s"
    return 0
  fi
  rm -f "$tmp"
  log "FAILED to dump $DUMP_DB; the previous dump is kept, retrying in $(( RETRY / 60 )) minutes"
  return 1
}

while :; do
  if dump; then
    wait=$(( (MINUTE * 60 - $(date +%s) % 3600 + 3600) % 3600 ))
    [ "$wait" -eq 0 ] && wait=3600
  else
    wait=$RETRY
  fi
  sleep "$wait"
done
