#!/bin/bash

# This script will get the repo XML file from googles server and create an orig.tar
# This XML is the same file is used by Google Android's SDK Manager

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"

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

UPSTREAM_URL="$(get_upstream_url)"
UPSTREAM_BASENAME="$(get_upstream_basename)"

echo "Downloading ${UPSTREAM_BASENAME}..."
wget -q --show-progress "${UPSTREAM_URL}" -O "$TMPDIR/${UPSTREAM_BASENAME}"
echo

GENERATION_DATE=$(grep "Generated on" "$TMPDIR/${UPSTREAM_BASENAME}" | sed "s/.*Generated on \(.*\) with.*/\1/")
if [ -z "$GENERATION_DATE" ]; then
  # In case XML doesn't have the "Generated on" comment, use the last-modified value of HTTP header
  last_modified="$(curl --silent --head last-modified "$UPSTREAM_URL" | grep -i "last-modified" | cut -d : -f 2-)"
  GENERATION_DATE="$last_modified"
fi
TIMESTAMP=$(date --date="$GENERATION_DATE" +%s)

CURRENT_TIMESTAMP="$(dpkg-parsechangelog --show-field Version)"
if dpkg --compare-versions "$TIMESTAMP" gt "$CURRENT_TIMESTAMP"; then
  echo "Current Debian version:   [$CURRENT_TIMESTAMP] $(date -Iseconds -u -d@"$(echo "$CURRENT_TIMESTAMP" | cut -d "-" -f 1)")"
  echo "Current upstream version: [$TIMESTAMP] $(date -Iseconds -u -d@"$TIMESTAMP")"
else
  echo "XML generation timestamp is not newer than last version in debian/changelog"
  exit
fi

echo

echo "Creating ../google-android-installers_$TIMESTAMP.orig.tar.xz"
tar --sort=name \
  --mtime="@${TIMESTAMP}" \
  --owner=0 --group=0 --numeric-owner \
  --pax-option=exthdr.name=%d/PaxHeaders/%f,delete=atime,delete=ctime \
  -C "$TMPDIR" \
  --transform "s,^,google-android-installers-$TIMESTAMP/," \
  -cJf "../google-android-installers_$TIMESTAMP.orig.tar.xz" "${UPSTREAM_BASENAME}"
echo "Done"
echo

echo
echo "New orig.tar.xz created. You should now import it with gbp import-orig or unpack it with uupdate"
