#!/bin/bash

# This script will update the debian package with the latest content of
# the repo XML file
#
# It:
#  - updates "version_list.info"
#  - extracts all necessary information to file "version_list.txt"
#  - builds debian/control file
#  - builds debian/tests/control file

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

if [ "$1" = "latest" ]; then
  # Get the version of the latest orig.tar.xz
  TIMESTAMP="$(ls -t1 "../$(dpkg-parsechangelog -S Source)"*".orig.tar.xz" | head -n1 | cut -d _ -f2 | sed "s/\.orig.*//")"
  echo -e "\nBuilding d/version_list.info file... "

  echo "TIMESTAMP=$TIMESTAMP" > "debian/version_list.info"
  echo "TIMESTAMP_DATE=\"$(date -Iseconds -u -d@"$TIMESTAMP")\"" >> "debian/version_list.info"

  column  -s "=" -t debian/version_list.info
  #echo -e "\nUpdating d/changelog to version ${TIMESTAMP}-1... "
  #if [ ! $(dpkg-parsechangelog -S Version) = "${TIMESTAMP}-1" ]; then
  #  gbp dch -N "${TIMESTAMP}-1" ""
  #fi
fi

echo -en "\nBuilding d/version_list.txt file... "
debian/scripts/build_version_list.sh
echo "done"

echo -en "\nBuilding d/control file... "
debian/scripts/build_control_file.sh
echo "done"

echo -en "\nBuilding d/tests/control file... "
debian/scripts/build_tests_control_file.sh
echo "done"

echo
