#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <vector>
#define _T(s) s
#include "Internal.h"

bool TwitchInGames::GetMacAddress(unsigned short* macAddress) {
	// Initialize the management information base data.
	auto en0 = static_cast<int>(if_nametoindex("en0"));
	int mgmtInfoBase[6] = {
		CTL_NET,       // network subsystem
		AF_ROUTE,      // routing table information
		0,
		AF_LINK,       // link layer information
		NET_RT_IFLIST, // all configured interfaces
		en0,           // handle index
	};
	if(mgmtInfoBase[5] == 0) {
		return false;
	}

	// Get the available system data.
	size_t size;
	if(sysctl(mgmtInfoBase, 6, nullptr, &size, nullptr, 0) < 0) {
		return false;
	}
	std::vector<char> msgBuffer(size);
	if(sysctl(mgmtInfoBase, 6, &msgBuffer[0], &size, nullptr, 0) < 0) {
		return false;
	}

	// Copy the link layer address data to the output array.
	auto const* ifHeader = reinterpret_cast<if_msghdr const*>(msgBuffer.data());
	auto const* dlAddr = reinterpret_cast<sockaddr_dl const*>(ifHeader + 1);
	memcpy(macAddress, dlAddr->sdl_data + dlAddr->sdl_nlen, 6);

	return true;
}
