#! /usr/bin/perl -w
# (@) $Header: /auto/homes/pb22/pl/RCS/getent-update.pl,v 1.1 2016/06/17 09:58:39 pb22 Exp pb22 $
# ensure that a non LDAP host has up to date LDAP derived data
use strict;

my ($orig, $pref, $suff);
my $ldapentpat = '^[a-z0-9]+:\*:\d+'; # what an ldap entry looks like
my $src = "/etc"; $src = "/tmp" if -e "/tmp/group"; # TEST!!!
my $dst = $src;

# If no arguments, do something sensible.
@ARGV = ("passwd", "group") if $#ARGV < 0;

while (my $type = shift) {
	die("$0: expected argument is passwd or group\n") unless $type =~ /^(passwd|group)$/;

	$orig = $pref = $suff = '';

	# Read the existing file. Save what it held, and the non '*' entries
	&read_orig($type);

	# Read the new info. Ignore any non '*' entries.
	&read_new($type);
	
	# See if the result is different:
	my $new = $pref . $suff;
	next if $new eq $orig;
	
	print STDERR "# Changed $dst/$type...\n";
	&install($type, $new);
}

# All done! code should be 0.
exit;

# Read the original local info
sub read_orig {
	my ($type) = @_;
	my $in = "$src/$type";
	open(IN, $in) || die("$0: failed to open '$in': $!\n");
	while (<IN>) {
		$orig .= $_;
		next if /$ldapentpat/;
		$pref .= $_;
	}
	close(IN) || die("$0: failed to close $in: $!\n");
}

# Read the new LDAP info
sub read_new {
	my ($type) = @_;
	my $in = "curl -#f sysdata/cgi-bin/getent?$type|";
	open(IN, $in) || die("$0: failed to open '$in': $!\n");
	while (<IN>) {
		next unless /$ldapentpat/;
		$suff .= $_;
	}
	close(IN) || die("$0: failed to close $in: $!\n");
}

# Install the new file: create $file-t then overwtite in place
sub install {
	my ($type, $new) = @_;
	my $out = "$dst/$type";
	my $outt = $out . "-t";
	unlink($outt);
	open(OUT, ">" . $outt) || die("$0: failed to open '$outt': $!\n");
	print OUT $new;
	close(OUT) || die("$0: failed to close '$outt': $!\n");
	system("mv -v $outt $out") && exit($!);
}
