#!/bin/bash

[% INCLUDE 'list_toolchain_updates-common-firefox-geckoview' %]

# ndk version
read -d '' p << 'EOF' || true
if (m/^\\s*NDK_VERSION\\s*=\\s*"(.+)"/) {
  print $1;
  exit;
}
EOF
needed=$(cat python/mozboot/mozboot/android.py | perl -ne "$p")
current='r[% pc("android-toolchain", "var/android_ndk_version") %][% pc("android-toolchain", "var/android_ndk_revision") %]'
check_update_needed ndk_version "$needed" "$current"


# build_tools
read -d '' p << 'EOF' || true
if (m/build_tools_version\\s*=\\s*"([^"]+)"/) {
  print $1;
  exit;
}
EOF
needed=$(cat build/moz.configure/android-sdk.configure | perl -ne "$p")
current='[% pc("android-toolchain", "var/version_33") %]'
check_update_needed build_tools "$needed" "$current"


# target_sdk
read -d '' p << 'EOF' || true
if (m/target_sdk_version\\s*=\\s*"(.+)"/) {
  print $1;
  exit;
}
EOF
needed=$(cat build/moz.configure/android-sdk.configure | perl -ne "$p")
current='[% pc("android-toolchain", "var/android_api_level_33") %]'
check_update_needed target_sdk "$needed" "$current"


# cmdline-tools
read -d '' p << 'EOF' || true
my $v, $s;
while (<>) {
  if (m/^\\s*CMDLINE_TOOLS_VERSION_STRING\\s*=\\s*"(.+)"/) {
    $s = $1;
  }
  if (m/^\\s*CMDLINE_TOOLS_VERSION\\s*=\\s*"(.+)"/) {
    $v = $1;
  }
  if ($v && $s) {
    print "$s-$v";
    exit;
  }
}
EOF
needed=$(cat python/mozboot/mozboot/android.py | perl -e "$p")
current='[% pc("android-toolchain", "var/commandlinetools_version_string") %]-[% pc("android-toolchain", "var/commandlinetools_version") %]'
check_update_needed cmdline-tools "$needed" "$current"


# min-android
read -d '' p << 'EOF' || true
use Path::Tiny;
use Digest::SHA qw(sha256_hex);
my $f;
my $min_indent;
foreach (path('build/moz.configure/android-ndk.configure')->lines_utf8) {
  if ($_ eq "def min_android_version(target):\\n") {
    $f = $_;
    next;
  } else {
    next unless $f;
  }
  m/^(\\s*)/;
  my $indent = length $1;
  $min_indent = $indent unless $min_indent;
  last if $indent < $min_indent;
  $f .= $_;
}
print substr(sha256_hex($f), 0, 10);
EOF
needed=$(perl -e "$p")
# We can't easily parse the min_android_version function.
# Instead we get a checksum of the function, and manually check it when
# it was updated.
# Current value of min_android_version is:
#  21 on aarch64, x86_64
#  16 on other archs
current=303de6de36
check_update_needed min-android "$needed" "$current"


# min_sdk
read -d '' p << 'EOF' || true
if (m/^\\s*min_sdk_version="[^"]+" if geckoview_lite else "([^"]+)"/) {
  print $1;
  exit;
}
EOF
needed=$(cat build/moz.configure/android-sdk.configure | perl -ne "$p")
current=21
check_update_needed min_sdk "$needed" "$current"


# gradle
read -d '' p << 'EOF' || true
if (m{distributionUrl=https\\\\://services.gradle.org/distributions/gradle-(.*)-(bin|all).zip}) {
  print $1;
  exit;
}
EOF
needed=$(cat gradle/wrapper/gradle-wrapper.properties | perl -ne "$p")
current='[% c("var/gradle_version") %]'
check_update_needed gradle "$needed" "$current"
