#!/bin/sh

cd ".repoupstream" || exit 1
needupdate=false

fullmirror=false
if [ -f "repourl" ]; then
  fullmirror=true
  repourl="$(cat repourl)"
fi

for repo in $(cat *.repo | sort -u); do
  rmd5="$(echo "$repo" | md5sum | awk '{print $1}')"
  if [ -f "$rmd5.oldpack.tgz" ]; then
    curl -sLo "$rmd5.pack.tgz" -z "$rmd5.oldpack.tgz" "$repo/.repo/pack.tgz"
  else
    curl -sLo "$rmd5.pack.tgz" "$repo/.repo/pack.tgz"
  fi
  if [ -f "$rmd5.pack.tgz" ]; then
    needupdate=true
    rm -rf "$rmd5"
    mkdir -p "$rmd5"
    tar -xaf "$rmd5.pack.tgz" -C "$rmd5/"
    rm -f "$rmd5/list"
    mv "$rmd5.pack.tgz" "$rmd5.oldpack.tgz"
  fi
done

$needupdate || exit 0
rm -rf "../.repo/"
mkdir -p "../.repo/"

for repo in $(cat *.repo | sort -u); do
  rmd5="$(echo "$repo" | md5sum | awk '{print $1}')"
  rsync -ac --ignore-existing "$rmd5/" "../.repo/"
done

ls "../.repo/" | sort -u > list
mv list "../.repo/"
cd "../.repo/"

if $fullmirror; then
  mkdir -p "../.repofiles/"
  for link in $(find -name link); do
    hmod="../.repofiles/$(basename "$(dirname "$link")")"
    if [ -f "$hmod" ]; then
      curl -sLo "$hmod" -z "$hmod" "$(cat "$link")" && echo "$repourl/.repofiles/$(basename "$hmod")" > "$link"
    else
      curl -sLo "$hmod" "$(cat "$link")" && echo "$repourl/.repofiles/$(basename "$hmod")" > "$link"
    fi
  done
fi

tar cz list --files-from list > "pack.tgz"
echo "done"
