#!/usr/bin/perl
use strict;
use warnings;
#our $basedir=".";

use WWW::Mechanize;
use Carp;
#push(@INC,$basedir);
use Getopt::Long qw(:config no_ignore_case);

my $pass; # = undef;
my $user; # = undef;
my @users;
my $url = "https://account.dyn.com/entrance/";

sub do_login($$$);

my $HOME = $ENV{"HOME"};

GetOptions ("u|user=s" => \$user,
            "p|pass=s" => \$pass,
            "U|url=s"  => \$url,
) || die;

if (defined $pass) {
	print "Warning: password can be read on process list\n";
	push(@users, [$user, $pass]) if defined $user;
} else {
	if (!open(L, '<', "$HOME/.config/dyndns.pass")) {
		die "can't open $HOME/.config/dyndns.pass";
	};
	while (<L>) {
		chomp;
		next if /^#/ || /^\s*$/;
		my @l = split(/\s+/);
		if (@l != 2) {
			die "expecting lines like 'user pass' in $HOME/.config/dyndns.pass";
		}
		next if (defined $user && $user ne $l[0]);
		push(@users, [@l]);
	}
}

if (!@users) {die "$0 -u user -p pass [ -U URL ]"};

my $errors = 0;
my $ok = 0;
for my $u (@users) {
	do_login($url, $u->[0], $u->[1])? $errors++ : $ok++;
}
print "$errors errors\n" if "$errors";
print "$ok updates\n";

sub do_login($$$) {
	my ($url, $user, $pass) = @_;

	my $mech = WWW::Mechanize->new(onerror => \&croak, autocheck => 1, env_proxy => 1);
	$mech->agent_alias("Windows IE 6");

	$mech->get($url);

	my $fn = 1 * @{$mech->forms};
	my $F;
	for (my $f=0; $f < $fn; $f++) {
		my $form = $mech->forms->[$f];
		for my $i ($form->inputs) {
			if ($i->type eq "submit"
			&&  $i->value eq "Log in") {
				$F = $f;
				last;
			}
		}
		last if defined $F;
	};
	if (defined $F) {
		$mech->submit_form(
			form_number => $F,
			fields => {
				username    => $user,
				password    => $pass,
			},
		);
	};
	if (grep {($_->[1]||'') =~ /Log Out/} $mech->links) {
		print "OK user $user on $url\n";
	} else {
		print "Login failed user $user on $url\n";
		return 42;
	}
	return 0;
};
