#!/bin/sh
set -e

. /usr/share/debconf/confmodule

file="$1"

# Ensure ROOT default; allow override
: "${ROOT:=/target}"

# If Deb822 sources already exist in the target, keep legacy minimal and clean.
if [ -d "$ROOT/etc/apt/sources.list.d" ] && ls "$ROOT/etc/apt/sources.list.d/"*.sources >/dev/null 2>&1; then
    msg="# Trisquel sources have moved to /etc/apt/sources.list.d/trisquel.sources"
    # Temp file consumed by the generators pipeline (must exist, but keep it clean)
    printf '%s\n' "$msg" > "$file"
    # Ensure the target legacy file exists and contains only the breadcrumb
    printf '%s\n' "$msg" > "$ROOT/etc/apt/sources.list"
else
    # Fallback: add old file as comments (tolerant if missing)
    if [ -r "$ROOT/etc/apt/sources.list" ]; then
        sed 's/^/# /' < "$ROOT/etc/apt/sources.list" | sed 's/^# # */# /' > "$file"
    else
        : > "$file"
    fi
fi

# add old file as comments
sed 's/^/# /' < $ROOT/etc/apt/sources.list | sed 's/^# # */# /' > $file

# start out with old configuration, if any
if [ -e $ROOT/etc/apt/apt.conf ]; then
	cp -a $ROOT/etc/apt/apt.conf $ROOT/etc/apt/apt.conf.new
else
	>$ROOT/etc/apt/apt.conf.new
fi

chroot=
if [ "$ROOT" ]; then
	chroot=chroot
fi

db_get apt-setup/multiarch
if [ "$RET" ]; then
	for arch in $RET; do
		$chroot $ROOT dpkg --add-architecture "$arch"
	done
else
	for arch in $($chroot $ROOT dpkg --print-foreign-architectures); do
		$chroot $ROOT dpkg --remove-architecture "$arch"
	done
fi
