#!/bin/bash

# Directory where the repo is stored locally. Example: /srv/repo
target="/srv/mirror/archlinux"

# Lockfile path
lock="/var/lock/syncrepo.lck"

# Use 0 to disable the limit.
# The default unit is KiB (see man rsync /--bwlimit for more)
bwlimit=0

# The source URL of the mirror you want to sync from.
# Chose a tier 1 mirror from this list and use its rsync URL:
# https://www.archlinux.org/mirrors/
source_url='rsync://mirror.raiolanetworks.com/pub/archlinux/'

# An HTTP(S) URL pointing to the 'lastupdate' file on your chosen mirror.
# Use the HTTP(S) URL from your chosen mirror.
lastupdate_url='https://mirror.raiolanetworks.com/archlinux/lastupdate'

exec 9>"${lock}"
flock -n 9 || exit

rsync_cmd() {
  local -a cmd=(rsync -rlptH --safe-links --delete-delay --delay-updates
    "--timeout=600" "--contimeout=60" --no-motd)

  if stty &>/dev/null; then
    cmd+=(-h -v --progress)
  else
    cmd+=(--quiet)
  fi

  if ((bwlimit > 0)); then
    cmd+=("--bwlimit=$bwlimit")
  fi

  "${cmd[@]}" "$@"
}

# if we are called without a tty (cronjob) only run when there are changes
if ! tty -s && [[ -f "$target/lastupdate" ]] && diff -b <(curl -Ls "$lastupdate_url") "$target/lastupdate" >/dev/null; then
  # keep lastsync file in sync for statistics generated by the Arch Linux website
  rsync_cmd "$source_url/lastsync" "$target/lastsync"
  exit 0
fi

rsync_cmd \
  --exclude='*.links.tar.gz*' \
  --exclude='/sources' \
  --exclude='/archive' \
  --exclude='/*-debug' \
  --exclude='/*-staging' \
  --exclude='/*-testing' \
  --exclude='/pool/*-debug' \
  --exclude='/images' \
  --exclude='/community' \
  --exclude='/gnome-unstable' \
  --exclude='/kde-unstable' \
  --exclude='/testing' \
  --exclude='/staging' \
  --exclude='/other' \
  "${source_url}" \
  "${target}"

echo "Last sync was $(date -d @$(cat ${target}/lastsync))"
