#!/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
  echo wget "$url"
   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_id="${VENDOR_RPM_VENDOR_ID:-osstech}"
vendor_rpmspec_ls_cmd="${VENDOR_RPM_VENDOR_RPMSPEC_LS_COMMAND-/opt/osstech/bin/$vendor_id-rpmspec-ls}"
vendor_source_url="${VENDOR_RPM_VENDOR_SOURCE_URL-https://devops.osstech.co.jp/source}"

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

"$vendor_rpmspec_ls_cmd" "$spec" \
|while read -r 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
