#!/usr/bin/perl

# This script is a quick hack to convert DHCPDCONF data from the old format to
# the new format. This script acts as a pipe: it expects data on STDIN and will
# output to STDOUT.

use strict;
use warnings;
use Net::NetReg::Variables qw($DDNS_USE_HOST_DECL);

while (<>) {
    if (not /^(\#)?host\s/o) { print; next; }

    my ($PLATFORM, $DATE, $SUBNET, $BLDG, $USER, $MAC, $IP, $TYPE, $SERIAL, $EXPIRY, $REGISTRAR, $excess) = ('') x 20;
    chomp;
    $EXPIRY = $1 if s/\#(\d{4}-\d{2}-\d{2})$//o;
    # This is the (modified) $DHCPDCONF reader code from the old version.
    if (/^host\s.*\}\#/) {
        ($USER, $PLATFORM, $DATE, $SUBNET, $BLDG) = split /\#/;
        ($USER, $MAC, $IP, $excess) = (split /\s+|\#/, $USER, 11)[1,5,8,10];
        $SERIAL = $1 if $USER =~ /-(\d+)$/;;
        ($USER) = split /-(\d+)$/, $USER;
        $TYPE = "S";

        chop $excess; # Strip closing }
        $excess =~ s/^\s*(.*?)\s*$/$1/o; # Strip beginning & end whitespace
        if ($excess) {
            $excess =~ s/\s*;/;/go;
            $excess =~ s/ddns-hostname [^;]*;\s*//o;
        }
    }
    elsif (/^\#host\s.*\#/) {
        (undef, $USER, $MAC, $IP, $PLATFORM, $DATE, $SUBNET, $BLDG)
            = split /\#/;
        $USER =~ s/host\s(.*)-(\d+)$/$1/;
        $SERIAL = $2;
        $TYPE = "M";
    } else {
        print STDERR $_; next;
    }


    # Sanitize the data
    foreach (\$PLATFORM, \$DATE, \$SUBNET, \$BLDG, \$USER, \$MAC, \$IP, \$TYPE, \$SERIAL, \$EXPIRY) {
        $$_ = '' if not defined $$_;
    }
    if ($DATE =~ /^(\d{4})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2})$/) {
        $DATE = "$1-$2-$3T$4"; # ISO-8601 format
    } else {
        $DATE = '0000-00-00T00:00:00';
    }
    $USER = lc($USER);
    if ($BLDG eq 'Student') {
        $REGISTRAR = 'Self Registered';
        $BLDG = '';
    }


    # Build the host record
    my $hostrec = ($TYPE eq 'M' ? '#' : ''); # Manual registrations
    $hostrec .= "host $USER-$SERIAL { hardware ethernet " . lc($MAC) . '; ';
    $hostrec .= "fixed-address $IP; " if $TYPE =~ /^[SM]$/;
    $hostrec .= "ddns-hostname $USER-$SERIAL; " if $DDNS_USE_HOST_DECL;
    $hostrec .= $excess . " " if $excess;
    $hostrec .= '}#';
    $hostrec .= join('#', $PLATFORM, $REGISTRAR, $DATE, $SUBNET, $BLDG);
    $hostrec .= "#$EXPIRY" if $EXPIRY;

    print "$hostrec\n";
}
