/*
 * dpkg - main program for package management
 * pkg.c - primitives for pkg handling
 *
 * Copyright © 1995, 1996 Ian Jackson <ian@chiark.greenend.org.uk>
 * Copyright © 2009 Guillem Jover <guillem@debian.org>
 *
 * This 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 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, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <compat.h>

#include <string.h>

#include <dpkg/dpkg-db.h>
#include <dpkg/pkg.h>

/**
 * Compare a package to be sorted by name.
 *
 * @param a A pointer of a pointer to a struct pkginfo.
 * @param b A pointer of a pointer to a struct pkginfo.
 *
 * @return An integer with the result of the comparison.
 * @retval -1 a is earlier than b.
 * @retval 0 a is equal to b.
 * @retval 1 a is later than b.
 */
int
pkg_sorter_by_name(const void *a, const void *b)
{
	const struct pkginfo *pa = *(const struct pkginfo **)a;
	const struct pkginfo *pb = *(const struct pkginfo **)b;
	const char *arch_a = pa->installed.arch->name;
	const char *arch_b = pb->installed.arch->name;
	int res;

	res = strcmp(pa->set->name, pb->set->name);
	if (res)
		return res;

	if (pa->installed.arch == pb->installed.arch)
		return 0;

	/* Native arch sorts first */
	if (pa->installed.arch->type == arch_all ||
            pa->installed.arch->type == arch_native)
		arch_a = "";
	if (pb->installed.arch->type == arch_all ||
            pb->installed.arch->type == arch_native)
		arch_b = "";

	return strcmp(arch_a, arch_b);
}
