#!/bin/bash

set -o errexit -o nounset

CONFIG=${1:-/etc/mirror-obs.conf}

if ! [ -r "$CONFIG" ]; then
  echo "failed to read config file $CONFIG."
  exit 1
fi
source $CONFIG

RSYNC_DELETE="--delete"
RSYNC_OPTS="-v -rlLptx --safe-links --stats $RSYNC_EXTRA_OPTS"

rsync_if_exists()
{
    src=$1
    dest=$2

    rsync -q $src || return 1
    echo "found rsync source: $src"
    [ -d "$dest" ] || return 2
    rsync $RSYNC_OPTS $RSYNC_DELETE $src $dest
}

# ---------------- mirror openSUSE repositories ------------------------
FAILED=""
SUCCESS=""


cd $DEST

for DIR in $REPOS; do
  SOURCE_DIR=${SOURCE_OPENSUSE}/${DIR}/.
  DEST_DIR=${DEST}/${DIR}/.
  mkdir -p ${DEST_DIR}
  rc=0
  rsync_if_exists  "${SOURCE_DIR}" "${DEST_DIR}" || rc=$?
  case $rc in
    1)  echo Distribution $DIR nicht gefunden
        FAILED="$FAILED $DIR"
        ;;
    2)  echo Zielverzeichnis ${DEST_DIR} nicht vorhanden
        FAILED="$FAILED $DIR"
        ;;
    0)
        SUCCESS="$SUCCESS $DIR"
        if [ "${POST_SCRIPT:-}" ]; then
            $POST_SCRIPT ${DEST_DIR}
        fi
        ;;
    *)
        echo Fehler $?
        FAILED="$FAILED $DIR"
        ;;
  esac
  echo
  echo
done

if [ "${REPORT_SCRIPT:-}" ]; then
    $REPORT_SCRIPT mirror-obs "$SUCCESS" "$FAILED"
fi
