#!/usr/bin/env bash

set -euo pipefail

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROPERTIES_FILE="$APP_DIR/gradle/wrapper/gradle-wrapper.properties"
GRADLE_USER_HOME="${GRADLE_USER_HOME:-$HOME/.gradle}"

if [[ ! -f "$PROPERTIES_FILE" ]]; then
  echo "Missing $PROPERTIES_FILE" >&2
  exit 1
fi

distribution_url=""
while IFS='=' read -r key value; do
  case "$key" in
    distributionUrl)
      distribution_url="${value//\\:/:}"
      ;;
  esac
done < "$PROPERTIES_FILE"

if [[ -z "$distribution_url" ]]; then
  echo "Unable to read distributionUrl from $PROPERTIES_FILE" >&2
  exit 1
fi

gradle_version="${distribution_url##*/gradle-}"
gradle_version="${gradle_version%-bin.zip}"
gradle_version="${gradle_version%-all.zip}"

dists_dir="$GRADLE_USER_HOME/wrapper/dists/gradle-${gradle_version}-bin"

shopt -s nullglob
for candidate in "$dists_dir"/*/gradle-"$gradle_version"; do
  if [[ -x "$candidate/bin/gradle" ]]; then
    exec "$candidate/bin/gradle" "$@"
  fi
done

download_dir="$dists_dir/manual/gradle-$gradle_version"
if [[ ! -x "$download_dir/bin/gradle" ]]; then
  mkdir -p "$dists_dir/manual"
  tmp_zip="$(mktemp)"
  cleanup() { rm -f "$tmp_zip"; }
  trap cleanup EXIT

  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$distribution_url" -o "$tmp_zip"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$tmp_zip" "$distribution_url"
  else
    echo "curl or wget is required to download Gradle" >&2
    exit 1
  fi

  unzip -q "$tmp_zip" -d "$dists_dir/manual"
fi

exec "$download_dir/bin/gradle" "$@"
