#!/bin/bash

## Copyright (C) 2019 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -x

set -e

true "INFO: (hardcoded) this script is: help-steps/repo_download_script"
true "INFO:  This script is supposed to be either executed:"
true "INFO: - by cowbuilder which is expected to run as root (sudo), or"
true "INFO: - using root (sudo)."
true "INFO: \$0: $0 | \$@; $@"

if [ "$(id -u)" != "0" ]; then
   echo "ERROR: This must be run as root (sudo)!"
   exit 1
fi

test -f "$if_no_pbuilder_base_folder/tmp/temporary-repository/newer.list"

cat "$if_no_pbuilder_base_folder/tmp/temporary-repository/newer.list"

true "APTGETOPT_ALT: $APTGETOPT_ALT"

## Delete the binary version in case it is there.
rm -f "/etc/apt/trusted.gpg.d/newer.asc"

if [ -f "$if_no_pbuilder_base_folder/tmp/temporary-repository/repo_signing_key.asc" ]; then
   cp --verbose "$if_no_pbuilder_base_folder/tmp/temporary-repository/repo_signing_key.asc" "/etc/apt/trusted.gpg.d/newer.asc"
   ## Fix for:
   ## The key(s) in the keyring /etc/apt/trusted.gpg.d/newer.asc are ignored as the file is not readable by user '_apt' executing apt-key.
   chmod o+r "/etc/apt/trusted.gpg.d/newer.asc"
   ## Debugging.
   gpg --keyid-format long --import --import-options show-only --with-fingerprint "/etc/apt/trusted.gpg.d/newer.asc"
fi

if [ "$temp_newer_packages" = "" ]; then
   echo "ERROR $0: temp_newer_packages is empty!"
   exit 1
fi

pushd "$temp_newer_packages"

## Use dpkg multiarch so we can download other architectures than the build host's one using apt-get.
for architecture in $architecture_list ; do
   dpkg --add-architecture "$architecture"
done

apt-get \
   $APTGETOPT_ALT \
   $apt_unattended_opts \
   -o Dir::Etc::sourcelist="$if_no_pbuilder_base_folder/tmp/temporary-repository/newer.list" \
   -o Dir::Etc::sourceparts="-" \
   update

# apt-cache \
#    $APTGETOPT_ALT \
#    $apt_unattended_opts \
#    -o Dir::Etc::sourcelist="$if_no_pbuilder_base_folder/tmp/temporary-repository/newer.list" \
#    -o Dir::Etc::sourceparts="-" \
#    show $newer_package_list || true

#apt-config \
   #$APTGETOPT_ALT \
   #$apt_unattended_opts \
   #-o Dir::Etc::sourcelist="$if_no_pbuilder_base_folder/tmp/temporary-repository/newer.list" \
   #-o Dir::Etc::sourceparts="-"
   #dump

#ls /var/lib/apt/lists/

apt-get \
   $APTGETOPT_ALT \
   $apt_unattended_opts \
   -o Dir::Etc::sourcelist="$if_no_pbuilder_base_folder/tmp/temporary-repository/newer.list" \
   -o Dir::Etc::sourceparts="-" \
   download \
   $newer_package_list

if [ "$download_source_package" = "true" ]; then
   apt-get \
      $APTGETOPT_ALT \
      $apt_unattended_opts \
      --yes \
      --download-only \
      -o Dir::Etc::sourcelist="$if_no_pbuilder_base_folder/tmp/temporary-repository/newer.list" \
      -o Dir::Etc::sourceparts="-" \
      source \
      $newer_package_list
fi

popd
