#! /bin/sh
#
# Copyright (C) 2012 Patrick "P. J." McDermott
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

MIRROR=http://ftp.us.debian.org/debian
DISTRIBUTION=sid
COMPONENT=main

main()
{
	get_orig_sources
	write_new_sources
	generate_patch
	rm -f Sources.orig Sources
}

get_orig_sources()
{
	url="${MIRROR}/dists/${DISTRIBUTION}/${COMPONENT}/source/Sources.bz2"
	curl -s "${url}" | bzcat >Sources.orig
}

write_new_sources()
{
	while IFS= read line; do
		if [ "${line#Package: }" != "${line}" ]; then
			pkg="${line#Package: }"
			printf '%s\n' "${line}"
			continue
		fi
		if [ -f "$(find_dsc "${pkg}")" ]; then
			if [ "${line#Build-*: }" != "${line}" ]; then
				continue
			fi
			if [ "${line#Architecture: }" != "${line}" ]; then
				get_field 'Build-Depends' "${pkg}"
				get_field 'Build-Depends-Indep' "${pkg}"
				get_field 'Build-Conflicts' "${pkg}"
				get_field 'Build-Conflicts-Indep' "${pkg}"
				printf '%s\n' "${line}"
				continue
			fi
		fi
		printf '%s\n' "${line}"
	done <Sources.orig >Sources
}

generate_patch()
{
	diff -U 6 Sources.orig Sources >Sources.patch
}

find_dsc()
{
	echo "../pkgs/${1}/${1}_"*.dsc
}

get_field()
{
	_field="${1}"
	_pkg="${2}"
	_dsc="$(find_dsc "${_pkg}")"

	_found=false
	while IFS= read _line; do
		if [ "${_line#${_field}: }" != "${_line}" ]; then
			_found=true
			printf '%s\n' "${_line}"
			continue
		fi
		if ${_found}; then
			if [ "${_line# }" != "${_line}" ]; then
				printf '%s\n' "${_line}"
			else
				_found=false
			fi
			continue
		fi
	done <"${_dsc}"
}

main
