#!/bin/bash
set -e

function die()
{
    echo "$1"
    exit 1
}

# Defaults
ORIGIN=
DESTINATION=
PATTERN=

# Read options
while [ -n "$1" ]; do
    case "$1" in
        --base-origin)
            shift
            ORIGIN="$1"
            ;;
        --base-dest)
            shift
            DESTINATION="$1"
            ;;
        *)
            PATTERN=$1
            ;;
    esac
    shift
done

if [ -z "${ORIGIN}" ]; then
    die "Missing origin"
fi
if [ -z "${DESTINATION}" ]; then
    die "Missing destination"
fi
if [ -z "${PATTERN}" ]; then
    die "Missing pattern"
fi


echo "* Origin: ${ORIGIN}"
echo "* Destination: ${DESTINATION}"
echo "* Pattern: ${PATTERN}"

# Find out nested repositories
REPOSITORIES=""
repodatas=`find ${ORIGIN}/el* -name "repodata"`
for repodata in ${repodatas}; do
    repo=`dirname "${repodata}"`
    echo "Found repository ${repo}"
    REPOSITORIES="${REPOSITORIES} ${repo}"
done

# Sync them
for src_repo in ${REPOSITORIES}; do
    subpath=${src_repo/${ORIGIN}/}
    dst_repo="$DESTINATION/${subpath}"
    echo "* Sync ${src_repo} => ${dst_repo}"
    mkdir -p "${dst_repo}"
    for pattern in $PATTERN; do
        check=$(find "${src_repo}" -maxdepth 1 -name "${pattern}")
        if [ -n "$check" ]; then
            cp --no-clobber -v ${src_repo}/${pattern} ${dst_repo}
        else
            echo "No pattern match for ${src_repo}/${pattern}"
        fi
    done
    echo "* Update repo ${dst_repo}"
    createrepo "${dst_repo}"
done

