#!/bin/bash

export LC_ALL=C
CONFIG='/etc/repopusher/repopusher.conf'

if [ -r "$CONFIG" ]; then
    . "$CONFIG"
else
    echo "ERROR: $CONFIG not found or not readable" >&2
    exit 1
fi 

cd "$arrived"  || { echo "ERROR: Could not chdir to $arrived"; exit 1; }
rm -vf ${locks}/*

while true; do
    # reload config
    . "$CONFIG"
    if $repopush_disabled; then
        sleep 5
        continue
    fi
    
    for j in ${servers}*; do
        server="${j##*/}"
        server="$(basename $server .conf)";
        lock="$locks$server"
        
        if test -e "$pausefile" && grep -q $server "$pausefile"; then
            echo "`date -R` skipping $j due to push pause"
            continue
        fi
        
        #$debug && echo 
        #$debug && echo "server $server"
        if [ -e "$lock" ]; then
            $debug && echo "$server locked($(cat $lock))"
            continue
        fi
        
        (
            # prioritize non-home projects
            for i in $(ls -tr | grep -v '^home:') $(ls -tr | grep '^home:'); do
                if ! [ -d "$repodata${i//:/:/}" ]; then
                    #$debug && echo "skipping for non-existing dir $repodata${i//:/:/}"
                    #$debug && echo "$arrived/$i seems obsolete: $repodata${i//:/:/} does not exist. Should be removed, but I can't do it"
                    # warning: this file might grow very quickly if there are lots of obsoletes; so better not append to it
                    echo "`date -R`  $arrived/$i $repodata${i//:/:/}" > $logdir/obsolete_projects.log 
                    #rm $i
                    continue
                fi
        
                # check again the lock file
                if [ -e "$lock" ]; then
                    $debug && echo "$server locked($(cat $lock))"
                    continue 2
                fi

                push_file="${pushed}$i.$server"
                #$debug && echo checking $push_file
                #if [ ! -f "$push_file" -o "$i" -nt "$push_file" ]; then

                # i:         mozilla
                # server:    widehat.opensuse.org
                # lock:      locks/widehat.opensuse.org
                # push_file: pushed/mozilla.widehat.opensuse.org
                if [ "$i" -nt "$push_file" ]; then
    		        echo "$i" > "$lock"
                    $debug && echo $server: start syncing $i
    
                    echo "`date -R` $server: start syncing $i" | \
                        /usr/sbin/cronolog -S $global_log \
                        "$logdir/%Y/%m/%d/global-%Y%m%d.log"

                    sh "$j" "$server" "$i" "$lock"
                    touch --reference="${arrived}$i" "$push_file"
                    continue 2
                fi
            done
        ) &
    done
    $debug && echo "...get some sleep... ($run_interval s)"
    $debug && echo 
    sleep $run_interval
done



