/ag-import
#!/usr/bin/perl
use strict;

use AwesomeGrid;
use AwesomeGrid::Config;
use AwesomeGrid::User;
use AwesomeGrid::Keyring;

use File::Copy;

my @files = @ARGV;
my $pwd = `pwd`; chomp $pwd;
mkdir "$AwesomeGrid::confdir/users.new";
chdir "$AwesomeGrid::confdir/users.new";

my @trusted = AwesomeGrid::Config::trusted();

END {system('stty echo')}
system('stty -echo');
print STDERR "GPG Passphrase: ";
my $passphrase = <STDIN>;
system('stty echo');
print "\n";

for my $f (@files) {
	AwesomeGrid::Keyring::gpgpass($passphrase, qq!--decrypt "$pwd/$f" | tar xfz -!);

	opendir USERS, ".";
	my @users = grep {/^[^.]/} readdir USERS;
	closedir USERS;
	
	for my $u (@users) {
		my $agu = AwesomeGrid::User->loadfrom($u);
		unless ($agu) {
			print "Unusable user info: $u\n";
			unlink $u;
			next;
		}
		unless (grep { $_ eq $agu->{home} } @trusted) {
			print "Refusing to import ",$agu->{username}," from untrusted system ",$agu->{home},"\n";
			unlink $u;
			next;
		}
		if (AwesomeGrid::User::exists($u)) {
			print "$u exists. Overwrite? [y/N] ";
			my $ans = <STDIN>; chomp $ans;
			if ($ans !~ /^[Yy]$/) {
				unlink $u;
				next;
			}
		}
		move $u, "$AwesomeGrid::confdir/users/"
			|| die "Could not write to $AwesomeGrid::confdir/users/";
		print "Imported $u\n";
	}
}

chdir $pwd;
rmdir "$AwesomeGrid::confdir/users.new";