package wol;

use warnings;
use strict;

use IO::Socket::INET;
use Regexp::Common qw/net/;
use CouchDB;

use client;
use server;

sub power_on {
	my $target = shift;

	my ( $port, $mac ) = ( 9 );

	if ( $target =~ m/$RE{net}{MAC}{-keep}/ ) {
		$mac = $1;
	} elsif ( $target =~ m/$RE{net}{IPv4}{-keep}/ ) {
		$mac = client::mac_from_ip $1;
	} else {
		die "$target isn't IP or MAC";
	}

	warn "# power_on $mac";

	my $sock = IO::Socket::INET->new( Proto=>'udp' );
	my $ip_addr = inet_aton($server::bcast);
	my $sock_addr = sockaddr_in($port, $ip_addr);

	my $mac_payload = $mac;
	$mac_payload =~ s{:}{}g;

	my $packet = pack('C6H*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, $mac_payload x 16);

	setsockopt($sock, SOL_SOCKET, SO_BROADCAST, 1);
	send($sock, $packet, 0, $sock_addr);
	close ($sock);

	CouchDB::audit( $target, { ip => $target, mac => $mac } );
}

1;
