#!/usr/bin/perl

use strict;

push @INC, "/usr/local/comkit/latest/modules/libwom/";
require "masterheap.pl";
require "markup.pl";
require "parsers.pl";

if ($#ARGV < 0) {
    print STDERR "Specify file name.\n";
    exit;
}

my ($filename) = $ARGV[0];

if ( index($filename, '.plist') == -1 ) {
    $filename .= '.plist';
}

`mv $filename back.plist`;
`wget http://www.osirix.jp/nodelist/$filename`;

my $bufhash = {};
my $bufkey = '';
my $serialnumber = `getserial`;


my $now_ip0 = `ipconfig getifaddr en0`;
$now_ip0 =~ s/[\n\r]//g;
my $now_ip1 = `ipconfig getifaddr en1`;
$now_ip1 =~ s/[\n\r]//g;


my $path_plist = "/Users/osirix/Library/Preferences/com.rossetantoine.osirix.plist";

if ( -x $path_plist ) {
} else {
    $path_plist = "/Library/Preferences/com.rossetantoine.osirix.plist";
}

my $now_ae = `/usr/libexec/PlistBuddy -c "print AETITLE" $path_plist`;
my $now_port = `/usr/libexec/PlistBuddy -c "print AEPORT" $path_plist`;
my $sync = `/usr/libexec/PlistBuddy -c "print syncDICOMNodes" $path_plist`;
my $url = `/usr/libexec/PlistBuddy -c "print syncDICOMNodesURL" $path_plist`;



sub ROPEN {

        my ($path) = @_;
        local *FILE;

        my $succeed = open(FILE, $path);

        binmode FILE;
        return *FILE;
}


sub MLone {
    my ( $event, $tagaddr, $endtag, $taghash, $mh ) = @_;

#    print "MLone $event    $endtag  $tagaddr\n";
    if ( lc($endtag) eq 'dict' ) {
	&gotOneDict($bufhash);
	$bufhash = {};
    }

    if ( $event == 202 ) {

#	if ( $$taghash{'text'} eq '') { return 0; };

	foreach my $t ( sort(keys(%$taghash))) {
	    print STDERR "$endtag\t$tagaddr." . $t . "\t" . $$taghash{$t} ."\n";

	    if ( lc($endtag) eq 'key' ) {
		$bufkey = $$taghash{$t};
	    } else {
		$$bufhash{$bufkey} = $$taghash{$t};
	    }

	}

    }
    return 0;
}

sub gotOneDict {
    my ( $h ) = @_;

    my $ip0 = 'undef';
    my $ip1 = 'undef';

    if ( $serialnumber eq $$bufhash{'SN'} ) {
	$ip0 = $$bufhash{'Address'};
    } else {
	return;
    }

    print STDERR "-Current Settings-------------------------------\n";
    print STDERR "en0 = $now_ip0\n";
    print STDERR "en1 = $now_ip1\n";
    print STDERR "------------------------------------------------\n";
    foreach my $k ( keys(%$bufhash) ) {
	print STDERR $k . " = " . $$bufhash{$k}."\n";
    }
    print STDERR "------------------------------------------------\n";

    if ( $$bufhash{'Address0'} ne '' ) {
	$ip0 = $$bufhash{'Address0'};
    }

    if ( $$bufhash{'Address1'} ne '' ) {
	$ip1 = $$bufhash{'Address1'};
	if ($ip1 eq $ip0) {
	    $ip0 = 'undef';
	}
    }

    if ( $$bufhash{'Ethernet'} ne '' ) {
	print "networksetup -setmanual 'Ethernet' ".$$bufhash{'Ethernet'}." 255.255.255.0 ".$$bufhash{'Gateway'}."\n";
	print "networksetup -setdnsservers 'Ethernet' ".$$bufhash{'Gateway'}." 8.8.8.8\n";
    }

    if ( $$bufhash{'Wi-Fi'} ne '' ) {
	print "networksetup -setmanual 'Wi-Fi' ".$$bufhash{'Ethernet'}." 255.255.255.0 ".$$bufhash{'Gateway'}."\n";
	print "networksetup -setdnsservers ".$$bufhash{'Gateway'}." 8.8.8.8\n";
    }

    if ( $ip0 ne 'undef' ) {
	if ( $now_ip0 ne $ip0 ) {
#	    print "ifconfig en0 $ip0/24\n";
	}
    }

    if ( $ip1 ne 'undef' ) {
	if ( $now_ip1 ne $ip1 ) {
#	    print "ifconfig en1 $ip1/24\n";
	    print "networksetup -setmanual 'Ethernet' $ip1 255.255.255.0 ".$$bufhash{'Gateway'}."\n";
	}
    }

    my $hostname = `scutil --get ComputerName`;
    $hostname =~ s/[\n\r]//g;
    print "# current: computer name = $hostname\n";

    if ( $hostname ne $$bufhash{'Description'} ) {
	print "scutil --set ComputerName '".$$bufhash{'Description'}."'\n";
	print "scutil --set LocalHostName '".$$bufhash{'AETitle'}."'\n";
    }
	print "scutil --set LocalHostName '".$$bufhash{'AETitle'}."'\n";


    if ( $now_ae ne $$bufhash{'AETitle'} ) {
	print "/usr/libexec/PlistBuddy -c \"add AETITLE string $$bufhash{'AETitle'}\" $path_plist 2>/dev/null\n";
    }
    if ( $now_port ne $$bufhash{'AEPORT'} ) {
	print "/usr/libexec/PlistBuddy -c \"add AEPORT string $$bufhash{'Port'}\" $path_plist 2>/dev/null\n";
    }

    if ( $$bufhash{'WANPort'} ne '' ) {

	my $outer = $$bufhash{'WANPort'};

	my $local_ip_address = get_local_ip_address();

	print "/usr/local/bin/upnpc-static.mac -d $outer tcp\n";
	my $upnp = "/usr/local/bin/upnpc-static.mac -a $local_ip_address 22 $outer tcp";
	print $upnp."\n";

    }

}


# This idea was stolen from Net::Address::IP::Local::connected_to()
sub get_local_ip_address {
    my $socket = IO::Socket::INET->new(
        Proto       => 'udp',
        PeerAddr    => '198.41.0.4', # a.root-servers.net
        PeerPort    => '53', # DNS
	);

    # A side-effect of making a socket connection is that our IP address
    # is available from the 'sockhost' method
    my $local_ip_address = $socket->sockhost;

    return $local_ip_address;
}




# LOAD SPECIFIED TEXT FILE.

my $fh = &ROPEN( $filename );
my $delimiter = $/;
undef $/;
my $wholetext = <$fh>;
$/ = $delimiter;


my $mh = Masterheap->new();

&main::drivenML( $wholetext, \&main::parseHTML, \&main::MLone, $mh );

