#!/bin/bash

# SPDX-FileCopyrightText: 2013 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@kicksecure.com>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

## requires running apt-cacher-ng

set -x
set -e

if [ ! "$(id -u)" = "0" ]; then
   true "ERROR: Must be run with root (sudo)! sudo $0" >&2
   exit 1
fi

if grep -q "AllowUserPorts: 0\$" /etc/apt-cacher-ng/acng.conf ; then
   true "INFO: 'AllowUserPorts: 0' already in /etc/apt-cacher-ng/acng.conf, ok."
else
   true "INFO: Adding 'AllowUserPorts: 0' to /etc/apt-cacher-ng/acng.conf"
   echo "AllowUserPorts: 0" | tee -a "/etc/apt-cacher-ng/acng.conf" >/dev/null
   systemctl restart apt-cacher-ng.service
fi

create_img() {
   sudo -u "$SUDO_USER" mkdir -p "/home/$SUDO_USER/grml-debootstraptestbin"

   VMSIZE=2G

   export DEBUG="true"

   #export KERNEL="linux-image-amd64"

   export FSCK='yes'
   export TIMEZONE='UTC'
   export RM_APTCACHE='no'
   export UPGRADE_SYSTEM='no'
   export FIXED_DISK_IDENTIFIERS='yes'

   export DEBOOTSTRAP=mmdebstrap
   export INITRD_GENERATOR=dracut
   export http_proxy=http://127.0.0.1:3142
   export INITRD_GENERATOR_OPTS='--add dmsquash-live'

   sudo cp --verbose ./packages-custom /etc/debootstrap/packages-custom

   bash -x \
      grml-debootstrap \
         --arch amd64 \
         --filesystem ext4 \
         --force \
         --hostname host \
         --mirror http://HTTPS///deb.debian.org/debian \
         --keep_src_list \
         --password changeme \
         --release trixie \
         --verbose \
         --vmfile \
         --vmsize "$VMSIZE" \
         --vmefi \
         --packages packages-custom \
         --target "/home/$SUDO_USER/grml-debootstraptestbin/test.img"

   chown --recursive $SUDO_USER:$SUDO_USER /home/$SUDO_USER/grml-debootstraptestbin
}

create_img
