#!/bin/awk -f
#
# Copyright (C) 2000, 2003  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2010  Michael Shigorin <mike@altlinux.org>
#
# Update BuildRequires.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

BEGIN {
	found = 0;
	skipws = 0;
	processed = 0;
	printed = 0;
}

function	insert_reqs()
{
	if ( reqs != "" && printed > 0 )
	{
		printf( "# Automatically added by buildreq on %s", strftime("%a %b %d %Y") );
		if (stage != "" && stage != "c")
			printf( " (-b%s)", stage );
		if ( pruned != "" )
			printf( "\n# optimized out: %s", pruned );
		printf( "\nBuildRequires: %s\n\n", reqs );
		reqs = "";
	}
}

/^# Automatically added by (auto)?buildreq on /{
	if ( !processed )
	{
		insert_reqs();
		processed = 1;
		found = 1;
		skipws = 1;
	}
}

/^# optimized out: /{
	if ( !processed )
	{
		insert_reqs();
		processed = 1;
		found = 1;
		skipws = 1;
	}
}

/^BuildRequires:/{
	if ( !processed )
	{
		insert_reqs();
		if ( !found )
		{
			print $0;
			skipws = 0;
		}
		else
		{
			found = 0;
			skipws = 1;
		}
		processed = 1;
	}
}

/^[[:space:]]*$/{
	if ( !processed )
	{
		processed = 1;
		if ( !skipws )
			print;
		found = 0;
		skipws = 0;
	}
}

/^(%package|%description)/{
	if ( !processed )
	{
		insert_reqs();
	}
}

{
	if ( !processed )
	{
		print $0;
		found = 0;
		skipws = 0;
		printed++;
	}
	processed = 0;
}
