#!/bin/sh

set -exu

# sources.list entries on debci look like this:
# deb http://deb.debian.org/debian-debug testing-debug main contrib non-free
# deb http://deb.debian.org/debian-debug unstable-debug main contrib non-free
# deb http://deb.debian.org/debian experimental main
# deb http://deb.debian.org/debian unstable main contrib non-free
# deb http://debian.osuosl.org/debian testing main contrib non-free
# deb http://debian.osuosl.org/debian unstable main contrib non-free
# deb-src http://deb.debian.org/debian-debug testing-debug main contrib non-free
# deb-src http://deb.debian.org/debian-debug unstable-debug main contrib non-free
# deb-src http://deb.debian.org/debian experimental main
# deb-src http://deb.debian.org/debian unstable main contrib non-free
# deb-src http://debian.osuosl.org/debian testing main contrib non-free
# deb-src http://debian.osuosl.org/debian unstable main contrib non-free
for f in /etc/apt/sources.list /etc/apt/sources.list.d/*; do
	[ -e "$f" ] || continue
	echo >> "$1/$f"
	# this regex replaces the deb.debian.org and the debian.osuosl.org (on
	# s390x) parts of a sources.list with 127.0.0.1
	# Also filter out debian-debug, deb-src, contrib and non-free because
	# ./make_mirror.sh doesn't retrieve those.
	sed 's/^\(deb\(-src\)\?\) \(http:\/\/deb[a-z.]\+\)\(\/debian\(-debug\)\?\) \(\(stable\|testing\|unstable\|experimental\)\(-debug\)\?\) \(.*\)$/\1 http:\/\/127.0.0.1\4 \6 \9/' "$f" \
		| grep -v '/debian-debug [^ ]\+-debug ' \
		| grep -v '^deb-src ' \
		| sed 's/ contrib//;s/ non-free//;s/ non-free-firmware//' >> "$1/$f" || :
done

# debci filters by suite name like this
# Package: *
# Pin: release unstable
# Pin-Priority: 990
#
# Package: experimental-package
# Pin: release a=experimental
# Pin-Priority: 995
for f in /etc/apt/preferences.d/*; do
	[ -e "$f" ] || continue
	# we append instead of overwriting
	echo >> "$1/$f"
	cat "$f" >> "$1/$f"
done
