File update-sources.sh of Package dash-core

#!/bin/bash

set -e

update_specfile () {
  local specfile
  for specfile in "$@"; do
    (
      local tmpdir=$(mktemp -d)
      local srcurl=$(spectool -s 0 -lf "$specfile" | sed 's/^Source[0-9]*: *//')
      local srcfile="${srcurl##*/}"
      local srcdir="${srcfile%.tar*}"
      curl -s -L -o "${tmpdir}/${srcfile}" "${srcurl}"
      tar xCf "$tmpdir" "${tmpdir}/${srcfile}"
      git -C "${tmpdir}/${srcdir}" init -q
      git -C "${tmpdir}/${srcdir}" config user.name rpm-build
      git -C "${tmpdir}/${srcdir}" config user.email '<rpm-build>'
      git -C "${tmpdir}/${srcdir}" add .
      git -C "${tmpdir}/${srcdir}" commit -q -a --author 'rpm-build <rpm-build>' -m 'dash-core base'
      spectool -P -lf "$specfile" |
      sed -e '/^Source[0-9]*:/d' -e 's/^Patch[0-9]*: *//' |
      while read patch; do
        cat "$patch" | git -C "${tmpdir}/${srcdir}" am -q
      done
      local packages=$(make -s -C "${tmpdir}/${srcdir}/depends" -f <(cat <<'EOF'
include Makefile
duplicated_packages = protobuf native_b2
list_packages:; @echo $(filter-out $(duplicated_packages),$(all_packages))
EOF
      ) list_packages)
      sed -n -e '1,/^# Autogenerated section begin\. Do not edit\.$/p' "$specfile"
      n=200
      for package in $packages; do
        make -s -C "${tmpdir}/${srcdir}/depends" -f <(cat <<EOF
package=${package}
fetch_file=echo "\$(2)/\$(3)\$(shell test '\$(3)' != '\$(4)' && echo '#/\$(4)')"
include packages/${package}.mk
${package}_download_file?=\$(${package}_file_name)
${package}_download_path_fixed=\$(subst :,\:,\$(${package}_download_path))
${package}_fetch_cmds?=\$(call fetch_file,${package},\$(subst \:,:,\$(${package}_download_path_fixed)),\$(${package}_download_file),\$(${package}_file_name),\$(${package}_sha256_hash))
show_url:; @\$(call ${package}_fetch_cmds)
EOF
        ) show_url
      done |
      while read url; do
	echo "Source$n:      $url"
        n=$((n + 1))
      done
      sed -n -e '/^# Autogenerated section end\.$/,$p' "$specfile"
      rm -rf "$tmpdir"
    ) > "$specfile.tmp" && mv "$specfile.tmp" "$specfile"
  done
}

if [ $# -gt 0 ]; then
  update_specfile "$@"
else
  update_specfile *.spec
fi