#!/bin/sh

for f in $(find /etc/apt/sources.list /etc/apt/sources.list.d -follow -type f \( -name '*.list' -o -name '*.sources' \) -print)
do
	# filename preceded by '# ':
	printf '%s\n' "# $f"

	case "$f" in
		*.list)
			# just data lines
			< "$f" sed -ne '/^[ \t]*[^ \t#]/p'
		;;
		*.sources)
			# just data lines and empty separator line(s) that matter
			sed -ne '

				# initial state
				# if we get data line, print it and branch to label p:
				/^[ \t]*[^ \t#]/{
					p
					bp
				}
				# otherwise delete line and start next cycle:
				d

				:p
				# our last output was to print data line, get next line
				n
				# if we get data line, print it and branch to label p
				/^[ \t]*[^ \t#]/{
					p
					bp
				}
				# if we get empty line, put it in hold space and branch to label e
				/^$/{
					h
					be
				}
				# branch to label p (we got a non-empty non-data line)
				bp

				:e
				# got empty line after printed data line, get next line
				n
				# if we get data line, exchange with hold space (empty line),
				# print that, exchange again, print data line, branch to label p
				/^[ \t]*[^ \t#]/{
					x
					p
					x
					p
					bp
				}
				# branch to label e:
				be
			' < "$f"
		;;
	esac
done

#(for f in $(find /etc/apt/sources.list /etc/apt/sources.list.d -follow -type f \( -name '*.list' -o -name '*.sources' \) -print);do printf '%s\n' "# $f";case "$f" in *.list) < "$f" sed -ne '/^[ \t]*[^ \t#]/p';;*.sources) sed -ne '/^[ \t]*[^ \t#]/{p;bp;};d;:p;n;/^[ \t]*[^ \t#]/{p;bp;};/^$/{h;be;};bp;:e;n;/^[ \t]*[^ \t#]/{x;p;x;p;bp;};be' < "$f";;esac;done)
