#!/bin/bash

# Usage: gradlew-retry [GRADLE-ARGUMENT...]
#
# Run ./gradlew (in the current directory) with the given arguments.  If that fails because Gradle
# could not resolve a dependency or plugin, and the failure looks transient, wait, then run
# ./gradlew again, by default up to 2 more times.  Exit with the status of the last run of
# ./gradlew.  Other failures, such as a compilation error, a test failure, a build that declares
# no repositories, or a 401 status code for bad credentials, are not retried.
#
# Environment variable GRADLEW_RETRY_DELAYS, if set, is a space-separated list of the number of
# seconds to wait before each retry, such as "60 180" (the default).  It also determines the
# number of retries.
#
# A resolution failure looks transient if Gradle reports a 5xx or 429 status code, a timeout, a
# refused or reset connection, or a failed TLS handshake.  A repository such as Maven Central also
# sometimes transiently fails to serve an artifact that it holds, for example by returning 404 for
# a minute or more.  A dependency or plugin that does not exist, such as a mistyped version or
# plugin id, also yields 404; to avoid pointless retries in that case, this script retries a 404
# only if the artifact exists, according to the URL where Gradle looked for it, the Gradle Plugin
# Portal, Maven Central, or a Google-hosted mirror of Maven Central.  This script consults the
# mirror only to make that decision; Gradle never downloads from it.  This script does not retry a
# failure to find a version that matches a dynamic version such as "1.+", because the existence of
# the module's list of versions does not show that a matching version exists.
#
# Each retry passes --refresh-dependencies to Gradle, because Gradle by default caches for 24 hours
# the fact that an artifact is missing, and would otherwise not ask the repository for it again.

# The prefix of each Maven Central URL that Gradle reports, and the corresponding prefix on the
# mirror.
central=https://repo.maven.apache.org/maven2/
mirror=https://maven-central.storage-download.googleapis.com/maven2/
# The prefix of each Gradle Plugin Portal URL.
plugin_portal=https://plugins.gradle.org/m2/

# Matches a line of Gradle output that reports a network failure that a retry might fix.
transient_regex='Received status code (5[0-9][0-9]|429)|[Tt]imed out|Connection reset|Connection refused|Remote host terminated the handshake|SSLHandshakeException|Premature end of'

log=$(mktemp)
trap 'rm -f "$log"' EXIT

# Return 0 (true) if the given URL serves a file.
url_exists() {
  curl --silent --fail --head --location --max-time 20 --output /dev/null "$1"
}

# Print, one per line, URLs of the pom file of the marker of each plugin that the run of Gradle
# that wrote $log reported as not found, on the Gradle Plugin Portal and on Maven Central.  A
# plugin whose version Gradle did not report is omitted.
plugin_marker_urls() {
  local id version path
  sed -n "s/.*Plugin \[id: '\([^']*\)', version: '\([^']*\)'[^]]*\] was not found.*/\1 \2/p" "$log" \
    | while read -r id version; do
      path="${id//.//}/$id.gradle.plugin/$version/$id.gradle.plugin-$version.pom"
      echo "$plugin_portal$path"
      echo "$central$path"
    done
}

# Return 0 (true) if the run of Gradle that wrote $log failed in a way that a retry might fix.
retry_might_help() {
  if ! grep -qE 'Could not resolve all |Plugin \[id: .*\] was not found' "$log"; then
    return 1
  fi
  if grep -qE "$transient_regex" "$log"; then
    echo "gradlew-retry: Gradle reported a network failure that a retry might fix."
    return 0
  fi
  # Gradle lists the URLs at which it did not find a module, one per line, as in
  # "       - https://repo.maven.apache.org/maven2/org/example/x/1.0/x-1.0.pom".
  # A maven-metadata.xml file or a directory lists a module's versions; its existence does not
  # show that a version that Gradle looked for exists, so such URLs are ignored.
  local urls
  urls=$({
    sed -n 's/^ *- \(https:\/\/[^ ]*\)$/\1/p' "$log"
    plugin_marker_urls
  } | grep -vE '/maven-metadata\.xml$|/$' | sort -u)
  if [ -z "$urls" ]; then
    echo "gradlew-retry: Not retrying, because the failure does not look transient."
    return 1
  fi
  local url
  for url in $urls; do
    if url_exists "$url"; then
      echo "gradlew-retry: $url exists."
      return 0
    fi
    case "$url" in
      "$central"*)
        if url_exists "$mirror${url#"$central"}"; then
          echo "gradlew-retry: $url exists on a mirror of Maven Central."
          return 0
        fi
        ;;
    esac
  done
  echo "gradlew-retry: Not retrying, because no missing artifact exists at a URL that Gradle"
  echo "  reported, on the Gradle Plugin Portal, or on a mirror of Maven Central."
  return 1
}

# Extra arguments to ./gradlew; empty for the first run.
refresh=()
for delay in ${GRADLEW_RETRY_DELAYS-60 180}; do
  ./gradlew "${refresh[@]}" "$@" 2>&1 | tee "$log"
  # Gradle's status, not that of `tee`.  If `tee` fails, the log may be incomplete, which at worst
  # prevents a retry.
  status=${PIPESTATUS[0]}
  if [ "$status" -eq 0 ] || ! retry_might_help; then
    exit "$status"
  fi
  echo "gradlew-retry: Gradle could not resolve a dependency; retrying in $delay seconds."
  sleep "$delay"
  refresh=(--refresh-dependencies)
done
# Not `exec`, so that the EXIT trap removes $log.
./gradlew "${refresh[@]}" "$@"
