#!/bin/bash

# because the normal mirroring tools often can't access current data
# this scripts updates the local repositories using:
# reposync + createrepo

set -o errexit -o nounset

if [ -r /etc/dass-it/reposync.conf ]; then
   source /etc/dass-it/reposync.conf
fi

usage()
{
  printf "
usage: $0 REPO_FILE_URL [<DIRECTORY>]

  $0 will download REPO_FILE_URL to a subdirectory of [DIRECTORY] (default: $DEST).
  It creates the repository structure, so that
  reposync-mirror-update.sh will be able to download the repository.

"
}

check_url()
{
   local URL="$1"
   [ -z "$1" ] && return 1
   local CODE=`curl --location --write-out %{http_code} --silent --output /dev/null "$URL"`
   printf "  %s: %s\n" "$URL" "$CODE"
   test "$CODE" = "200"
   return $?
}

REPO_FILE_URL=${1:-}
STARTDIR=${2:-$DEST}

if ! [ -d $STARTDIR ]; then
  echo "FAILED: $STARTDIR is not a valid directory."
  usage
  exit 1
fi

if ! check_url "$REPO_FILE_URL"; then
  echo "FAILED: url \"$REPO_FILE_URL\" not accessable."
  usage
  exit 1
fi

REPO_FILE=`sed "s|http://|$STARTDIR/|" <<< "$REPO_FILE_URL"`
mkdir -p `dirname $REPO_FILE`
curl --silent $REPO_FILE_URL -o $REPO_FILE

mirror-adapt-repository.sh "$REPO_FILE"
