#!/bin/bash

# This script synchronizes first, the generated frontend and then
# retrieves submissions

BASEDIR="/srv"
FRONTEND_HOSTNAME="phobos"

SSH_OPTS="ssh -p 22 -i ~/.ssh/id_ed25519 -o ControlMaster=auto -o ControlPath=/root/.ssh/%r@%h:%p -o ControlPersist=2 -o PasswordAuthentication=no -o StrictHostKeyChecking=no"

cd "${BASEDIR}"

touch /tmp/stop

# Establish first ssh connection for controlpersist socket, to avoid delay during time synchronization
${SSH_OPTS} ${FRONTEND_HOSTNAME} ls > /dev/null

# Synchronize the date one time
${SSH_OPTS} ${FRONTEND_HOSTNAME} date -s @"$(date +%s)"

# Synchronize static files in a separate loop (to avoid submissions delays during file synchronization)
while ! [ -f SETTINGS/stop ] || [ /tmp/stop -nt SETTINGS/stop ]
do
    rsync -e "$SSH_OPTS" -av --delete FILES "${FRONTEND_HOSTNAME}":"${BASEDIR}"

    # Synchronize logs
    rsync -e "$SSH_OPTS" -av "${FRONTEND_HOSTNAME}":/var/log/ /var/log/frontend

    sleep 5
done &

while ! [ -f SETTINGS/stop ] || [ /tmp/stop -nt SETTINGS/stop ]
do
    # Synchronize static files pages
    rsync -e "$SSH_OPTS" -av --delete --delay-updates --partial-dir=.tmp/ PKI TEAMS SETTINGSDIST "${FRONTEND_HOSTNAME}":"${BASEDIR}"

    # Synchronize submissions
    rsync -e "$SSH_OPTS" -av --ignore-existing --delay-updates --temp-dir=.tmp/ --partial-dir=.tmp/ --remove-source-files "${FRONTEND_HOSTNAME}":"${BASEDIR}"/submissions/ submissions/

    sleep 0.3
done

wait
echo See you
