#!/bin/sh
set -e
if [ -z "$PUSH_KEY" ]; then
    echo "Please set PUSH_KEY in .env"
    exit 1
fi

if [ -z "$PUSH_DELAY" ]; then
    echo "Please set PUSH_DELAY in .env to a string compatible with sleep(1)"
    exit 1
fi

if [ -z "$PUSH_URLS" ]; then
    echo "Please set PUSH_URLS in .env"
    exit 1
fi

cd /git
#use global config to not modify the repository
git config --global core.sshCommand "/usr/bin/ssh -o 'StrictHostKeyChecking no' -i /ssh/$PUSH_KEY"
while true; do
    IFS="|"
    for PAIR in $PUSH_URLS; do
        #URL comes first, because they can't contain spaces, but directories can
        URL="$(echo $PAIR | cut -d ' ' -f 1)"
        DIR="$(echo $PAIR | cut -d ' ' -f 2-)"
        cd "$DIR"
        #using --mirror causes errors when pushing, but --prune,--force, plus these refspecs should catch most stuff
        git push --force --prune "$URL" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' '+refs/change/*:refs/change/*' || true
        cd - > /dev/null
    done
    sleep "$PUSH_DELAY"
done
