#!/bin/bash

echo $0
set -e
set -x

debian_mirror=$1
export DEBIAN_FRONTEND=noninteractive

printf 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";\n' \
       > /etc/apt/apt.conf.d/99no-install-recommends

printf 'APT::Acquire::Retries "20";\n' \
       > /etc/apt/apt.conf.d/99acquire-retries

cat <<EOF > /etc/apt/apt.conf.d/99no-auto-updates
APT::Periodic::Enable "0";
APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Unattended-Upgrade "0";
EOF

printf 'APT::Get::Assume-Yes "true";\n' \
       > /etc/apt/apt.conf.d/99assumeyes

cat <<EOF > /etc/apt/apt.conf.d/99quiet
Dpkg::Use-Pty "0";
quiet "1";
EOF

cat <<EOF > /etc/apt/apt.conf.d/99confdef
Dpkg::Options { "--force-confdef"; };
EOF

echo "man-db man-db/auto-update boolean false" | debconf-set-selections

if echo $debian_mirror | grep '^https' 2>&1 > /dev/null; then
    apt-get update || apt-get update
    apt-get install ca-certificates
fi

cat << EOF > /etc/apt/sources.list
deb ${debian_mirror} bullseye main
deb https://security.debian.org/debian-security bullseye-security main
deb ${debian_mirror} bullseye-updates main
EOF
echo "deb ${debian_mirror} bullseye-backports main" > /etc/apt/sources.list.d/backports.list

apt-get update || apt-get update

# purge things that might come from the base box, but we don't want
# https://salsa.debian.org/cloud-team/debian-vagrant-images/-/tree/master/config_space/package_config
# cat config_space/package_config/* | sort -u | grep -v '[A-Z#]'
purge="
 apt-listchanges
 apt-utils
 bash-completion
 bind9-*
 bsdextrautils
 build-essential
 bzip2
 chrony
 cloud-utils
 cron
 dbus
 debconf-i18n
 debian-faq
 dmidecode
 doc-debian
 fdisk
 file
 groff-base
 krb5-locales
 less
 locales
 logrotate
 lsof
 manpages
 nano
 ncurses-term
 netcat-traditional
 pciutils
 reportbug
 rsyslog
 tasksel
 telnet
 traceroute
 unattended-upgrades
 vim-*
 wamerican
 wget
 whiptail
 xxd
 xz-utils
"
# clean up files packages to be purged, then purge the packages
rm -rf /var/run/dbus /var/log/unattended-upgrades
apt-get purge $purge

apt-get upgrade --download-only
apt-get upgrade

# again after upgrade in case of keyring changes
apt-get update || apt-get update

packages="
 apksigner
 default-jdk-headless
 default-jre-headless
 dexdump
 fdroidserver
 git-svn
 gnupg
 mercurial
 patch
 rsync
 sdkmanager
 sudo
"

apt-get install $packages --download-only
apt-get install $packages

# fdroidserver comes from git, it was installed just for dependencies
apt-mark manual `apt-cache depends fdroidserver | sed -nE 's,^[| ]*Depends: ([a-z0-9 -]+),\1,p'`
apt-get purge fdroidserver

# clean up things that will become outdated anyway
apt-get autoremove --purge
apt-get clean
rm -rf /var/lib/apt/lists/*

highestjava=`update-java-alternatives --list | sort -n | tail -1 | cut -d ' ' -f 1`
update-java-alternatives --set $highestjava
