#!/bin/bash

set -e

SCRIPT_PATH=$(dirname "$0")

if [ ! "$(realpath "$SCRIPT_PATH")" = "$PWD/debian/scripts" ]; then
  echo "This script must be run from the package root dir (the path containing the debian/ dir)"
  exit 1
fi

source "$SCRIPT_PATH/_common_functions.sh"
source "$SCRIPT_PATH/_components_to_package.sh"

TMPFILE=$(mktemp -t google-installers-upgrade.XXX) || exit
# shellcheck disable=SC2064
trap "rm -f -- '$TMPFILE'" EXIT

# Extract info from XML
xsltproc "$SCRIPT_PATH/list_available_packages.xsl" "$(get_upstream_basename)" > "$TMPFILE"

# Manually add some lines
# We don't add them through a patch file to repository2-1.xml because if we update
# repository2-1.xml, it will impact the package.xml files which would then differ
# from the ones shipped by google.
echo "ndk;10.4		10.4	NDK (Side by side) r10e	android-sdk-license	1110915721	android-ndk-r10e-linux-x86_64.zip	f692681b007071103277f6edc6f91cb5c5494a32		patcher;v4	" >> "$TMPFILE"

# Manual import from "repository-12.xml"
echo "sdk-docs		24	Android SDK Documentation	android-sdk-license	419477967	docs-24_r01.zip	eef58238949ee9544876cb3e002f2d58e4ee7b5d			" >> "$TMPFILE"

if [ "$SKIP_OBSOLETE_PACKAGES" -eq 1 ]; then
  # We always want 'tools' although it is marked obsolete
  sed -i -e "/^tools\t\t/ s/\tobsolete\t/\t\t/" "$TMPFILE"
fi

if grep --perl-regexp "extras;google;auto\t\t2\.0.*77e3f80c2834e1fad33f56539ceb0215da408fab" "$TMPFILE" > /dev/null; then
  # Fix version of Android Auto to 2.0.0+really2.0 because upstream labeled 2.0rc2 as 2.0.2, and the final
  # release is labeled 2.0
  sed -i "s/extras;google;auto\t\t2\.0\t/extras;google;auto\t\t2.0.2+really2.0\t/" "$TMPFILE"
fi

# sort and write everything to debian/version_list.txt
echo "# This file is generated automatically by script in debian/scripts/$(basename "$0")" > "debian/version_list.txt"
echo "# Don't update this file manually." >> "debian/version_list.txt"

if grep "XS-With-Zips: yes" debian/control.in > /dev/null &&
  [ -f "debian/version_list.txt.single" ]; then
  cat "debian/version_list.txt.single" >> "debian/version_list.txt"
else
  sort -V "$TMPFILE" >> "debian/version_list.txt"
fi
