#!/bin/bash

set -u

## HTTP GET
get() {
  local url="$1"; shift
  local out_dir="$1"; shift
  local out_file="${out_dir%/}/${url##*/}"

  if [ -s "$out_file" ]; then
    return 0
  fi

   wget --no-config \
    --no-verbose \
    --no-clobber \
    --output-document="$out_file" \
    "$url" \
  ;
  local ret="$?"
  if [[ $ret -eq 0 ]]; then
    echo "$out_file"
  else
    rm -f "$out_file"
  fi

  return "$ret"
}

## Check if URL or not
url_p() {
  [ -z "${1##*://*}" ]
}

vendor_source_url="https://devops.osstech.co.jp/source"

spec="$1"; shift
out_dir="${1-.}/"; ${1+shift}

/opt/osstech/bin/rpmspec-ls "$spec" \
|while read src; do \
  ## Try to download a cached source
  if url_p "$src"; then
    url="$vendor_source_url/${src##*/}"
  else
    url="$vendor_source_url/$src"
  fi
  get "$url" "$out_dir" && continue
  ret="$?"
  if ! url_p "$src"; then
    exit "$ret"
  fi

  ## Try to download the origin source
  url="$src"
  get "$url" "$out_dir" || exit $?
done
