#!/bin/env perl

use strict;
use warnings;
use File::Temp qw(tempfile);

my %jpass;
my %shell;

sub set_pass {
    my ($user, $pass) = @_;
    $pass eq 'x' and return;
    $pass eq '!!' and return;
    $pass eq 'CLOSED' and return;
    $jpass{$user} ||= $pass;
}


my $ssh1 = open (my $fh, "ssh thauvin\@sirocco.aero.jussieu.fr 'ypcat passwd' |") or die "can't ssh sirocco";
while (my $line = <$fh>) {
	chomp($line);
	my @ch = split(':', $line);
	set_pass $ch[0], $ch[1];
}
close($fh) or die "ssh exit with error on sirroco";


my $ssh3 = open (my $sfh, "ssh thauvin\@savtcp.aerov.jussieu.fr 'ypcat passwd' |") or die "can't ssh savtcp";
while (<$sfh>) {
	chomp;
	my @ch = split(':', $_);
	set_pass $ch[0], $ch[1];
    $shell{$ch[0]} = $ch[6];
}
close($sfh) or die "ssh exit with error on savtcp";

my $ssh2 = open (my $pfh, "ssh thauvin\@python.latmos.ipsl.fr 'ypcat passwd' |") or die "can't ssh python";
while (my $line = <$pfh>) {
    chomp($line);
    my @ch = split(':', $line);
	set_pass $ch[0], $ch[1];
    $shell{$ch[0]} ||= $ch[6];
}
close($pfh) or die "ssh exit with error on python";;

require Data::Dumper;
warn Data::Dumper::Dumper { var => \%jpass };

open (my $lpfh, '<', 'passwd') or die "Can't open passwd";
while (my $line = <$lpfh>) {
    chomp($line);
    my @var = split(':', $line);
    $var[1] = $jpass{$var[0]} || 'x';
    $var[5] = "/net/nfs/home/$var[0]"; # Force home directory
    $var[6] = $shell{$var[0]};
    print join(':', @var) . "\n";
}
