#!/bin/bash

REPO=$1
BRANCHES="stable prestable testing unstable"
URL="http://dist.yandex.ru"

echo "Cacus Import Repo script. It uses 'sudo -i'"

for branch in $BRANCHES; do
    echo "Importing $REPO $branch"
    mkdir -p /var/log/cacus-import/$REPO/$branch

    COUNT=0

    false
    while [ $? -ne 0 ]; do
        sleep 1
        DATE=$(date +%s)
        time cacus import-repo $URL/$REPO/$branch/ $REPO $branch \
            2> /var/log/cacus-import/$REPO/$branch/$branch-$DATE.log

        if [ $? -eq 0 ]; then
            head -n1 /var/log/cacus-import/$REPO/$branch/$branch-$DATE.log | \
                grep "Found 0 packages" > /dev/null

            if [ $? -eq 0 -a $COUNT -le 3 ]; then
                COUNT=$(($COUNT+1))
                false
            fi
        else
                false
        fi
    done
done
