#!/usr/bin/env bash
#
#######
# Taken from Procursus
# Modified by Nebula
#######
# BEGIN CONFIG
#######
#
# Directory where the repo is stored locally. Example: /srv/repo
target="/srv/palera1n/files"

# Directory where files are downloaded to before being moved in place.
# This should be on the same filesystem as $target, but not a subdirectory of $target.
# Example: /srv/tmp
tmp="/srv/palera1n/tmp"

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

# If you want to limit the bandwidth used by rsync set this.
# 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.
# This should probably be the palera1n server, unless you
# are syncing off another third-party mirror. Needs to be rsync.
source_url="rsync://static.palera.in/rsync"

# An HTTP(S) URL pointing to the 'lastupdate' file on your chosen mirror or static.palera.in.
lastupdate_url="https://static.palera.in/lastupdate"

####### 
# END CONFIG
#######

[ ! -d "${target}" ] && mkdir -p "${target}"
[ ! -d "${tmp}" ] && mkdir -p "${tmp}"

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

# Cleanup any temporary files from old run that might remain.
find "${target}" -name '.~tmp~' -exec rm -r {} +

rsync_cmd() {
        local -a cmd=(rsync -rtlH --safe-links --delete-after ${VERBOSE} "--timeout=600" "--contimeout=60" -p \
                --delay-updates --no-motd "--temp-dir=${tmp}")

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

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

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


# Only run when there are changes
if [[ -f "$target/lastupdate" ]] && diff -b <(curl -Ls "$lastupdate_url") "$target/lastupdate" >/dev/null; then
        stty &>/dev/null && echo "lastupdate has not changed"
        exit 0
fi

rsync_cmd \
        "${source_url}" \
        "${target}"
