/*
 * opkg_utils.c: OPKG utility functions
 *
 * Copyright (C) 2021-2023 IOPSYS Software Solutions AB. All rights reserved.
 *
 * Author: Vivek Dutta <vivek.dutta@iopsys.eu>
 *
 * See LICENSE file for license related information.
 */

/*
* Description: Opkg does not provide a library to interact with opkg packages,
*  utilities written in this file is to provide a wrapper functions.
*/

#include "opkg_utils.h"
#include "tools.h"  // run_cmd

int opkg_install_pkg(const char *pkg_name, char *output, int out_len)
{
	char command[1024] = {0};

	if (pkg_name == NULL)
		return 0;

	snprintf(command, sizeof(command), "opkg --force-depends --force-maintainer install %s 2>&1", pkg_name);

	return run_cmd(command, output, out_len);
}

int opkg_update_pkg(const char *pkg_name, char *output, int out_len)
{
	char command[1024] = {0};

	if (pkg_name == NULL)
		return 0;

	snprintf(command, sizeof(command), "opkg --force-depends --force-maintainer install %s 2>&1", pkg_name);

	return run_cmd(command, output, out_len);
}

int opkg_remove_pkg(const char *pkg_name, char *output, int out_len)
{
	char command[1024] = {0};

	if (pkg_name == NULL)
		return 0;

	snprintf(command, sizeof(command), "opkg --force-depends remove %s 2>&1", pkg_name);

	return run_cmd(command, output, out_len);
}

int opkg_get_version(const char *pkg_name, char *buffer, int buf_len)
{
	/* Get Description from package_name.control */
	char pkg_path[128] = {0};
	snprintf(pkg_path, sizeof(pkg_path), "%s/%s.control", OPKG_INFO_PATH, pkg_name);

	FILE *fp = fopen(pkg_path, "r");
	if (fp != NULL) {
		char line[256] = {0};
		char *spch = NULL;

		while (fgets(line, sizeof(line), fp) != NULL) {
			if ((spch = strstr(line, "Version:"))) {
				remove_new_line(spch);
				snprintf(buffer, buf_len, "%s", spch+9);
				break;
			}
		}

		fclose(fp);
	}

	return 0;
}
