#!/usr/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
hashdetect () {
  strhash=${1};
  hashlen="${#strhash}"
  case $hashlen in
     128)
       hashbinary='sha512sum'
       ;;
     64)
       hashbinary='sha256sum'
       ;;
     40)
       hashbinary='sha1sum'
       ;;
     32)
       hashbinary='md5sum'
       ;;
     *)
       hashbinary='unknown'
       ;;
      esac
      echo ${hashbinary};
}
if [[ ! -d .git ]]; then
  echo "You must run this in a cloned git repo"
  exit 12
fi

# We have 2 URL patterns for lookaside: the sources-staging s3 bucket, and the (mostly defunct) Peridot import one
# Rockyget simply checks them both for the appropriate file/hash
export SURL1="https://rocky-linux-sources-staging.a1.rockylinux.org"
export SURL2="https://sources.build.resf.org"

shopt -s nullglob
set -- .*.metadata
if (( $# == 0 )); then
  echo "No metadata found"
  exit 13
elif (( $# > 1 )); then
  echo "Multiple metadata files found. Only using $1"
fi
mkdir -p SOURCES
metafile="$1"

while read -r sha name; do
  hashtype=$(hashdetect "${sha}")
  if [ "${hashtype}" == "unknown" ]; then
    echo "Failed: Unknown hash type"
    exit 1;
  fi
  #if ! which "${hashtype}" > /dev/null 2>&1; then
  #  echo "Failed: you need ${hashtype} in your PATH" >&2
  #  exit 1
  #fi
  if [ ! -e "${name}" ]; then
    curl -L -q -H Pragma: -o "${name}" -R -S --fail --retry 5 "${SURL1}/${sha}" --write-out "%{http_code}" || \
    curl -L -q -H Pragma: -o "${name}" -R -S --fail --retry 5 "${SURL2}/${sha}" --write-out "%{http_code}"
  else
    echo "${name} already exists"
  fi
  sum=$(${hashtype} "${name}" | awk '{print $1}')
  if [ "${sha}" != "${sum}" ]; then
    echo "Failure: Hash does not match."
    exit 1;
  fi
done < "${metafile}"
