/* SPDX-License-Identifier: LGPL-2.1-only */
/*
 * mediatek_common.h - common definitions for Mediatek drivers
 *
 * Copyright (C) 2025 Iopsys Software Solutions AB. All rights reserved.
 */

#ifndef __MEDIATEK_COMMON_H__
#define __MEDIATEK_COMMON_H__

#include <stdio.h>
#include <ctype.h>
#include <linux/limits.h>

__attribute__ ((__format__(__printf__, 1, 2)))
static inline uint64_t
read_u64_from_file(const char *fmt, ...)
{
	char str[PATH_MAX] = { 0, };
	char *tmp;
	va_list ap;
	FILE *f;
	uint64_t res;

	va_start(ap, fmt);
	vsnprintf(str, sizeof(str), fmt, ap); /* Flawfinder: ignore */
	va_end(ap);

	if ((f = fopen(str, "r")) == NULL)
		return 0;

	tmp = fgets(str, sizeof(str), f);
	fclose(f);
	if (tmp == NULL)
		return 0;

	res = strtoll(str, &tmp, 10);
	if (tmp == str || (*tmp != 0 && !isspace(*tmp)))
		return 0;

	return res;
}

#define read_int_from_file(_fmt, ...) (int)read_u64_from_file(_fmt, ##__VA_ARGS__)

static inline int iface_to_phy_index(const char *ifname)
{
	return read_int_from_file("/sys/class/net/%s/phy80211/index", ifname);
}

static inline int phy_name_to_index(const char *phyname)
{
	return read_int_from_file("/sys/class/ieee80211/%s/index", phyname);
}

static inline int get_phyname(const char *ifname, char *phy)
{
	int index = read_int_from_file("/sys/class/net/%s/phy80211/index", ifname);
	sprintf(phy, "phy%d", index);
	return 0;
}

#endif
