#include "src/lib.h"

int send_wol(const char *interface, unsigned char *buf, int len) {
	struct sockaddr_ll sll;
	struct ifreq ifr;
	int sock, arp_source_ip, arp_target_ip;

	if((sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
		perror("socket");
		return 1;
	}

	memset(&ifr, 0x00, sizeof(ifr));

	strcpy(ifr.ifr_name, interface);
	if(ioctl(sock, SIOCGIFINDEX, &ifr) < 0 ) {
		perror("ioctl ");
		return 1;
	}

	memset(&sll, 0x00, sizeof(sll));
	sll.sll_family = PF_PACKET;
	sll.sll_ifindex = ifr.ifr_ifindex;
	sll.sll_protocol = htons(ETH_P_ALL);

	if(sendto(sock, buf, len, 0,
    (struct sockaddr *)&sll, sizeof(sll)) < 0) {

    perror("sendto ");
	}

	return 0;
}

void make_ether_packet(char *buf, const char *dstmac) {
  struct ether_header *ether_header = (struct ether_header *)buf;
  const char broadmac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
  const char srcmac[6] = {0x00, 0x90, 0x27, 0x85, 0xcf, 0x01};

  memcpy(ether_header->ether_dhost, broadmac, 6);
  memcpy(ether_header->ether_shost, srcmac, 6);

  ether_header->ether_type = htons(0x0842);
}

void make_wol_packet(char *buf, const char *dstmac) {
  int offset = 0;
  const char broadmac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

  memcpy(buf, broadmac, sizeof(broadmac));

  offset += sizeof(broadmac);

  for (int i=0; i<16; i++) {
    memcpy(buf + offset, dstmac, 6);

    offset += 6;
  }
}
