#!/usr/bin/env perl
#
# danielbowling424@msn.com
# http://swagg.cc
#
# Copyright 2019 Daniel Bowling, Mount Rainier, Maryland, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# - current time of day in 64-bit NTP format (da_time)
# - obtain eui64
# - cat first with second
# - compute SHA-1 of third and use least significant 40 bits

use strict;
use warnings;
use DateTime;
use Digest::SHA qw(sha1_hex);

if ("$#ARGV" == "-1") {
    print "USAGE: $0 <MAC ADDRESS>\n";
    exit 64;
}

# current time of day

my $time = time();
my $offset = 2208988800;
my $epoch = $time + $offset;

# eui64

my $mac = "$ARGV[0]";
$mac =~ tr/A-F/a-f/;
my @fields = split /:/, $mac;
my $halfone = "$fields[0]" . "$fields[1]" . "$fields[2]" . "ff";
my $halftwo = "fe" . "$fields[3]" . "$fields[4]" . "$fields[5]";
my $binfield = sprintf("%b", hex("$fields[0]"));
my $decfield = sprintf("%d", hex("$fields[0]"));
if ($binfield =~ m/1[01]$/) {
    $decfield = $decfield - 2;
} else {
    $decfield = $decfield + 2;
}
$binfield = sprintf("%b", int("$decfield"));
my $hexfield = sprintf("%x", int("$decfield"));
$halfone = "$hexfield" . "$fields[1]" . "$fields[2]" . "ff";
my $fulleui = "$halfone" . "$halftwo";

# cat time

my $zeroes = ":/48";
my $digesty = sha1_hex("$epoch" . "$fulleui");
my $uniqueid = "fd" . substr("$digesty", -10);
$uniqueid =~ s/(.{1,4})/$1:/gs;
print "$uniqueid" . "$zeroes\n";
