#!/usr/bin/env perl
use warnings;
use strict;
use feature 'switch';
use Net::Netrc;

sub usage {
	print "Usage: $0 <operation>\n";
	exit 2;
}

sub lookup {
	my $res = Net::Netrc->lookup(@_);
	return defined $res->{machine} ? $res : undef;
}

sub find_best {
	my (%attr) = @_;

	my $res;

	if (!$res and defined $attr{protocol}) {
		$res = lookup($attr{protocol}.'@'.$attr{host}, $attr{username});
	}
	if (!$res) {
		$res = lookup($attr{host}, $attr{username});
	}
	if (!$res and defined $attr{protocol}) {
		$res = lookup($attr{protocol}.'@'.$attr{host});
	}
	if (!$res) {
		$res = lookup($attr{host});
	}

	if ($res) {
		return (username => $res->login,
			password => $res->password);
	} else {
		return;
	}
}

my $op = shift(@ARGV) // usage();

my %attr = map {chomp; split(/=/, $_, 2)} grep {/=/} <STDIN>;

if ($op eq "get") {
	my %cred = find_best(%attr);
	@attr{keys %cred} = map {$_ // ""} values %cred;
	print "$_=$attr{$_}\n" for sort keys %attr;
}
