#!/usr/bin/env bash

readonly RSYNC_USER="${RSYNC_USER}"
readonly RSYNC_SERVER="${RSYNC_SERVER}"

main() {
  local filepath="$1"
  local name
  name="$(basename "${filepath}")"

  # Stagger transfers to avoid congestion at the hour mark.
  sleep $((RANDOM % 180))

  # Limit bandwidth so the backup does not saturate the connection.
  rsync --archive --verbose --bwlimit=4096 \
	"${HOME}/timelapse/${name}" \
	"${RSYNC_USER}@${RSYNC_SERVER}:/timelapse/${name}"

  # Delete outdated files.
  # This assumes the timelapse is created on an hourly basis.
  rm -f "$1"
  find "${HOME}/timelapse/" -mmin +60 -delete
}

main "$@"
